blib/lib/oEdtk/DBAdmin.pm untested

filter: Statementstmt 0.0% 0 / 2798 Branchbran 0.0% 0 / 918 Conditioncond 0.0% 0 / 1085 MC/DCmcdc 0.0% 0 / 620 Subroutinesub 0.0% 0 / 191 Podpod 0.0% 0 / 147 totaltotal 0.0% 0 / 5759 CC 460 SCAR 45.3
CC
460
Cov
0%
schema_Additive
600.0
csv_import
342.0
_load_csv_pg_copy
306.0
CRAP 92.8
1 package oEdtk::DBAdmin;
2  
3 use DBI;
4 use oEdtk::Config qw(config_read);
5 use oEdtk::logger qw(logger $LOGGERLEVEL $WARN2LOGGER);
6 use POSIX qw(strftime);
7 use Scalar::Util qw(looks_like_number);
8 use Digest::MD5 ();
9 use Time::HiRes qw(time);
10 use strict;
11 use Text::CSV;
12 use Encode qw(encode decode find_encoding);
13 use warnings;
14 use Data::Dumper qw(Dumper);
15  
16 # check sql : https://www.eversql.com
17 # SHOW CREATE DATABASE oEdtk;
18  
19 use Exporter;
20 our $VERSION = 2.1126;
21 our $VERSION_TXT = $VERSION =~ s/\./_/gr;
22 our @ISA = qw(Exporter);
23 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 my $_LOCAL_EDTK_WAITRUN = 0;
79 my $CONNECT_COUNT = 0;
80  
81 # Re-entrancy guards (package variables so `local` can scope them per call).
82 our $IN_ACHECK = 0; # acheck_db_admin_on_connect
83 our $IN_RECONCILE = 0; # db_reconcile_backup
84 our %_csv_import_type_cache;
85 my $_DB_ENGINE_CACHE;
86 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 use constant PG_COPY_SYNC_OFF =>
90 'SET LOCAL synchronous_commit = off'; # relax fsync for this transaction only
91 use constant PG_COPY_ANALYZE => 'ANALYZE %s'; # refresh planner stats after a bulk load
92 use constant PG_COPY_BLOCK_SIZE => 1 << 20; # bytes fed per pg_putcopydata call
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 use constant PG_COPY_LOCK_TIMEOUT => '5s'; # cap the lock wait for the deferral
98 use constant PG_DEFER_DEFAULT_RATIO => 0.1; # defer if incoming >= 10% of the table
99 use constant PG_DEFER_DEFAULT_MIN_ROWS => 10_000; # ... and at least this many rows
100 use constant PG_DEFER_SAMPLE_BYTES => 65_536; # header sample used to size the import
101 use constant PG_ANALYZE_TABLE_SHARE => 0.1; # ANALYZE only if rows added >= 10% (O5)
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 use constant PG_BURST_MO_DEFAULT => 50; # default threshold, in MiB; 0 disables ELT
108 use constant PG_BURST_BYTES_PER_MO => 1_048_576; # bytes per MiB
109 use constant PG_STG_PREFIX => 'edtk_stg_'; # staging table name prefix
110 use constant PG_BURST_MAINT_MEM => '256MB'; # maintenance_work_mem during an index rebuild
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 use constant ACQ_FIELD_LOT => 2; # mailing batch id (sub-batch)
116 use constant ACQ_FIELD_PLI => 7; # folded-item file name, "name_number"
117 use constant ACQ_FIELD_IDDEST => 11; # recipient id in the management system
118 use constant ACQ_FIELD_DTLOT => 25; # batch reception date (its year prefix)
119 use constant ACQ_FIELD_EXPED => 26; # mailing-out date (DATEEXPED)
120 use constant ACQ_FIELD_STATUS => 29; # acknowledgement status
121  
122 sub move_table {
123 &logger( 4,
124 "method oEdtk::DBAdmin::move_table is deprecated you should use oEdtk::DBAdmin::copy_table"
125 );
126  
127 copy_table(@_);
128 1;
129 }
130  
131 sub copy_table {
132 my ( $dbh, $table_source, $table_cible, $create_option ) = @_;
133 $create_option ||= "";
134  
135 # check if source is empty
136 my $sql_check_source = "SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END FROM " . $table_source;
137 my $sth = $dbh->prepare($sql_check_source);
138 do { local $sth->{PrintError} = 0; $sth->execute() }
139 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
140 my $result = $sth->fetchrow_array;
141 unless ($result) {
142 &logger( 4, "Source $table_source is empty, copy aborted" );
143 return 1;
144 }
145  
146 # preparing the data copy from source to target
147 &logger( 5, "Data from $table_source will be copyed into $table_cible" );
148  
149 if ( $create_option =~ /-create/i ) {
150 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 _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 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 _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 &logger( 6, "Insert DONE into $table_cible" );
174 1;
175 }
176  
177 sub _load_csv_mysql_local_infile {
178 my ( $dbh, $tablename, $fi, $params ) = @_;
179  
180 # read the header line: it holds the field names and the insert order
181 open( my $fh, '<', $fi ) or die "ERROR: Cannot open file \"$fi\": $!\n";
182 my $fields = <$fh>;
183 chomp($fields);
184 $fields =~ s/\"+//g;
185 close($fh);
186  
187 # H9 : validate the header columns before building the LOAD statement.
188 my ( $norm_id, $norm_table, @cols ) =
189 _norm_identifiers( $dbh, $tablename, [ split( /,/, $fields ) ] );
190 my $col_meta = _get_col_meta( $dbh, $norm_table, $norm_id );
191 my $unknown = keys %$col_meta ? _unknown_csv_columns( \@cols, $col_meta ) : [];
192 if (@$unknown) {
193 return (
194 -1,
195 &logger(
196 3,
197 "LOAD DATA: unknown column(s) " . join( ', ', @$unknown ) . " for table $tablename"
198 )
199 );
200 }
201  
202 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 . $params->{'quote_char'} . "' "
209 . " LINES TERMINATED BY '" . '\n' . "'"
210 . " IGNORE 1 LINES "
211 . "($fields)";
212 &logger( 7, $sql );
213  
214 ## OPTIONALLY ENCLOSED BY '"'
215 ## REPLACE
216  
217 &logger( 7, "_load_csv_mysql_local_infile trying : $sql" );
218  
219 my $count = _db_do_log( $dbh, $sql, "SQL execute failed", bind => [$fi] );
220  
221 if ( !defined $count || ( $count !~ m/^\d+$/ && $count ne '0E0' ) ) {
222 return ( -1, &logger( 3, "$count-ERROR LOAD INFILE-$@ $!" . ( $dbh->errstr // '' ) ) );
223 }
224  
225 # Refresh the planner statistics after the bulk load (parity with the PG COPY path).
226 eval { local $dbh->{PrintError} = 0; $dbh->do("analyze table $tablename"); 1 }
227 or &logger( 7, "_load_csv_mysql_local_infile: analyze table $tablename failed: $@" );
228  
229 my $rows = _count_csv_rows( $fi, $params );
230 &logger( 5, "bulk insert into $tablename via LOAD DATA LOCAL INFILE: $rows rows" );
231 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 sub _pg_csv_field {
241 my ( $val, $sep, $quo ) = @_;
242 return '' unless defined $val;
243 return $val
244 unless $val eq ''
245 || index( $val, $sep ) >= 0
246 || index( $val, $quo ) >= 0
247 || $val =~ /[\r\n]/;
248 ( my $esc = $val ) =~ s/\Q$quo\E/$quo$quo/g;
249 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 sub _pg_csv_row {
262 my ( $data, $cols, $sep, $quo, $blank_to_null, $col_size ) = @_;
263 my @out;
264 for my $i ( 0 .. $#{$cols} ) {
265 my $v = $data->[$i];
266 if ( defined $v ) {
267 if ( $v eq '' ) {
268 if ( $blank_to_null->[$i] ) {
269 &logger( 7, "clean_val: col '$cols->[$i]' numeric/date, '' => undef" )
270 if $LOGGERLEVEL >= 7;
271 $v = undef;
272 }
273 }
274 elsif ( $col_size->[$i] && length($v) > $col_size->[$i] ) {
275 &logger( 6,
276 "clean_val: col '$cols->[$i]' truncated from "
277 . length($v)
278 . " to $col_size->[$i] chars" )
279 if $LOGGERLEVEL >= 6;
280 $v = substr( $v, 0, $col_size->[$i] );
281 }
282 }
283 push @out, _pg_csv_field( $v, $sep, $quo );
284 }
285 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 sub _pg_csv_supplier {
299 my ( $fi, $params, $cols, $blank_to_null, $col_size, $count_ref, $enc, $src_enc ) = @_;
300 my $sep = $params->{'sep_char'};
301 my $quo = $params->{'quote_char'};
302  
303 open( my $fh, '<', $fi ) or die "ERROR: Cannot open file \"$fi\": $!\n";
304 my $csv = Text::CSV->new(
305 {
306 binary => 1,
307 sep_char => $sep,
308 quote_char => $quo
309 }
310 );
311 unless ( $csv->getline($fh) ) { # skip the header record
312 close($fh);
313 die "ERROR: cannot read header of \"$fi\"\n";
314 }
315  
316 my $closed = 0;
317 return sub {
318 return if $closed;
319 my $eof = 0;
320 my $bytes = 0;
321 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 while ( $bytes < PG_COPY_BLOCK_SIZE ) {
327 my $data = $csv->getline($fh);
328 if ( !defined $data ) {
329 unless ( $csv->eof ) {
330 die "CSV parse error near line "
331 . ( $$count_ref + 1 )
332 . " in \"$fi\": "
333 . ( $csv->error_diag // 'unknown' ) . "\n";
334 }
335 $eof = 1;
336 last;
337 }
338 my $row = _pg_csv_row( $data, $cols, $sep, $quo, $blank_to_null, $col_size );
339 push @rows, $row;
340 $bytes += length($row) + 1; # +1 for the newline added by join()
341 $$count_ref++;
342 }
343 if ($eof) { $closed = 1; close($fh); }
344 return unless @rows;
345 my $chunk = join( "\n", @rows ) . "\n";
346  
347 if ( defined $src_enc ) {
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 utf8::encode($chunk) if Encode::is_utf8($chunk);
353 $chunk = encode( $enc, decode( $src_enc, $chunk ) ) if defined $enc;
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 $chunk = encode( $enc, $chunk ) if defined $enc;
361 }
362 return $chunk;
363 };
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 sub _pg_encoding_name {
370 my ($pg) = @_;
371 my $n = uc( $pg // '' );
372 $n =~ s/[^A-Z0-9]//g;
373 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 return $map{$n} if exists $map{$n};
388 return "CP$1" if $n =~ /^WIN(\d+)$/;
389 return $n if $n ne '' && defined find_encoding($n);
390 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 sub _pg_encoding_known {
398 my ($pg) = @_;
399 my $n = uc( $pg // '' );
400 $n =~ s/[^A-Z0-9]//g;
401 return 0 if $n eq '';
402 return 1 if $n =~ /^(?:UTF8|UNICODE|LATIN(?:10|[1-9]))$/;
403 return 1 if $n =~ /^WIN\d+$/;
404 return 1 if defined find_encoding($n);
405 return 1 if defined find_encoding( $pg // '' );
406 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 sub _pg_source_encoding {
417 my ( $params, $cfg ) = @_;
418 my $raw = $params->{'pg_copy_encoding'};
419 $raw = $cfg->{'EDTK_DB_COPY_ENCODING'} unless defined $raw && $raw ne '';
420 $raw = 'LATIN1' unless defined $raw && $raw ne '';
421 return ( undef, "unknown copy encoding '$raw'" ) unless _pg_encoding_known($raw);
422 return ( ( defined find_encoding($raw) ? $raw : _pg_encoding_name($raw) ), undef );
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 sub _count_csv_rows {
432 my ( $fi, $params ) = @_;
433 open( my $fh, '<', $fi ) or return -1;
434 my $csv = Text::CSV->new(
435 {
436 binary => 1,
437 sep_char => $params->{'sep_char'} // ',',
438 quote_char => $params->{'quote_char'} // '"',
439 }
440 );
441 $csv->getline($fh); # skip the header record
442 my $rows = 0;
443 while (1) {
444 my $data = $csv->getline($fh);
445 last if !defined $data;
446 $rows++;
447 }
448 close($fh);
449 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 sub _pg_copy_stdin {
461 my ( $dbh, $sql, $next_block ) = @_;
462 my $emsg;
463 my $copy_live = 0;
464 eval {
465 local $dbh->{PrintError} = 0;
466 $dbh->do($sql);
467 $copy_live = 1;
468 while ( defined( my $chunk = $next_block->() ) ) {
469 defined $dbh->pg_putcopydata($chunk)
470 or die( $dbh->errstr || "pg_putcopydata failed" );
471 }
472 $copy_live = 0; # pg_putcopyend always ends the COPY
473 $dbh->pg_putcopyend();
474 1;
475 } or $emsg = $@;
476 $emsg ||= ( $dbh->err ? $dbh->errstr : '' );
477 if ($emsg) {
478 eval { $dbh->pg_putcopyend() } if $copy_live; # abort a live COPY
479 return $emsg;
480 }
481 return;
482 }
483  
484 # ============================================================
485 # PRIVATE : quote a PostgreSQL identifier ("" doubling).
486 # ============================================================
487 sub _pg_quote_ident {
488 my ($name) = @_;
489 ( my $s = $name ) =~ s/"/""/g;
490 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 sub _pg_deferrable_ddl {
502 my ( $dbh, $table, $defer_pk ) = @_;
503 my ($oid) = $dbh->selectrow_array( "SELECT to_regclass(?)::oid", undef, $table );
504 return { drop => [], create => [] } unless $oid;
505  
506 my ( @drop, @create );
507  
508 # Secondary indexes that back no constraint and are referenced by no FK.
509 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 foreach my $r (@$idx) {
519 my ( $nsp, $name, $def ) = @$r;
520 push @drop, "DROP INDEX " . _pg_quote_ident($nsp) . "." . _pg_quote_ident($name);
521 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 my $cons = $dbh->selectall_arrayref(
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 foreach my $r (@$cons) {
536 my ( $cname, $cdef ) = @$r;
537 my $cid = _pg_quote_ident($cname);
538 push @drop, "ALTER TABLE $table DROP CONSTRAINT $cid";
539 push @create, "ALTER TABLE $table ADD CONSTRAINT $cid $cdef";
540 }
541  
542 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 sub _pg_estimate_rows {
551 my ($fi) = @_;
552 my $size = -s $fi;
553 return 0 unless defined $size && $size > 0;
554 open( my $fh, '<', $fi ) or return 0;
555 binmode($fh);
556 my $got = read( $fh, my $buf, PG_DEFER_SAMPLE_BYTES );
557 close($fh);
558 return 0 unless $got;
559 my $cut = rindex( $buf, "\n" ); # ignore the truncated last line
560 return 0 if $cut < 0;
561 my $sample = substr( $buf, 0, $cut + 1 );
562 my $lines = () = $sample =~ /\n/g;
563 return 0 unless $lines;
564 my $mean = length($sample) / $lines;
565 return 0 unless $mean > 0;
566 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 sub _pg_table_rows {
575 my ( $dbh, $table ) = @_;
576 my ($n) = eval {
577 $dbh->selectrow_array(
578 'SELECT GREATEST(reltuples, 0) FROM pg_class WHERE oid = to_regclass(?)',
579 undef, $table );
580 };
581 return 0 unless defined $n;
582 return $n < 0 ? 0 : int($n);
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 sub _pg_should_defer {
595 my ( $params, $cfg, $incoming, $table_rows ) = @_;
596 my $ratio = $params->{'pg_defer_index_ratio'};
597 $ratio = $cfg->{'EDTK_DB_DEFER_INDEX_RATIO'} unless defined $ratio && $ratio ne '';
598 my $min = $params->{'pg_defer_index_min_rows'};
599 $min = $cfg->{'EDTK_DB_DEFER_INDEX_MIN_ROWS'} unless defined $min && $min ne '';
600 return 0 unless ( defined $ratio && $ratio ne '' ) || ( defined $min && $min ne '' );
601 $ratio = PG_DEFER_DEFAULT_RATIO unless defined $ratio && $ratio ne '';
602 $min = PG_DEFER_DEFAULT_MIN_ROWS unless defined $min && $min ne '';
603 return 0 unless $incoming >= $min;
604 return 1 if $table_rows <= 0; # empty or unknown table: nothing to weigh against
605 return $incoming >= $ratio * $table_rows ? 1 : 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 sub _pg_load_tx {
620 my ( $dbh, $tablename, $sql, $make_supplier, $ddl, %opt ) = @_;
621 my $own = $dbh->{AutoCommit} ? 1 : 0;
622 my $sp = 'edtk_pg_load'; # savepoint used when the caller owns the transaction
623 my $phase = 'begin';
624 my $ok = eval {
625 if ($own) { $dbh->begin_work }
626 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 if ( $opt{lock_timeout} ) {
631 eval {
632 local $dbh->{PrintError} = 0;
633 $dbh->do("SET LOCAL lock_timeout = '$opt{lock_timeout}'");
634 1;
635 } or &logger( 4, "_pg_load_tx: SET LOCAL lock_timeout failed: $@" );
636 }
637 eval { local $dbh->{PrintError} = 0; $dbh->do(PG_COPY_SYNC_OFF); 1 }
638 or &logger( 4, "_pg_load_tx: SET LOCAL failed: $@" );
639 $phase = 'defer';
640 foreach my $s ( @{ $ddl->{drop} } ) {
641 $dbh->do($s) or die( $dbh->errstr || "drop failed: $s" );
642 }
643 $phase = 'copy';
644 my $err = _pg_copy_stdin( $dbh, $sql, $make_supplier->() );
645 die $err if defined $err;
646 $phase = 'rebuild';
647 foreach my $s ( @{ $ddl->{create} } ) {
648 $dbh->do($s) or die( $dbh->errstr || "create failed: $s" );
649 }
650 if ($own) { $dbh->commit }
651 else { $dbh->do("RELEASE SAVEPOINT $sp") }
652 1;
653 };
654 return ( 'ok', '' ) if $ok;
655  
656 my $err = $@ // '';
657 if ($own) {
658 eval { $dbh->rollback } if !$dbh->{AutoCommit};
659 }
660 else {
661 # H14: undo to the savepoint, leaving the caller's transaction usable.
662 eval {
663 local $dbh->{PrintError} = 0;
664 $dbh->do("ROLLBACK TO SAVEPOINT $sp");
665 $dbh->do("RELEASE SAVEPOINT $sp");
666 1;
667 };
668 }
669 $err =~ s/\s+\z//;
670 return ( $phase eq 'defer' ? 'defer' : 'fail', $err );
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 sub _pg_burst_decision {
683 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 return ( 0, 'force_copy => 1' ) if $params->{'force_copy'};
688 if ( defined $params->{'pg_copy_staging'} ) {
689 return $params->{'pg_copy_staging'}
690 ? ( 1, 'pg_copy_staging => 1' )
691 : ( 0, 'pg_copy_staging => 0' );
692 }
693 my $mo = $params->{'burst_mo'};
694 $mo = $cfg->{'EDTK_DB_BURST_MO'} unless defined $mo && $mo ne '';
695 if ( !defined $mo || $mo eq '' ) { $mo = PG_BURST_MO_DEFAULT; }
696 elsif ( $mo !~ /^\s*[0-9]+(?:\.[0-9]+)?\s*$/ ) {
697 &logger( 3,
698 "_pg_burst_decision: invalid EDTK_DB_BURST_MO '$mo', using default "
699 . PG_BURST_MO_DEFAULT );
700 $mo = PG_BURST_MO_DEFAULT;
701 }
702 return ( 0, 'EDTK_DB_BURST_MO=0 (ELT disabled)' ) if $mo == 0;
703 my $size = -s $fi;
704 $size = 0 unless defined $size && $size > 0;
705 my $limit = $mo * PG_BURST_BYTES_PER_MO;
706 return ( 1, "file ${size}B >= ${mo}Mo threshold" ) if $size >= $limit;
707 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 sub _pg_defer_plan {
716 my ( $dbh, $tablename, $params, $cfg, $fi, $rows_before ) = @_;
717 return { drop => [], create => [] } unless $params->{'pg_copy_optimize'} // 1;
718 my $incoming = _pg_estimate_rows($fi);
719 unless ( _pg_should_defer( $params, $cfg, $incoming, $rows_before ) ) {
720 &logger( 5, "_pg_defer_plan: not deferring (~$incoming incoming, $rows_before rows)" );
721 return { drop => [], create => [] };
722 }
723 my $ddl = eval { _pg_deferrable_ddl( $dbh, $tablename, $params->{'pg_copy_defer_pk'} ) };
724 &logger( 4, "_pg_defer_plan: deferral lookup failed: $@" ) unless $ddl;
725 $ddl ||= { drop => [], create => [] };
726 &logger( 5, "_pg_defer_plan: deferring indexes (~$incoming incoming vs $rows_before rows)" )
727 if @{ $ddl->{drop} };
728 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 sub _pg_column_types {
740 my ( $dbh, $table, $cols ) = @_;
741 my $rows = eval {
742 $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 return undef unless $rows; ## no critic (ProhibitExplicitReturnUndef)
750 my %seen = map { lc( $_->[0] ) => { typname => $_->[1], ftype => $_->[2] } } @$rows;
751 my %type;
752 for my $c (@$cols) {
753 my $t = $seen{ lc $c } or return undef; ## no critic (ProhibitExplicitReturnUndef)
754 $type{$c} = $t->{typname} =~ /^(?:text|varchar|bpchar|char|name)$/ ? 'text' : $t->{ftype};
755 }
756 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 sub _pg_stg_name {
770 return PG_STG_PREFIX . $$ . '_' . ++$_PG_STG_SEQ;
771 }
772  
773 sub _pg_stg_ddl {
774 my ( $stg, $cols, $types ) = @_;
775 my $list = join( ', ', map { _pg_quote_ident($_) . ' ' . $types->{$_} } @$cols );
776 return 'CREATE TEMP TABLE ' . _pg_quote_ident($stg) . " ( $list ) ON COMMIT DROP";
777 }
778  
779 sub _pg_stg_copy_sql {
780 my ( $stg, $cols, $types, $sep, $quo, $src_enc ) = @_;
781 my $opts = "FORMAT csv, HEADER true, DELIMITER '$sep', QUOTE '$quo'";
782 $opts .= ", ENCODING '$src_enc'" if defined $src_enc && $src_enc ne '';
783 my @text = grep { $types->{$_} eq 'text' } @$cols;
784 $opts .= ', FORCE_NOT_NULL (' . join( ',', map { _pg_quote_ident($_) } @text ) . ')' if @text;
785 return
786 'COPY '
787 . _pg_quote_ident($stg) . ' ('
788 . join( ',', map { _pg_quote_ident($_) } @$cols )
789 . ") FROM STDIN WITH ($opts)";
790 }
791  
792 sub _pg_stg_insert_sql {
793 my ( $copy_table, $cols, $col_meta, $stg ) = @_;
794 my $ins = join( ', ', map { _pg_quote_ident($_) } @$cols );
795 my $sel = join(
796 ', ',
797 map {
798 my $size = ( $col_meta->{$_} // {} )->{size} // 0;
799 $size > 0 ? 'substr(' . _pg_quote_ident($_) . ", 1, $size)" : _pg_quote_ident($_);
800 } @$cols
801 );
802 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 sub _pg_raw_supplier {
810 my ($fi) = @_;
811 return sub {
812 open my $fh, '<:raw', $fi or die "cannot open \"$fi\": $!";
813 return sub {
814 my $r = read( $fh, my $buf, PG_COPY_BLOCK_SIZE );
815 die "read \"$fi\": $!" unless defined $r;
816 if ( $r == 0 ) { close $fh; return undef; } ## no critic (ProhibitExplicitReturnUndef)
817 return $buf;
818 };
819 };
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 sub _pg_stage_and_insert {
833 my (%a) = @_;
834 my $dbh = $a{dbh};
835 my $cols = $a{cols};
836 my $col_meta = $a{col_meta};
837 my $ddl = $a{ddl};
838 my $own = $dbh->{AutoCommit} ? 1 : 0;
839 my $sp = 'edtk_pg_elt';
840 my $phase = 'begin';
841 my $rows = 0;
842 my $t0 = time;
843 my $ok = eval {
844 if ($own) { $dbh->begin_work }
845 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 if ( $a{lock_timeout} ) {
850 eval {
851 local $dbh->{PrintError} = 0;
852 $dbh->do("SET LOCAL lock_timeout = '$a{lock_timeout}'");
853 1;
854 } or &logger( 4, "_pg_stage_and_insert: SET LOCAL lock_timeout failed: $@" );
855 }
856 eval { local $dbh->{PrintError} = 0; $dbh->do(PG_COPY_SYNC_OFF); 1 }
857 or &logger( 4, "_pg_stage_and_insert: SET LOCAL failed: $@" );
858 if ( @{ $ddl->{drop} } ) {
859 eval {
860 local $dbh->{PrintError} = 0;
861 $dbh->do( "SET LOCAL maintenance_work_mem = '" . PG_BURST_MAINT_MEM . "'" );
862 1;
863 }
864 or &logger( 4, "_pg_stage_and_insert: SET LOCAL maintenance_work_mem failed: $@" );
865 }
866  
867 $phase = 'defer';
868 foreach my $s ( @{ $ddl->{drop} } ) {
869 $dbh->do($s) or die( $dbh->errstr || "drop failed: $s" );
870 }
871  
872 $phase = 'stage';
873 my $types = _pg_column_types( $dbh, $a{tablename}, $cols );
874 die "ELT_FALLBACK: column types unavailable\n" unless $types;
875 my $stg = _pg_stg_name();
876 my $cre =
877 eval { local $dbh->{PrintError} = 0; $dbh->do( _pg_stg_ddl( $stg, $cols, $types ) ); 1 };
878 die 'ELT_FALLBACK: CREATE TEMP TABLE refused: ' . ( $@ || $dbh->errstr ) . "\n" unless $cre;
879 my $err = _pg_copy_stdin(
880 $dbh,
881 _pg_stg_copy_sql( $stg, $cols, $types, $a{sep}, $a{quo}, $a{src_enc} ),
882 _pg_raw_supplier( $a{fi} )->()
883 );
884 die $err if defined $err;
885 my $t_stage = time;
886  
887 $phase = 'insert';
888 $rows = $dbh->do( _pg_stg_insert_sql( $a{copy_table}, $cols, $col_meta, $stg ) );
889 defined $rows or die( $dbh->errstr || "insert failed" );
890 my $t_ins = time;
891  
892 $phase = 'rebuild';
893 foreach my $s ( @{ $ddl->{create} } ) {
894 $dbh->do($s) or die( $dbh->errstr || "create failed: $s" );
895 }
896 if ($own) { $dbh->commit }
897 else { $dbh->do("RELEASE SAVEPOINT $sp") }
898 &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 1;
908 };
909 return ( 'ok', $rows ) if $ok;
910  
911 my $err = $@ // '';
912 if ($own) {
913 eval { $dbh->rollback } if !$dbh->{AutoCommit};
914 }
915 else {
916  
917 # H14: undo to the savepoint, leaving the caller's transaction usable.
918 eval {
919 local $dbh->{PrintError} = 0;
920 $dbh->do("ROLLBACK TO SAVEPOINT $sp");
921 $dbh->do("RELEASE SAVEPOINT $sp");
922 1;
923 };
924 }
925 $err =~ s/\s+\z//;
926 return ( 'fallback', $err ) if $err =~ /^ELT_FALLBACK:/;
927 return ( $phase eq 'defer' ? 'defer' : 'fail', $err );
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 sub _pg_elt_load {
936 my (
937 $dbh, $tablename, $fi, $params, $cols, $col_meta,
938 $sep, $quo, $enc, $src_enc, $copy_table, $cfg
939 ) = @_;
940 my $rows_before = _pg_table_rows( $dbh, $tablename );
941 my $defer_ddl = _pg_defer_plan( $dbh, $tablename, $params, $cfg, $fi, $rows_before );
942 my %lt = ( @{ $defer_ddl->{drop} } ? ( lock_timeout => PG_COPY_LOCK_TIMEOUT ) : () );
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 return ( 'fallback', 'ELT needs an explicit source encoding' )
952 unless defined $src_enc && $src_enc ne '';
953 my $decl = $src_enc;
954  
955 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 my ( $status, $res ) = _pg_stage_and_insert( %common, ddl => $defer_ddl, %lt );
967 if ( $status eq 'defer' ) {
968 &logger( 4, "_pg_elt_load: deferral unavailable ($res), retrying without it" );
969 ( $status, $res ) =
970 _pg_stage_and_insert( %common, ddl => { drop => [], create => [] } );
971 }
972 return ( $status, $res ) unless $status eq 'ok';
973  
974 # Refresh the planner statistics only when the load is significant (O5).
975 if ( $rows_before <= 0 || $res >= PG_ANALYZE_TABLE_SHARE * $rows_before ) {
976 eval { local $dbh->{PrintError} = 0; $dbh->do( sprintf( PG_COPY_ANALYZE, $tablename ) ); 1 }
977 or &logger( 4, "_pg_elt_load: ANALYZE $tablename failed: $@" );
978 }
979 else {
980 &logger( 5, "_pg_elt_load: ANALYZE $tablename skipped ($res rows added to $rows_before)" );
981 }
982 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 sub _load_csv_pg_copy {
995 my ( $dbh, $tablename, $fi, $params, $norm_id ) = @_;
996  
997 my $sep = $params->{'sep_char'};
998 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 my $enc = _pg_encoding_name( eval { $dbh->selectrow_array('SHOW client_encoding') } );
1003 &logger( 7, "_load_csv_pg_copy: client_encoding=" . ( $enc // 'raw' ) );
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 my $cfg = eval { config_read('EDTK_DB') } || {};
1010 my ( $src_enc, $src_err ) = _pg_source_encoding( $params, $cfg );
1011 return ( -1, &logger( 3, "_load_csv_pg_copy: $src_err" ) ) if $src_err;
1012 my $decl = $params->{'pg_copy_encoding'};
1013 $decl = $cfg->{'EDTK_DB_COPY_ENCODING'} unless defined $decl && $decl ne '';
1014 $src_enc = undef unless defined $decl && $decl ne '';
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 open( my $fh, '<', $fi )
1019 or return ( -1, &logger( 3, "_load_csv_pg_copy: cannot open \"$fi\": $!" ) );
1020 my $csv = Text::CSV->new(
1021 {
1022 binary => 1,
1023 sep_char => $sep,
1024 quote_char => $quo
1025 }
1026 );
1027 my $hdr = $csv->getline($fh);
1028 unless ($hdr) {
1029 close($fh);
1030 return ( -1, &logger( 3, "_load_csv_pg_copy: cannot read header of \"$fi\"" ) );
1031 }
1032 close($fh);
1033 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 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 my $unknown = keys %$col_meta ? _unknown_csv_columns( \@cols, $col_meta ) : [];
1042 if (@$unknown) {
1043 return (
1044 -1,
1045 &logger(
1046 3,
1047 "_load_csv_pg_copy: unknown column(s) "
1048 . join( ', ', @$unknown )
1049 . " for table $tablename"
1050 )
1051 );
1052 }
1053 my @blank_to_null = map { ( $col_meta->{$_} // {} )->{blank_to_null} ? 1 : 0 } @cols;
1054 my @col_size = map { ( $col_meta->{$_} // {} )->{size} // 0 } @cols;
1055  
1056 # COPY ... FROM STDIN : NULL '' makes an unquoted empty field a NULL.
1057 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 my ( $use_elt, $why ) = _pg_burst_decision( $params, $cfg, $fi );
1063 &logger( 5, "_load_csv_pg_copy: path " . ( $use_elt ? 'ELT' : 'COPY' ) . " ($why)" );
1064 if ($use_elt) {
1065 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 &logger( 5, "bulk insert into $tablename via ELT staging: $res rows" ) if $status eq 'ok';
1070 return ( $res, " lines inserted" ) if $status eq 'ok';
1071 return ( -1, &logger( 3, "_load_csv_pg_copy: ELT into $tablename failed: $res" ) )
1072 if $status eq 'fail';
1073 &logger( 3, "_load_csv_pg_copy: ELT unavailable ($res), using COPY" );
1074 }
1075  
1076 my $sql =
1077 "COPY $copy_table ("
1078 . join( ',', map { _pg_quote_ident($_) } @cols ) . ")"
1079 . " FROM STDIN WITH (FORMAT csv, DELIMITER '"
1080 . $sep . "',"
1081 . " QUOTE '"
1082 . $quo
1083 . "', NULL '')";
1084 &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 my $count = 0;
1089 my $make_supplier = sub {
1090 $count = 0;
1091 _pg_csv_supplier( $fi, $params, \@cols, \@blank_to_null, \@col_size, \$count, $enc,
1092 $src_enc );
1093 };
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 my $rows_before = _pg_table_rows( $dbh, $tablename );
1105 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 my %lt = ( @{ $defer_ddl->{drop} } ? ( lock_timeout => PG_COPY_LOCK_TIMEOUT ) : () );
1109 my ( $status, $emsg ) = _pg_load_tx( $dbh, $tablename, $sql, $make_supplier, $defer_ddl, %lt );
1110 if ( $status eq 'defer' ) {
1111 &logger( 4, "_load_csv_pg_copy: deferral unavailable ($emsg), retrying without it" );
1112 ( $status, $emsg ) =
1113 _pg_load_tx( $dbh, $tablename, $sql, $make_supplier, { drop => [], create => [] } );
1114 }
1115  
1116 if ( $status ne 'ok' ) {
1117 chomp( $emsg //= '' );
1118 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 if ( $rows_before <= 0 || $count >= PG_ANALYZE_TABLE_SHARE * $rows_before ) {
1124 eval { local $dbh->{PrintError} = 0; $dbh->do( sprintf( PG_COPY_ANALYZE, $tablename ) ); 1 }
1125 or &logger( 4, "_load_csv_pg_copy: ANALYZE $tablename failed: $@" );
1126 }
1127 else {
1128 &logger( 5,
1129 "_load_csv_pg_copy: ANALYZE $tablename skipped ($count rows added to $rows_before)" );
1130 }
1131  
1132 &logger( 5, "bulk insert into $tablename via COPY ... FROM STDIN: $count rows" );
1133 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 sub _unknown_csv_columns {
1143 my ( $cols, $col_meta ) = @_;
1144 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 sub _norm_identifiers {
1152 my ( $dbh, $table, $cols_ref ) = @_;
1153  
1154 my $driver = lc( $dbh->{Driver}{Name} // '' );
1155 my $is_mysql = ( $driver =~ /mysql|mariadb/ ) ? 1 : 0;
1156 my $norm_id =
1157 $is_mysql
1158 ? sub { my $s = $_[0]; $s =~ s/^\s+|\s+$//g; return uc($s) }
1159 : sub { my $s = $_[0]; $s =~ s/^\s+|\s+$//g; return lc($s) };
1160  
1161 # Normalize the table name, keeping the schema when present
1162 my $norm_table = join( '.', map { $norm_id->($_) } split( /\./, $table, 2 ) );
1163  
1164 # Normalize the columns (optional)
1165 my @norm_cols = map { $norm_id->($_) } @{ $cols_ref // [] };
1166  
1167 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 sub _col_meta_from_names {
1178 my ( $dbh, $table, $norm_id ) = @_;
1179  
1180 my %meta;
1181 my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
1182 $sth->execute();
1183 for my $col ( @{ $sth->{NAME} } ) {
1184 my $norm_col = $norm_id->($col);
1185 $meta{$norm_col} = { numeric => 0, size => 0 };
1186 &logger( 7, "_get_col_meta (fallback): col=$norm_col" );
1187 }
1188 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 sub _get_col_meta {
1199 my ( $dbh, $table, $norm_id ) = @_;
1200  
1201 # $norm_id is mandatory - always supplied by _norm_identifiers
1202 die "_get_col_meta: norm_id missing" unless defined $norm_id;
1203  
1204 my $driver = lc( $dbh->{Driver}{Name} // '' );
1205 my $cache_key = lc($table) . "\0" . $driver;
1206 return $_csv_import_type_cache{$cache_key}
1207 if exists $_csv_import_type_cache{$cache_key};
1208  
1209 my %meta;
1210 eval {
1211 # $table is already normalized by the caller: split without re-normalizing
1212 my ( $schema, $table_name ) =
1213 $table =~ /^(\w+)\.(\w+)$/
1214 ? ( $1, $2 )
1215 : ( undef, $table );
1216  
1217 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 unless ( defined $sth ) {
1222 &logger( 5,
1223 "_get_col_meta: column_info unsupported for '$table_name', fallback SELECT" );
1224 %meta = %{ _col_meta_from_names( $dbh, $table, $norm_id ) };
1225 $_csv_import_type_cache{$cache_key} = \%meta;
1226 return;
1227 }
1228  
1229 my %num_codes = map { $_ => 1 } ( 2, 3, 4, 5, 6, 7, 8, -5, -6, -7 );
1230 my $found = 0;
1231 while ( my $row = $sth->fetchrow_hashref ) {
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 next unless defined $row->{COLUMN_NAME} && $row->{COLUMN_NAME} ne '';
1237 $found++;
1238 my $col = $norm_id->( $row->{COLUMN_NAME} );
1239 my $type = $row->{DATA_TYPE} // 0;
1240 my $name = lc( $row->{TYPE_NAME} // '' );
1241 my $size = $row->{COLUMN_SIZE} // 0;
1242  
1243 my $by_name = (
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 my $is_num = ( $num_codes{$type} || $by_name ) ? 1 : 0;
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 my $is_text = (
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 my $is_datetime = (
1270 $name =~ m{
1271 ^( date | time | timestamp(tz)? | datetime )
1272 }xi
1273 ) ? 1 : 0;
1274 my $blank_to_null = ( $is_num || $is_datetime ) ? 1 : 0;
1275  
1276 $meta{$col} = {
1277 numeric => $is_num,
1278 blank_to_null => $blank_to_null,
1279 size => ( $is_text ? $size : 0 ),
1280 };
1281 &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 if ( !$found ) {
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 &logger( 5,
1292 "_get_col_meta: column_info returned no usable column for '$table_name', fallback SELECT"
1293 );
1294 %meta = %{ _col_meta_from_names( $dbh, $table, $norm_id ) };
1295 }
1296 else {
1297 &logger( 5, "_get_col_meta: $found columns for '$table_name'" );
1298 }
1299 };
1300 if ($@) {
1301 &logger( 3, "_get_col_meta: column_info failed for $table: $@" );
1302 }
1303  
1304 $_csv_import_type_cache{$cache_key} = \%meta;
1305 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 sub db_invalidate_meta_cache {
1312 %_csv_import_type_cache = ();
1313 return 1;
1314 }
1315  
1316 # ============================================================
1317 # PRIVATE: clean one value according to the column metadata
1318 # (numeric type, max size)
1319 # ============================================================
1320 sub _make_clean_val {
1321 my ($col_meta) = @_;
1322 return sub {
1323 my ( $col, $val ) = @_;
1324 return undef unless defined $val; ## no critic (ProhibitExplicitReturnUndef)
1325 my $m = $col_meta->{$col} // {};
1326  
1327 if ( $val eq '' ) {
1328 if ( $m->{blank_to_null} ) {
1329 &logger( 7, "clean_val: col '$col' numeric/date, '' => undef" );
1330 return undef; ## no critic (ProhibitExplicitReturnUndef)
1331 }
1332 return $val;
1333 }
1334  
1335 if ( $m->{size} && length($val) > $m->{size} ) {
1336 my $truncated = substr( $val, 0, $m->{size} );
1337 &logger( 6,
1338 "clean_val: col '$col' truncated from " . length($val) . " to $m->{size} chars" );
1339 return $truncated;
1340 }
1341  
1342 return $val;
1343 };
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 sub _make_clean_plan {
1353 my ( $col_meta, $cols ) = @_;
1354 return [
1355 map {
1356 my $m = $col_meta->{$_} // {};
1357 [ $_, ( $m->{size} // 0 ), ( $m->{blank_to_null} ? 1 : 0 ) ]
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 sub _clean_row {
1369 my ( $plan, $data ) = @_;
1370 my @out;
1371 for my $i ( 0 .. $#$plan ) {
1372 my $v = $data->[$i];
1373 my $p = $plan->[$i];
1374 if ( !defined $v ) { push @out, undef; next; }
1375 if ( $v eq '' ) {
1376 if ( $p->[2] ) {
1377 &logger( 7, "clean_val: col '$p->[0]' numeric/date, '' => undef" )
1378 if $LOGGERLEVEL >= 7;
1379 push @out, undef;
1380 }
1381 else { push @out, $v; }
1382 next;
1383 }
1384 if ( $p->[1] && length($v) > $p->[1] ) {
1385 &logger( 6,
1386 "clean_val: col '$p->[0]' truncated from " . length($v) . " to $p->[1] chars" )
1387 if $LOGGERLEVEL >= 6;
1388 push @out, substr( $v, 0, $p->[1] );
1389 next;
1390 }
1391 push @out, $v;
1392 }
1393 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 my $_CSV_BACKEND_WARNED = 0;
1403  
1404 sub _check_csv_backend {
1405 return if $_CSV_BACKEND_WARNED;
1406 my $backend = eval { Text::CSV->backend };
1407 unless ( defined $backend && $backend eq 'Text::CSV_XS' ) {
1408 $_CSV_BACKEND_WARNED = 1;
1409 &logger( 3,
1410 "csv_import: Text::CSV backend is '"
1411 . ( $backend // 'unknown' )
1412 . "', not Text::CSV_XS - install Text::CSV_XS (plan O1)" );
1413 }
1414 return;
1415 }
1416  
1417 sub insert_tData {
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 my (%p) = @_;
1427  
1428 my ( $norm_id, $norm_table, @norm_cols ) =
1429 _norm_identifiers( $p{'dbh'}, $p{'table'}, $p{'tCols'} );
1430  
1431 my $col_meta = _get_col_meta( $p{'dbh'}, $norm_table, $norm_id );
1432 my $plan = _make_clean_plan( $col_meta, \@norm_cols );
1433  
1434 &logger( 7, "Table : $norm_table" );
1435 &logger( 7, "NB Data : " . scalar @{ $p{'tData'} } );
1436 &logger( 7, "Data : " . Dumper( $p{'tData'} ) );
1437  
1438 my $sql =
1439 "INSERT INTO "
1440 . $norm_table . " ("
1441 . join( ',', @norm_cols ) . ")"
1442 . " VALUES ("
1443 . join( ',', ('?') x @norm_cols ) . ")";
1444 &logger( 7, $sql );
1445  
1446 my $sth = $p{'dbh'}->prepare_cached($sql);
1447 do {
1448 local $sth->{PrintError} = 0;
1449 $sth->execute( _clean_row( $plan, $p{'tData'} ) );
1450 }
1451 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1452 1;
1453 }
1454  
1455 # ============================================================
1456 # PUBLIC: import a CSV file into a table
1457 # API unchanged
1458 # ============================================================
1459 sub csv_import {
1460 my ( $dbh, $table, $in, $params ) = @_;
1461 $params->{'mode'} = $params->{'mode'} || "insert";
1462 $params->{'sep_char'} = $params->{'sep_char'} || ',';
1463 $params->{'quote_char'} = $params->{'quote_char'} || '"';
1464 $params->{'local_infile'} = $params->{'local_infile'} || "no";
1465 $params->{'ref_col'} = $params->{'ref_col'} || 0; # merge match column (D-S53)
1466  
1467 # O1: the CSV parse paths need the Text::CSV_XS backend; warn once otherwise.
1468 _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 my ( $norm_id, $norm_table ) = _norm_identifiers( $dbh, $table );
1473  
1474 if ( $params->{'local_infile'} =~ /try/i
1475 && $params->{'mode'} !~ /merge/i
1476 && $dbh->{'Name'} =~ m/mysql_local_infile\=true/i )
1477 {
1478 &logger( 7,
1479 "'mysql_local_infile=true' detected in DSN by csv_import, trying local infile" );
1480 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 if ( $params->{'mode'} !~ /merge/i
1486 && _db_check_driver_name($dbh) eq "PostgreSQL" )
1487 {
1488 if ( defined $params->{'header'} || defined $params->{'ignore_first_line'} ) {
1489 &logger( 5,
1490 "csv_import: header/ignore_first_line requested, using the row-by-row path (COPY ignores them)"
1491 );
1492 }
1493 else {
1494 &logger( 7, "PostgreSQL driver detected by csv_import, trying COPY FROM STDIN" );
1495 return _load_csv_pg_copy( $dbh, $norm_table, $in, $params, $norm_id );
1496 }
1497 }
1498  
1499 open( my $fh, '<', $in ) or die "ERROR: Cannot open index file \"$in\": $!\n";
1500 my $csv = Text::CSV->new(
1501 {
1502 binary => 1,
1503 sep_char => $params->{'sep_char'},
1504 quote_char => $params->{'quote_char'}
1505 }
1506 );
1507  
1508 my ( $line, $lines_inserted, $rv );
1509 if ( defined $params->{'header'} ) {
1510 $line = $params->{'header'};
1511 }
1512 else {
1513 $line = <$fh>;
1514 }
1515 $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 my @cols = map { $norm_id->($_) } $csv->fields();
1520  
1521 if ( defined $params->{'ignore_first_line'} ) {
1522 $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 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 my $unknown = keys %$col_meta ? _unknown_csv_columns( \@cols, $col_meta ) : [];
1531 if (@$unknown) {
1532 close($fh);
1533 return (
1534 -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 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 my $refcol = $params->{'ref_col'};
1551  
1552 while (<$fh>) {
1553 $lines_inserted++;
1554 $csv->parse($_);
1555 my @data = $csv->fields();
1556 my @clean = _clean_row( $plan, \@data );
1557 my ( $sql, $sth, $seqlot );
1558  
1559 if ( $params->{'mode'} =~ /merge/i ) {
1560 $sql =
1561 "SELECT "
1562 . $cols[$refcol]
1563 . " FROM "
1564 . $norm_table
1565 . " WHERE "
1566 . $cols[$refcol] . " = ?";
1567 &logger( 7, "Select from $norm_table : $sql" );
1568 $sth = $dbh->prepare_cached($sql);
1569 do {
1570 local $sth->{PrintError} = 0;
1571 $sth->execute( $clean[$refcol] );
1572 }
1573 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1574 $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 if ( defined $seqlot ) {
1579 $seqlot = { map { $norm_id->($_) => $seqlot->{$_} } keys %$seqlot };
1580 }
1581 }
1582  
1583 if ( defined $seqlot && defined $seqlot->{ $cols[$refcol] } ) {
1584 $sql =
1585 "UPDATE "
1586 . $norm_table . " SET "
1587 . join( '=?, ', @cols ) . "=? "
1588 . " WHERE "
1589 . $cols[$refcol] . " = ?";
1590 &logger( 7, "Update $norm_table : $sql" );
1591 $sth = $dbh->prepare_cached($sql);
1592 do {
1593 local $sth->{PrintError} = 0;
1594 $sth->execute( @clean, $clean[$refcol] );
1595 }
1596 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1597 }
1598 else {
1599 $sql =
1600 "INSERT INTO "
1601 . $norm_table . " ("
1602 . join( ',', @cols ) . ")"
1603 . " VALUES ("
1604 . join( ',', ('?') x @cols ) . ")";
1605 &logger( 7, "Insert into $norm_table : $sql" );
1606 $sth = $dbh->prepare_cached($sql);
1607 do {
1608 local $sth->{PrintError} = 0;
1609 $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 if ( $params->{'timestamp'} ) {
1620 my $exped = $data[ACQ_FIELD_EXPED];
1621 if ( defined $exped && $exped ne '' ) {
1622 if ( $exped !~ /^20[0-9]+$/ ) {
1623 &logger( 3, "csv_import: acknowledgement date '$exped' is not a valid date" );
1624 }
1625 else {
1626 my $acfg = eval { config_read( 'EDTK_DB', 'SERVICES' ) };
1627 if ( ref $acfg eq 'HASH' ) {
1628 my $idx = $acfg->{'EDTK_DBI_OUTMNGR'};
1629 _acquit_table_INDEX( $dbh, \@data, $idx ) if defined $idx && length $idx;
1630 _acquit_API( $dbh, \@data, $acfg );
1631 }
1632 }
1633 }
1634 }
1635  
1636 if ( $sth->err && ( $sth->err > 0 || $sth->err =~ m/0E/ ) ) {
1637 $rv = $sth->err . "-" . $sth->errstr;
1638 }
1639 }
1640  
1641 close($fh);
1642 if ($rv) {
1643 &logger( -1, $rv );
1644 return ( -1, " - $rv" );
1645 }
1646 else {
1647 $lines_inserted //= 0;
1648 &logger( 5, "$lines_inserted lines inserted from $in" );
1649 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 sub _db_connect1 {
1686 my ( $cfg, $dsnvar, $dbargs ) = @_;
1687 my $dbh;
1688 my $dsn = $cfg->{$dsnvar};
1689 $_LOCAL_EDTK_WAITRUN = $cfg->{EDTK_WAITRUN};
1690  
1691 &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 for ( my $i = 0 ; $i < 3 ; $i++ ) {
1698 sleep( $_LOCAL_EDTK_WAITRUN * $i );
1699 $dbh = undef;
1700 eval {
1701 $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 if ( $@ || !defined $dbh ) {
1709  
1710 # on a connection failure, try again
1711 &logger( 4, "DBI connection missmatch to $dsnvar, we try 3 times" );
1712 &logger( 4, "Error message was : " . ( $@ || $DBI::errstr || 'no handle returned' ) );
1713  
1714 }
1715 else {
1716 # if it looks fine, we are done
1717  
1718 if (
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 my ( $level, $return ) = acheck_db_admin_on_connect( $dbh, $cfg );
1737 &logger( $level, "$return-$dsn" );
1738 }
1739 $CONNECT_COUNT++;
1740  
1741 $i = 4;
1742 }
1743 }
1744 return $dbh;
1745 }
1746  
1747 sub db_connect {
1748 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 && ( uc( $cfg->{'EDTK_TRACK_MODE'} // '' ) eq 'NONE' ) );
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 $dbargs->{'FetchHashKeyName'} = $cfg->{EDTK_DB_FetchHashKeyName} || 'NAME_uc';
1762  
1763 #$dbh = DBI->connect($dsn, $user, $password,
1764 # { RaiseError => 1, AutoCommit => 0 });
1765  
1766 # Connect to the database.
1767 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 if ( !defined $dbh ) {
1772 if ( defined $cfg->{"${dsnvar}_BAK"} )
1773 { # TODO the setting should be added in the backup database (procedure that creates it)
1774 &logger( 4,
1775 "Could not connect to main database server: " . ( $DBI::errstr || "not defined" ) );
1776 $dbh = _db_connect1( $cfg, "${dsnvar}_BAK", $dbargs );
1777  
1778 if ( !defined $dbh ) {
1779 die "ERROR: Could not connect to backup database server : "
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 $dbh->{'private_oEdtk_on_backup'} = 1;
1787 &logger( 3,
1788 "Writing to the BACKUP database (main unreachable): data is buffered and will be repatriated."
1789 );
1790 eval { db_backup_prepare($dbh); };
1791 }
1792 else {
1793 die "ERROR: Could not connect to database server : "
1794 . ( $DBI::errstr || "not defined" ) . "\n";
1795 }
1796 }
1797  
1798 if ( _table_exists( $dbh, $cfg->{'EDTK_DBI_TRACKING'} ) ) {
1799  
1800 # silent soft check
1801 }
1802 else {
1803 create_table_TRACKING( $dbh, $cfg->{'EDTK_DBI_TRACKING'}, $cfg->{'EDTK_MAX_USER_KEY'} );
1804 }
1805  
1806 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 sub _elapsed_seconds {
1812 my ($since) = @_;
1813 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 sub _db_do_log {
1822 my ( $dbh, $sql, $msg, %opt ) = @_;
1823 my $res = do {
1824 local $dbh->{PrintError} = 0;
1825 local $dbh->{RaiseError} = 0;
1826 eval { $dbh->do( $sql, undef, @{ $opt{bind} // [] } ) };
1827 };
1828 return $res if defined $res;
1829 my $full = $msg . ": " . ( $dbh->errstr // $@ // 'unknown error' );
1830 die &logger( -1, $full ) if $opt{fatal};
1831 &logger( 3, $full );
1832 return;
1833 }
1834  
1835 sub _table_exists {
1836 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 my $sth = $dbh->table_info( undef, undef, $table_name, 'TABLE' );
1843  
1844 # If fetchrow_array returns a row, the table exists
1845 my @info = $sth->fetchrow_array();
1846  
1847 return @info ? 1 : 0;
1848 }
1849  
1850 sub acheck_db_admin {
1851  
1852 # EXAMPLE CALL:
1853 # acheck_db_admin (CFG => $cfg);
1854 # in Auto mode, a single daily run is performed
1855 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 my $date = strftime "%Y-%m-%d", localtime;
1864 my ( $sth, $sql );
1865 &logger( 6, "ACHECK lookup" );
1866  
1867 # LOOK FOR THE LAST ACTION ON THE ADMIN TABLE
1868 $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 &logger( 7, $sql );
1874  
1875 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
1876 eval { schema_StaleWarning( $p{DBH}, cfg => $p{CFG} ); };
1877 $sth = $p{DBH}->prepare($sql) or return ( 3, $p{DBH}->errstr );
1878 do { local $sth->{PrintError} = 0; $sth->execute() }
1879 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1880  
1881 # HAS AN ADMINISTRATION ACTION ALREADY BEEN DONE TODAY ?
1882 my @tValues = $p{DBH}->selectrow_array( $sql, undef )
1883 ; # or warn ("ERROR: in acheck_db_admin_on_connect, message is " . $dbh->errstr);
1884 my $rc = $sth->finish;
1885 $p{DBH}->disconnect;
1886  
1887 if ( $tValues[0] and $date eq $tValues[0] ) {
1888 &logger(
1889 5,
1890 (
1891 "Previously done, ACHECK Last EDTK_DB_MAX_DAYS check : "
1892 . $tValues[0] . " PID "
1893 . $tValues[1]
1894 )
1895 );
1896 return ( 5,
1897 ( "ACHECK Last EDTK_DB_MAX_DAYS check : " . $tValues[0] . " PID " . $tValues[1] ) );
1898 }
1899  
1900 return _acheck_request_for_db( CFG => $p{CFG} );
1901 }
1902  
1903 sub _acheck_request_for_db {
1904  
1905 # example call
1906 # _acheck_request_for_db (CFG => $cfg, DBH => $dbh);
1907 my %p = @_;
1908  
1909 my $time = time;
1910 my $date = strftime "%Y-%m-%d", localtime;
1911 my $pid = $$;
1912 my ( $rc, $sth, $sql, $insert, $reportActions );
1913  
1914 # REQUEST A TICKET TO CARRY OUT THE ACTIONS
1915 $insert =
1916 'insert into edtk_admin (ed_action_date, ed_action_pid, ed_action_status, ed_oedtk_release) '
1917 . ' values (?, ?, ?, ?) ';
1918 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
1919 $sth = $p{DBH}->prepare_cached($insert);
1920  
1921 eval {
1922 do { local $sth->{PrintError} = 0; $sth->execute( $date, $pid, "START", $VERSION ) }
1923 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1924 };
1925 if ($@) {
1926 &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 "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 &logger( 7, $sql );
1937  
1938 $sth = $p{DBH}->prepare($sql);
1939 do { local $sth->{PrintError} = 0; $sth->execute() }
1940 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
1941 my @tValues = do { local $p{DBH}->{PrintError} = 0; $p{DBH}->selectrow_array( $sql, undef ) }
1942 or &logger( 3, "ERROR: in acheck_db_admin_on_connect, message is " . $p{DBH}->errstr );
1943 $reportActions = "ACHECK Check 1 : " . $tValues[0] . " PID " . $tValues[1];
1944 $rc = $sth->finish;
1945 $p{DBH}->disconnect;
1946  
1947 if ( $date eq $tValues[0] and $pid eq $tValues[1] ) {
1948 &logger( 5, $reportActions );
1949 $reportActions .= _acheck_db_rotate( CFG => $p{CFG} );
1950 $reportActions .= _acheck_db_purges( CFG => $p{CFG} );
1951  
1952 }
1953 else {
1954 # another process took the action, giving up
1955 &logger( 6, "failed, process locked" );
1956 return ( 5, $reportActions );
1957 }
1958  
1959 # End of the run
1960 $time = _elapsed_seconds($time);
1961 $sql =
1962 'update edtk_admin set ed_action_status = ?, ed_action_duration = ? where ed_action_date = ?';
1963 &logger( 7, $sql );
1964  
1965 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
1966 _db_do_log(
1967 $p{DBH}, $sql,
1968 "ERROR: can't update ED_ACTION_STATUS",
1969 bind => [ "DONE", $time, $date ]
1970 );
1971  
1972 $rc = $sth->finish;
1973 $p{DBH}->disconnect;
1974 return ( 4, $reportActions );
1975 }
1976  
1977 sub _acheck_db_purges {
1978 my %p = @_;
1979  
1980 # my $time =time;
1981 # my $date =strftime "%Y-%m-%d", localtime;
1982 # my $day =strftime "%d", localtime;
1983 my ( $sql, $insert, $result, $reportActions );
1984  
1985 # my $DAYS_KEPT_time = time - (86400*$p{CFG}->{EDTK_DB_MAX_DAYS_KEPT});
1986 my $DAYS_TRACKED_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_TRACKED} );
1987 my $DAYS_KEPT_STATS_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_KEPT_STATS} );
1988 my $DAYS_AGREGED_time = time -
1989 ( 86400 * ( $p{CFG}->{EDTK_DB_MAX_DAYS_AGREGED} || $p{CFG}->{EDTK_DB_MAX_DAYS_TRACKED} ) );
1990  
1991 ### STATS PURGES ###
1992 # PURGE FROM OEDTK_ADMIN
1993 $sql = "delete from edtk_admin where ed_action_date < '"
1994 . ( strftime "%Y-%m-%d", localtime($DAYS_TRACKED_time) ) . "'";
1995 &logger( 7, $sql );
1996  
1997 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
1998 $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update edtk_admin" ) or return;
1999 $p{DBH}->disconnect;
2000 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2001 $reportActions = "ACHECK PURGE edtk_admin=" . ( $result || 0 );
2002  
2003 # PURGE FROM EDTK_DBI_TRACKING
2004 $sql =
2005 "delete from "
2006 . $p{CFG}->{'EDTK_DBI_TRACKING'}
2007 . " where ed_tstamp < '"
2008 . ( strftime "%Y%m%d", localtime($DAYS_TRACKED_time) )
2009 . "000000'";
2010 &logger( 7, $sql );
2011  
2012 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2013 $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_TRACKING'} )
2014 or return;
2015 $p{DBH}->disconnect;
2016 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2017 $reportActions .= "-PURGE TRACKING=" . ( $result || 0 );
2018  
2019 # PURGE FROM EDTK_DBI_DISTRIB_STATS
2020 $sql =
2021 "delete from "
2022 . $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 &logger( 7, $sql );
2027  
2028 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2029 $result =
2030 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} )
2031 or return;
2032 $p{DBH}->disconnect;
2033 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2034 $reportActions .= "-PURGE DISTRIB_S=" . ( $result || 0 );
2035  
2036 # PURGE FROM OUTMNGR_STATS
2037 $sql =
2038 "delete from "
2039 . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'}
2040 . " where ed_dtlot < '"
2041 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_STATS_time) ) . "'";
2042 &logger( 7, $sql );
2043  
2044 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2045 $result =
2046 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} )
2047 or return;
2048 $p{DBH}->disconnect;
2049 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2050 $reportActions .= "-PURGE OUTMNGR_S=" . ( $result || 0 );
2051  
2052 # PURGE FROM EDTK_AGREGE
2053 $sql =
2054 "delete from edtk_agrege "
2055 . " where ed_dtlot < '"
2056 . ( strftime "%Y-%m-%d", localtime($DAYS_AGREGED_time) ) . "'";
2057 &logger( 7, $sql );
2058  
2059 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2060 $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update EDTK_AGREGE" ) or return;
2061 $p{DBH}->disconnect;
2062 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2063 $reportActions .= "-PURGE AGREGE=" . ( $result || 0 );
2064  
2065 ### EDTK_ID ###
2066 # PURGE FROM EDTK_ID
2067 $sql =
2068 "delete from edtk_id"
2069 . " where ed_id_date < '"
2070 . ( strftime "%Y-%m-%d", localtime($DAYS_TRACKED_time) ) . "'";
2071 &logger( 7, $sql );
2072  
2073 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2074 $result =
2075 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2076 $p{DBH}->disconnect;
2077 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2078 $reportActions .= "-PURGE EDTK_ID=" . ( $result || 0 );
2079  
2080 return &logger( 6, $reportActions );
2081 }
2082  
2083 sub _acheck_db_rotate {
2084 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 my ( $sql, $insert, $result, $reportActions );
2091 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2092  
2093 # Repatriate any pending backup rows before rotating / purging.
2094 eval { _db_maybe_reconcile( $p{DBH}, $p{CFG} ); };
2095 my $stamp = strftime "%Y%m%d%H%M%S", localtime;
2096  
2097 my $DAYS_KEPT_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_KEPT} );
2098 my $DAYS_KEPT_STATS_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_KEPT_STATS} );
2099 my $DAYS_TRACKED_time = time - ( 86400 * $p{CFG}->{EDTK_DB_MAX_DAYS_TRACKED} );
2100 my $DAYS_AGREGED_time = time -
2101 ( 86400 * ( $p{CFG}->{EDTK_DB_MAX_DAYS_AGREGED} || $p{CFG}->{EDTK_DB_MAX_DAYS_TRACKED} ) );
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 . $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 &logger( 7, "SQL = $sql" );
2141  
2142 $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update EDTK_AGREGE", fatal => 1 );
2143 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2144 $reportActions .= "-MV AGREGE=" . ( $result || 0 );
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 . $p{CFG}->{'EDTK_DBI_DISTRIB'}
2153 . " where ed_dtlot < '"
2154 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2155 &logger( 7, $sql );
2156  
2157 $result =
2158 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} )
2159 or return;
2160 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2161 $reportActions .= "-MV DISTRIB=" . ( $result || 0 );
2162  
2163 # CLEAN DISTRIB
2164 $sql =
2165 "delete from "
2166 . $p{CFG}->{'EDTK_DBI_DISTRIB'}
2167 . " where ed_dtlot < '"
2168 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2169 &logger( 7, $sql );
2170  
2171 $result =
2172 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} );
2173 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2174 $reportActions .= "/" . ( $result || 0 );
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 . $p{CFG}->{'EDTK_DBI_OUTMNGR'}
2183 . " where ed_dtlot < '"
2184 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2185 &logger( 7, $sql );
2186  
2187 $result =
2188 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2189 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2190 $reportActions .= "-MV OUTMNGR=" . ( $result || 0 );
2191  
2192 # CLEAN OUTMNGR
2193 $sql =
2194 "delete from "
2195 . $p{CFG}->{'EDTK_DBI_OUTMNGR'}
2196 . " where ed_dtlot < '"
2197 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2198 &logger( 7, $sql );
2199  
2200 $result =
2201 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2202 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2203 $reportActions .= "/" . ( $result || 0 );
2204  
2205 $p{DBH}->disconnect;
2206 return ( 4, $reportActions );
2207 }
2208  
2209 sub agrege_idJob {
2210  
2211 # EXAMPLE CALL:
2212 # agrege_idJob (CFG => $cfg, IDJOB => 'IdJob');
2213 my %p = @_;
2214 my $stamp = strftime "%Y%m%d%H%M%S", localtime;
2215 &logger( 6, "p{CFG} = " . $p{CFG} . " - p{IDJOB} " . $p{IDJOB} );
2216  
2217 my ( $sql, $insert, $result, $reportActions );
2218 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
2219  
2220 # Repatriate any pending backup rows before aggregating.
2221 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 . $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 &logger( 7, "SQL = $sql" );
2262  
2263 $result = _db_do_log( $p{DBH}, $sql, "ERROR: can't update edtk_agrege", fatal => 1 );
2264 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2265 $reportActions .= "-MV AGREGE=" . ( $result || 0 );
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 . $p{IDJOB} . "'";
2276 &logger( 7, $sql );
2277  
2278 $result =
2279 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} )
2280 or do { $p{DBH}->disconnect; return ( 4, $reportActions ); };
2281 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2282 $reportActions .= "-MV DISTRIB=" . ( $result || 0 );
2283  
2284 # CLEAN DISTRIB
2285 $sql = "delete from " . $p{CFG}->{'EDTK_DBI_DISTRIB'} . " where ed_idjob = '" . $p{IDJOB} . "'";
2286 &logger( 7, $sql );
2287  
2288 $result =
2289 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_DISTRIB_STATS'} );
2290 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2291 $reportActions .= "/" . ( $result || 0 );
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 . $p{IDJOB} . "'";
2302 &logger( 7, $sql );
2303  
2304 $result =
2305 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2306 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2307 $reportActions .= "-MV OUTMNGR=" . ( $result || 0 );
2308  
2309 # CLEAN OUTMNGR
2310 $sql = "delete from " . $p{CFG}->{'EDTK_DBI_OUTMNGR'} . " where ed_idjob = '" . $p{IDJOB} . "'";
2311 &logger( 7, $sql );
2312  
2313 $result =
2314 _db_do_log( $p{DBH}, $sql, "ERROR: can't update " . $p{CFG}->{'EDTK_DBI_OUTMNGR_STATS'} );
2315 &logger( 6, "RESULT = " . ( $result || 0 ) . " for $sql" );
2316 $reportActions .= "/" . ( $result || 0 );
2317  
2318 $p{DBH}->disconnect;
2319 return ( 4, $reportActions );
2320 }
2321  
2322 sub acheck_db_admin_on_connect {
2323  
2324 # https://www.forknerds.com/reduce-the-size-of-mysql/
2325 # my ($level, $return) = acheck_db_admin_on_connect ($dbh, $cfg);
2326 my $dbh = shift;
2327 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 return ( 5, "ACHECK already running in this process" ) if $IN_ACHECK;
2334 local $IN_ACHECK = 1;
2335  
2336 eval { schema_StaleWarning( $dbh, cfg => $cfg ); };
2337  
2338 my $time = time;
2339 my $date = strftime "%Y-%m-%d", localtime;
2340 my $day = strftime "%d", localtime;
2341 my $pid = $$;
2342 my ( $sth, $sql, $insert, $result, $reportActions );
2343  
2344 my $DAYS_KEPT_time = time - ( 86400 * $cfg->{EDTK_DB_MAX_DAYS_KEPT} );
2345 my $DAYS_KEPT_STATS_time = time - ( 86400 * $cfg->{EDTK_DB_MAX_DAYS_KEPT_STATS} );
2346 my $DAYS_TRACKED_time = time - ( 86400 * $cfg->{EDTK_DB_MAX_DAYS_TRACKED} );
2347 my $DAYS_AGREGED_time =
2348 time - ( 86400 * ( $cfg->{EDTK_DB_MAX_DAYS_AGREGED} || $cfg->{EDTK_DB_MAX_DAYS_TRACKED} ) );
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 eval { _db_maybe_reconcile( $dbh, $cfg ); };
2354  
2355 &logger( 6, "ACHECK Check START" );
2356  
2357 #LOOK FOR THE LAST ACTION ON THE ADMIN TABLE
2358 $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 &logger( 7, $sql );
2364  
2365 $sth = $dbh->prepare($sql) or return ( 3, $dbh->errstr );
2366  
2367 do { local $sth->{PrintError} = 0; $sth->execute() }
2368 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
2369  
2370 # HAS AN ADMINISTRATION ACTION ALREADY BEEN DONE TODAY ?
2371 my @tValues = $dbh->selectrow_array( $sql, undef )
2372 ; # or warn ("ERROR: in acheck_db_admin_on_connect, message is " . $dbh->errstr);
2373 if ( $tValues[0] and $date eq $tValues[0] ) {
2374 &logger(
2375 6,
2376 (
2377 "Previously done, ACHECK Last EDTK_DB_MAX_DAYS check : "
2378 . $tValues[0] . " PID "
2379 . $tValues[1]
2380 )
2381 );
2382 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 'insert into edtk_admin (ed_action_date, ed_action_pid, ed_action_status, ed_oedtk_release) '
2389 . ' values (?, ?, ?, ?) ';
2390 $sth = $dbh->prepare_cached($insert);
2391  
2392 eval {
2393 do { local $sth->{PrintError} = 0; $sth->execute( $date, $pid, "START", $VERSION ) }
2394 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
2395 };
2396 if ($@) {
2397 &logger( 3, "ERROR: $@ into $insert" );
2398 }
2399  
2400 # CHECK THAT WE HOLD THE LOCK FOR THE ACTION
2401 $sth = $dbh->prepare($sql);
2402 do { local $sth->{PrintError} = 0; $sth->execute() }
2403 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
2404 @tValues = do { local $dbh->{PrintError} = 0; $dbh->selectrow_array( $sql, undef ) }
2405 or &logger( 3, "ERROR: in acheck_db_admin_on_connect, message is " . $dbh->errstr );
2406 $reportActions = "ACHECK Check 2 : " . $tValues[0] . " PID " . $tValues[1];
2407  
2408 if ( $date eq $tValues[0] and $pid eq $tValues[1] ) {
2409 &logger( 5, $reportActions );
2410  
2411 # _db_admin_actions;
2412 }
2413 else {
2414 # another process did the action, giving up
2415 return ( 5, $reportActions );
2416 }
2417  
2418 ### PURGES ###
2419 # PURGE FROM OEDTK_ADMIN
2420 $sql = "delete from edtk_admin where ed_action_date < '"
2421 . ( strftime "%Y-%m-%d", localtime($DAYS_TRACKED_time) ) . "'";
2422 &logger( 7, $sql );
2423  
2424 $result = _db_do_log( $dbh, $sql, "ERROR: can't update EDTK_ADMIN" ) or return;
2425 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2426 $reportActions = "ACHECK PURGE edtk_admin=" . ( $result // 0 );
2427  
2428 # PURGE FROM EDTK_DBI_TRACKING
2429 $sql =
2430 "delete from "
2431 . $cfg->{'EDTK_DBI_TRACKING'}
2432 . " where ed_tstamp < '"
2433 . ( strftime "%Y%m%d", localtime($DAYS_TRACKED_time) )
2434 . "000000'";
2435 &logger( 7, $sql );
2436  
2437 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_TRACKING'} )
2438 or return;
2439 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2440 $reportActions .= "-PURGE tracking=" . ( $result // 0 );
2441  
2442 # PURGE FROM EDTK_DBI_DISTRIB_STATS
2443 $sql =
2444 "delete from "
2445 . $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 &logger( 7, $sql );
2450  
2451 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_DISTRIB_STATS'} )
2452 or return;
2453 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2454 $reportActions .= "-PURGE distrib_s=" . ( $result // 0 );
2455  
2456 # PURGE FROM OUTMNGR_STATS
2457 $sql =
2458 "delete from "
2459 . $cfg->{'EDTK_DBI_OUTMNGR_STATS'}
2460 . " where ed_dtlot < '"
2461 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_STATS_time) ) . "'";
2462 &logger( 7, $sql );
2463  
2464 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_OUTMNGR_STATS'} )
2465 or return;
2466 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2467 $reportActions .= "-PURGE outmngr_s=" . ( $result // 0 );
2468  
2469 # PURGE FROM EDTK_AGREGE
2470 $sql =
2471 "delete from edtk_agrege "
2472 . " where ed_dtlot < '"
2473 . ( strftime "%Y-%m-%d", localtime($DAYS_AGREGED_time) ) . "'";
2474 &logger( 7, $sql );
2475  
2476 $result = _db_do_log( $dbh, $sql, "ERROR: can't update EDTK_AGREGE" ) or return;
2477 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2478 $reportActions .= "-PURGE agrege=" . ( $result // 0 );
2479 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 . $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 &logger( 7, "SQL = $sql" );
2519  
2520 $result = _db_do_log( $dbh, $sql, "ERROR: can't update EDTK_AGREGE", fatal => 1 );
2521 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2522 $reportActions .= "-MV agrege=" . ( $result // 0 );
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 . $cfg->{'EDTK_DBI_DISTRIB'}
2531 . " where ed_dtlot < '"
2532 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2533 &logger( 7, $sql );
2534  
2535 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_DISTRIB_STATS'} )
2536 or return;
2537 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2538 $reportActions .= "-MV distrib=" . ( $result // 0 );
2539  
2540 # CLEAN DISTRIB
2541 $sql =
2542 "delete from "
2543 . $cfg->{'EDTK_DBI_DISTRIB'}
2544 . " where ed_dtlot < '"
2545 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2546 &logger( 7, $sql );
2547  
2548 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_DISTRIB_STATS'} );
2549 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2550 $reportActions .= "/" . ( $result // 0 );
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 . $cfg->{'EDTK_DBI_OUTMNGR'}
2559 . " where ed_dtlot < '"
2560 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2561 &logger( 7, $sql );
2562  
2563 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_OUTMNGR_STATS'} );
2564 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2565 $reportActions .= "-MV outmngr=" . ( $result // 0 );
2566  
2567 # CLEAN OUTMNGR
2568 $sql =
2569 "delete from "
2570 . $cfg->{'EDTK_DBI_OUTMNGR'}
2571 . " where ed_dtlot < '"
2572 . ( strftime "%Y-%m-%d", localtime($DAYS_KEPT_time) ) . "'";
2573 &logger( 7, $sql );
2574  
2575 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_OUTMNGR_STATS'} );
2576 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2577 $reportActions .= "/" . ( $result // 0 );
2578  
2579 ### EDTK_ID ###
2580 # PURGE FROM EDTK_ID
2581 $sql =
2582 "delete from edtk_id"
2583 . " where ed_id_date < '"
2584 . ( strftime "%Y-%m-%d", localtime($DAYS_TRACKED_time) ) . "'";
2585 &logger( 7, $sql );
2586  
2587 $result = _db_do_log( $dbh, $sql, "ERROR: can't update " . $cfg->{'EDTK_DBI_OUTMNGR_STATS'} );
2588 &logger( 6, "RESULT = " . ( $result // 0 ) . " for $sql" );
2589 $reportActions .= "-PURGE edtk_id=" . ( $result // 0 );
2590  
2591 # End of the run
2592 $time = _elapsed_seconds($time);
2593 $sql =
2594 'update edtk_admin set ed_action_status = ?, ed_action_duration = ? where ed_action_date = ?';
2595 _db_do_log(
2596 $dbh, $sql,
2597 "ERROR: can't update ED_ACTION_STATUS",
2598 bind => [ "DONE", $time, $date ]
2599 );
2600  
2601 return ( 4, $reportActions );
2602 }
2603  
2604 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 sub create_table_TRACKING {
2633 my ( $dbh, $table, $maxkeys ) = @_;
2634  
2635 my $sql = "create table if not exists $table ("
2636 . join( ', ', map { "$$_[0] $$_[1]" } @TRACKER_COLS ) . ", ";
2637  
2638 foreach my $i ( 0 .. $maxkeys ) {
2639 $sql .= " ed_k${i}_NAME VARCHAR2(8),"; # Name of key $i
2640 $sql .= " ed_k${i}_VAL VARCHAR2(128)"; # Value of key $i
2641 $sql .= "," unless ( $i == $maxkeys );
2642 }
2643 $sql .= " )";
2644 $sql .= _db_engine_clause($dbh);
2645 &logger( 7, $sql );
2646 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
2647  
2648 # my $idx = "ix_".$table."_".$VERSION_TXT;
2649 my $idx = "ix_" . $table;
2650 $sql = "create index if not exists $idx on $table " . " (ed_tstamp);";
2651 &logger( 7, $sql );
2652 _db_do_ddl( $dbh, $sql )
2653 or &logger( 3, $dbh->errstr )
2654 if ( _db_check_driver_name($dbh) ne "SQLite" );
2655  
2656 }
2657  
2658 sub db_drop_table {
2659 my ( $dbh, $table ) = @_;
2660 my $sql = "drop table $table";
2661  
2662 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
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 sub db_backup_available {
2682 my ($cfg) = @_;
2683 return 0 unless $cfg && defined $cfg->{'EDTK_DBI_DSN_BAK'};
2684 my $main = $cfg->{'EDTK_DBI_DSN'} // '';
2685 my $bak = $cfg->{'EDTK_DBI_DSN_BAK'} // '';
2686 return 0 if $bak eq '';
2687 return 0 if $bak eq $main; # anti-loop guard: backup == main
2688 return 1;
2689 }
2690  
2691 # Does this handle point at the backup buffer?
2692 sub db_on_backup {
2693 my ($dbh) = @_;
2694 return ( defined $dbh && $dbh->{'private_oEdtk_on_backup'} ) ? 1 : 0;
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 sub _db_identity {
2702 my ($dbh) = @_;
2703 return unless defined $dbh;
2704 my $drv = eval { _db_check_driver_name($dbh) };
2705 return unless defined $drv;
2706 return do {
2707 local $dbh->{PrintError} = 0;
2708 local $dbh->{RaiseError} = 0;
2709 my @parts;
2710 if ( $drv eq 'SQLite' ) {
2711  
2712 # PRAGMA database_list canonicalizes the file path, so ".../main.db"
2713 # and "..././main.db" resolve to the same absolute path.
2714 my $rows = eval { $dbh->selectall_arrayref('pragma database_list') };
2715 my ($main) = grep { $_->[1] eq 'main' } @{ $rows || [] };
2716 push @parts, 'sqlite', ( $main ? ( $main->[2] // '' ) : '' );
2717 }
2718 elsif ( $drv eq 'PostgreSQL' ) {
2719 my ( $d, $h, $p ) = eval {
2720 $dbh->selectrow_array(
2721 'select current_database(), inet_server_addr()::text, inet_server_port()');
2722 };
2723 push @parts, 'pg', ( $d // '' ), ( $h // '' ), ( $p // '' );
2724 }
2725 elsif ( $drv eq 'mysql' ) {
2726 my ( $d, $h, $p ) =
2727 eval { $dbh->selectrow_array('select database(), @@hostname, @@port') };
2728 push @parts, 'mysql', ( $d // '' ), ( $h // '' ), ( $p // '' );
2729 }
2730 else { return }
2731 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 sub _db_same_database {
2739 my ( $a, $b ) = @_;
2740 my $ka = _db_identity($a);
2741 my $kb = _db_identity($b);
2742 return 0 unless defined $ka && defined $kb;
2743 return $ka eq $kb ? 1 : 0;
2744 }
2745  
2746 # Open the backup buffer (never fatal, never blocking).
2747 sub _db_backup_connect {
2748 my ($cfg) = @_;
2749 return unless db_backup_available($cfg);
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 my %bcfg = ( %$cfg, EDTK_WAITRUN => 0, EDTK_DB_CHECK_AUTO => 'NO' );
2755 my $bak = eval {
2756 _db_connect1(
2757 \%bcfg,
2758 'EDTK_DBI_DSN_BAK',
2759 {
2760 FetchHashKeyName => $cfg->{'EDTK_DB_FetchHashKeyName'} || 'NAME_uc',
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 $bak->{'private_oEdtk_on_backup'} = 1 if defined $bak;
2769 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 sub _backup_table_registry {
2775 my ($cfg) = @_;
2776 my @t;
2777 push @t,
2778 { table => $cfg->{'EDTK_DBI_TRACKING'}, keys => [qw(ed_tstamp ed_sngl_id ed_seq ed_app)] }
2779 if $cfg->{'EDTK_DBI_TRACKING'};
2780 push @t, { table => $cfg->{'EDTK_DBI_ACQUIT'}, keys => [qw(ed_seqlot ed_lotname ed_dtpost)] }
2781 if $cfg->{'EDTK_DBI_ACQUIT'};
2782 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 if $cfg->{'EDTK_DBI_OUTMNGR'};
2789 push @t,
2790 {
2791 table => $cfg->{'EDTK_DBI_DISTRIB'},
2792 keys => [qw(ed_idldoc ed_seqdoc ed_idseqpg ed_idjob)]
2793 }
2794 if $cfg->{'EDTK_DBI_DISTRIB'};
2795 return @t;
2796 }
2797  
2798 # Guarantee the backup buffer can hold the event tables (resolves TODO in db_connect).
2799 sub db_backup_prepare {
2800 my ($bak_dbh) = @_;
2801 return 0 unless defined $bak_dbh;
2802 my $ok = eval {
2803 my $cfg = config_read('EDTK_DB');
2804 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 unless ( _table_exists( $bak_dbh, $cfg->{'EDTK_DBI_TRACKING'} ) ) {
2809 create_table_TRACKING(
2810 $bak_dbh,
2811 $cfg->{'EDTK_DBI_TRACKING'},
2812 $cfg->{'EDTK_MAX_USER_KEY'}
2813 );
2814 }
2815 1;
2816 };
2817 &logger( 3, "db_backup_prepare: could not prepare the backup schema: $@" ) unless $ok;
2818 return $ok ? 1 : 0;
2819 }
2820  
2821 # Count pending rows per buffer table (read-only detection).
2822 sub db_backup_pending {
2823 my ($cfg) = @_;
2824 my %pending;
2825 return \%pending unless db_backup_available($cfg);
2826 my $bak = _db_backup_connect($cfg);
2827 unless ($bak) {
2828 &logger( 7, "db_backup_pending: backup database unreachable" );
2829 return \%pending;
2830 }
2831 for my $t ( _backup_table_registry($cfg) ) {
2832 my $n = eval { my ($c) = $bak->selectrow_array("select count(*) from $t->{table}"); $c };
2833 $pending{ $t->{table} } = $n if defined $n && $n > 0;
2834 }
2835 eval { $bak->disconnect };
2836 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 sub _reconcile_one_table {
2842 my ( $main, $bak, $t, %p ) = @_;
2843 my $table = $t->{table};
2844 my @keys = @{ $t->{keys} };
2845 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 my $n = do {
2851 local $bak->{PrintError} = 0;
2852 local $bak->{RaiseError} = 0;
2853 eval { my ($c) = $bak->selectrow_array("select count(*) from $table"); $c };
2854 };
2855 unless ( defined $n ) {
2856 &logger( 7, "_reconcile_one_table: '$table' absent from the backup" );
2857 return $out;
2858 }
2859 return $out if $n == 0;
2860 if ( $p{dry_run} ) { $out->{read} = $n; return $out; }
2861  
2862 my $sth_rd = $bak->prepare("select * from $table");
2863 unless ( $sth_rd && $sth_rd->execute ) {
2864 &logger( 3,
2865 "_reconcile_one_table: cannot read '$table' from the backup: "
2866 . ( $bak->errstr // '' ) );
2867 $out->{ok} = 0;
2868 return $out;
2869 }
2870 my $raw_cols = $sth_rd->{NAME}; # buffer column names (raw order)
2871  
2872 my ( $norm_id, $norm_table, @norm_cols ) = _norm_identifiers( $main, $table, $raw_cols );
2873 my $meta = _get_col_meta( $main, $norm_table, $norm_id );
2874 my $clean = _make_clean_val($meta);
2875  
2876 my @uk = map { $norm_id->($_) } @keys;
2877 my $sql_exists = "select 1 from $norm_table where " . join( ' and ', map { "$_ = ?" } @uk );
2878 my $sql_insert =
2879 "insert into $norm_table ("
2880 . join( ',', @norm_cols ) . ")"
2881 . " values ("
2882 . join( ',', ('?') x @norm_cols ) . ")";
2883 my $sth_chk = $main->prepare($sql_exists);
2884 my $sth_ins = $main->prepare($sql_insert);
2885 &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 my %norm2raw;
2893 for my $i ( 0 .. $#$raw_cols ) { $norm2raw{ $norm_id->( $raw_cols->[$i] ) } = $raw_cols->[$i]; }
2894 my @del_cols = map { $norm2raw{ $norm_id->($_) } // $_ } @keys;
2895 my $sql_del = "delete from $table where " . join( ' and ', map { "$_ = ?" } @del_cols );
2896 my @read_keys;
2897  
2898 while ( my $row = $sth_rd->fetchrow_arrayref ) {
2899 $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 my %by_name;
2904 for my $i ( 0 .. $#$raw_cols ) { $by_name{ $norm_id->( $raw_cols->[$i] ) } = $row->[$i]; }
2905 push @read_keys, [ map { $by_name{ $norm_id->($_) } } @keys ];
2906  
2907 my $dup = eval {
2908 local $sth_chk->{PrintError} = 0;
2909 $sth_chk->execute( map { $clean->( $_, $by_name{$_} ) } @uk );
2910 my ($x) = $sth_chk->fetchrow_array;
2911 $sth_chk->finish;
2912 $x;
2913 };
2914 if ($dup) { $out->{skipped}++; next; }
2915  
2916 my $ok = eval {
2917 local $sth_ins->{PrintError} = 0;
2918 $sth_ins->execute( map { $clean->( $_, $by_name{$_} ) } @norm_cols );
2919 1;
2920 };
2921 if ($ok) { $out->{written}++ }
2922 else {
2923 &logger( 3,
2924 "_reconcile_one_table: insert into '$table' failed: " . ( $main->errstr // $@ ) );
2925 $out->{ok} = 0;
2926 last;
2927 }
2928 }
2929 $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 if ( $out->{ok} && !$p{keep_backup} ) {
2935 if ( @read_keys != $out->{read} ) {
2936 &logger( 3, "_reconcile_one_table: '$table' read/key mismatch, buffer not drained" );
2937 $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 my $own_tx = eval { $bak->{AutoCommit} };
2943 eval { $bak->begin_work } if $own_tx;
2944 my $bad;
2945 for my $kv (@read_keys) {
2946 my $ok = eval {
2947 local $bak->{PrintError} = 0;
2948 local $bak->{RaiseError} = 0;
2949 $bak->do( $sql_del, undef, @$kv );
2950 1;
2951 };
2952 unless ($ok) { $bad = $bak->errstr // $@ // 'unknown error'; last; }
2953 }
2954 if ( defined $bad ) {
2955 eval { $bak->rollback } if $own_tx;
2956 &logger( 3, "_reconcile_one_table: could not drain '$table': $bad" );
2957 $out->{ok} = 0;
2958 }
2959 else {
2960 eval { $bak->commit } if $own_tx;
2961 }
2962 }
2963 }
2964 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 sub db_reconcile_backup {
2971 my ( $main_dbh, %p ) = @_;
2972 my $cfg = $p{CFG} || config_read('EDTK_DB');
2973 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 if ($IN_RECONCILE) {
2978 &logger( 7, "db_reconcile_backup: already running in this process, skipping" );
2979 return $res;
2980 }
2981 local $IN_RECONCILE = 1;
2982  
2983 unless ( db_backup_available($cfg) ) {
2984 &logger( 7, "db_reconcile_backup: no distinct backup database configured, nothing to do" );
2985 return $res;
2986 }
2987 if ( db_on_backup($main_dbh) ) {
2988 &logger( 7, "db_reconcile_backup: current handle is the backup itself, skipping" );
2989 return $res;
2990 }
2991  
2992 my $bak = _db_backup_connect($cfg);
2993 unless ($bak) {
2994 &logger( 3, "db_reconcile_backup: backup database unreachable, no repatriation" );
2995 $res->{ok} = 0;
2996 $res->{error} = 'backup unreachable';
2997 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 if ( _db_same_database( $main_dbh, $bak ) ) {
3004 &logger( 3,
3005 "db_reconcile_backup: main and backup handles designate the same database, refusing" );
3006 $res->{ok} = 0;
3007 $res->{error} = 'main and backup are the same database';
3008 eval { $bak->disconnect };
3009 return $res;
3010 }
3011  
3012 my @tables = $p{tables} ? @{ $p{tables} } : _backup_table_registry($cfg);
3013 &logger( 6, "checking if backup data needs reconciliation ..." );
3014  
3015 for my $t (@tables) {
3016 my $r = _reconcile_one_table( $main_dbh, $bak, $t, %p );
3017 $res->{tables}{ $t->{table} } = $r;
3018 $res->{written} += $r->{written};
3019 $res->{ok} = 0 unless $r->{ok};
3020 }
3021 eval { $bak->disconnect };
3022 return $res;
3023 }
3024  
3025 # Best-effort hook: repatriate before a maintenance operation. Never fatal.
3026 sub _db_maybe_reconcile {
3027 my ( $dbh, $cfg ) = @_;
3028 return unless defined $dbh && defined $cfg && db_backup_available($cfg);
3029 eval {
3030 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 if ( $r->{written} || 0 ) > 0;
3034 };
3035 &logger( 3, "db_reconcile_backup failed: $@" ) if $@;
3036 return;
3037 }
3038  
3039 sub historicize_table {
3040 my ( $dbh, $table, $suffixe ) = @_;
3041 my $table_cible = $table . "_" . $suffixe;
3042  
3043 copy_table( $dbh, $table, $table_cible, '-create' );
3044  
3045 # SQLite has no TRUNCATE statement; DELETE achieves the same move of the data.
3046 my $sql =
3047 ( _db_check_driver_name($dbh) eq 'SQLite' )
3048 ? "delete from $table"
3049 : "truncate table $table";
3050 &logger( 7, $sql );
3051  
3052 _db_do_log( $dbh, _sql_fixup( $dbh, $sql, 'casse' ), "ERROR: can't $sql", fatal => 1 );
3053 }
3054  
3055 sub create_table_ADMIN {
3056 my $dbh = shift;
3057 my $table = "edtk_admin";
3058  
3059 my $sql = "create table if not exists $table ";
3060 $sql .= "( ed_action_date date not null";
3061 $sql .= ", ed_action_pid integer not null";
3062 $sql .= ", ed_action_status varchar2(16)";
3063 $sql .= ", ed_action_duration integer";
3064 $sql .= ", ed_oedtk_release varchar2(8) not null";
3065 $sql .= ", primary key (ed_action_date)";
3066 $sql .= " )";
3067 $sql .= _db_engine_clause($dbh);
3068 &logger( 7, $sql );
3069  
3070 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3071 }
3072  
3073 sub create_table_ID {
3074 my $dbh = shift;
3075 my $table = "edtk_id";
3076  
3077 my $sql = "create table if not exists $table ";
3078 $sql .= "( ed_id_date date not null"; # 2021-05-19
3079 $sql .= ", ed_id_value varchar2(25) unique";
3080 $sql .= ", ed_id_chanel_out varchar2(32)";
3081 $sql .= ", primary key (ed_id_value)";
3082 $sql .= " )";
3083 $sql .= _db_engine_clause($dbh);
3084  
3085 &logger( 7, $sql );
3086  
3087 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3088  
3089 # my $idx = "ix_".$table."_".$VERSION_TXT;
3090 my $idx = "ix_" . $table;
3091 $sql = "create index if not exists $idx on $table (ed_id_date);";
3092 &logger( 7, $sql );
3093 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3094  
3095 }
3096  
3097 sub create_table_FILIERES {
3098 my $dbh = shift;
3099 my $table = "edtk_filieres";
3100  
3101 my $sql = "create table if not exists $table ";
3102 $sql .= "( ed_idfiliere varchar2(5) unique"; #
3103 $sql .= ", ed_priorite integer unique"; #
3104 $sql .= ", ed_idmanufact varchar2(16)";
3105 $sql .= ", ed_designation varchar2(64)"; #
3106 $sql .= ", ed_actif char(1) not null"; # flag: whether that business line (filiere) is active
3107 $sql .= ", ed_typed char(1) not null"; #
3108 $sql .= ", ed_modedi char(1) not null"; #
3109 $sql .= ", ed_idgplot varchar2(16) not null"; #
3110 $sql .= ", ed_nbbacprn integer not null"; #
3111 $sql .= ", ed_nbencmax integer";
3112 $sql .= ", ed_minfeuil_l integer";
3113 $sql .= ", ed_maxfeuil_l integer";
3114 $sql .= ", ed_feuilpli integer";
3115 $sql .= ", ed_minplis integer";
3116 $sql .= ", ed_maxplis integer not null";
3117 $sql .= ", ed_poids_pli integer"; # maximum weight of the folded item in the line
3118 $sql .= ", ed_ref_env varchar2(8) not null";
3119 $sql .= ", ed_formflux varchar2(3) not null";
3120 $sql .= ", ed_sort varchar2(128) not null";
3121 $sql .= ", ed_direction varchar2(4) not null";
3122 $sql .= ", ed_postcomp varchar2(8) not null";
3123 $sql .= ", primary key (ed_idfiliere, ed_priorite)";
3124 $sql .= " )";
3125 $sql .= _db_engine_clause($dbh);
3126 &logger( 7, $sql );
3127  
3128 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3129 }
3130  
3131 sub create_table_LOTS {
3132 my $dbh = shift;
3133 my $table = "edtk_lots";
3134  
3135 my $sql = "create table if not exists $table ";
3136 $sql .= "( ed_idlot varchar2(8) not null"
3137 ; # rendre unique ? -> alter table edtk_lots modify ed_idlot varchar2(8) not null
3138 $sql .= ", ed_priorite integer unique"; #
3139 $sql .= ", ed_idappdoc varchar2(20)"; #
3140 $sql .= ", ed_refiddoc varchar2(20) not null"; #
3141 $sql .= ", ed_cpdest varchar2(10)"; #
3142 $sql .= ", ed_filter varchar2(64)"; #
3143 $sql .= ", ed_refenc varchar2(32)"; #
3144 $sql .= ", ed_groupby varchar2(16)";
3145 $sql .= ", ed_lotname varchar2(64) not null"; #
3146 $sql .= ", ed_idgplot varchar2(16) not null";
3147 $sql .= ", ed_idmanufact varchar2(16) not null";
3148 $sql .= ", ed_consigne varchar2(250) "; #
3149 $sql .= ", primary key (ed_idlot, ed_priorite)";
3150 $sql .= " )";
3151 $sql .= _db_engine_clause($dbh);
3152 &logger( 7, $sql );
3153  
3154 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3155 }
3156  
3157 sub create_table_REFIDDOC {
3158 my $dbh = shift;
3159 my $table = "edtk_refiddoc";
3160  
3161 my $sql = "create table if not exists $table ";
3162 $sql .= "( ed_refiddoc varchar2(20) unique";
3163 $sql .= ", ed_corp varchar2(8) not null"; # entity related to the document
3164 $sql .= ", ed_catdoc char(1) not null";
3165 $sql .= ", ed_portadr char(1) not null";
3166 $sql .= ", ed_massmail char(1) not null";
3167 $sql .= ", ed_edocshare char(1) not null";
3168 $sql .= ", ed_typed char(1) not null";
3169 $sql .= ", ed_modedi char(1) not null";
3170 $sql .= ", ed_pgorien varchar2(2)";
3171 $sql .= ", ed_formatp varchar2(2)";
3172 $sql .= ", ed_refimp_p1 varchar2(16)";
3173 $sql .= ", ed_refimp_ps varchar2(16)";
3174 $sql .= ", ed_refimp_refiddoc varchar2(64)";
3175 $sql .= ", ed_mail_referent varchar2(300)"; # referent mail for doc validation
3176 $sql .= ", primary key (ed_refiddoc, ed_corp, ed_catdoc)";
3177 $sql .= " )";
3178 $sql .= _db_engine_clause($dbh);
3179 &logger( 7, $sql );
3180  
3181 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3182 }
3183  
3184 sub create_table_SUPPORTS {
3185 my $dbh = shift;
3186 my $table = "edtk_supports";
3187  
3188 my $sql = "create table if not exists $table ";
3189 $sql .= "( ed_refimp varchar2(16) unique"; #
3190 $sql .= ", ed_typimp char(1) not null";
3191 $sql .= ", ed_formatp varchar2(2) not null";
3192 $sql .= ", ed_poidsunit integer not null";
3193 $sql .= ", ed_feuimax integer";
3194 $sql .= ", ed_poidsmax integer";
3195 $sql .= ", ed_bac_insert integer";
3196 $sql .= ", ed_copygroup varchar2(16)";
3197 $sql .= ", ed_optctrl varchar2(8)";
3198 $sql .= ", ed_debvalid varchar2(8)";
3199 $sql .= ", ed_finvalid varchar2(8)";
3200 $sql .= ", primary key (ed_refimp)";
3201 $sql .= " )";
3202 $sql .= _db_engine_clause($dbh);
3203 &logger( 7, $sql );
3204  
3205 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3206 }
3207  
3208 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 sub create_table_DISTRIB {
3231 my ( $dbh, $table ) = @_;
3232  
3233 my $sql =
3234 "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 $sql .= _db_engine_clause($dbh);
3239 &logger( 7, $sql );
3240  
3241 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3242  
3243 # my $idx = "ix_".$table."_".$VERSION_TXT;
3244 my $idx = "ix_" . $table;
3245  
3246 $sql = "create index if not exists $idx on $table "
3247 . " (ed_idldoc, ed_seqdoc, ed_idseqpg, ed_idjob, ed_chanel_out, ed_dtlot);";
3248 &logger( 7, $sql );
3249 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
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 for my $spec ( [ 'job', 'ed_idjob' ], [ 'dtlot', 'ed_dtlot' ] ) {
3256 my ( $sfx, $col ) = @$spec;
3257 $sql = "create index if not exists ${idx}_$sfx on $table ($col);";
3258 &logger( 7, $sql );
3259 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3260 }
3261  
3262 }
3263  
3264 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 sub create_table_AGREGE {
3282 my ($dbh) = @_;
3283 my $table = "edtk_agrege";
3284  
3285 my $sql = "create table if not exists $table ("
3286 . join( ', ', map { "$$_[0] $$_[1]" } @AGREGE_COLS ) . " )";
3287 $sql .= _db_engine_clause($dbh);
3288 &logger( 7, $sql );
3289  
3290 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3291  
3292 # my $idx = "ix_".$table."_".$VERSION_TXT;
3293 my $idx = "ix_" . $table;
3294 $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 &logger( 7, $sql );
3297 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3298  
3299 }
3300  
3301 sub create_table_PARA {
3302 my $dbh = shift;
3303 my $table = "edtk_test_para";
3304  
3305 my $sql = "create table if not exists $table ";
3306 $sql .= "( ed_para_refiddoc varchar2(20) not null";
3307 $sql .= ", ed_para_corp varchar2(8) not null"; # entity related to the document
3308 $sql .= ", ed_id integer unique"; #
3309 $sql .= ", ed_tstamp varchar2(14) not null"; # timestamp of event
3310 $sql .= ", ed_textbloc varchar2(512)";
3311 $sql .= ", primary key (ed_para_refiddoc, ed_para_corp, ed_id)";
3312 $sql .= " )";
3313 $sql .= _db_engine_clause($dbh);
3314 &logger( 7, $sql );
3315  
3316 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3317 }
3318  
3319 sub create_table_DATAGROUPS {
3320 my $dbh = shift;
3321 my $table = "edtk_test_datagroups";
3322  
3323 my $sql = "create table if not exists $table ";
3324 $sql .= "( ed_dgps_refiddoc varchar2(20) not null";
3325 $sql .= ", ed_id integer not null";
3326 $sql .= ", ed_data varchar2(64)";
3327 $sql .= " )";
3328 $sql .= _db_engine_clause($dbh);
3329  
3330 &logger( 7, $sql );
3331  
3332 _db_do_ddl( $dbh, $sql ) or die &logger( -1, $dbh->errstr );
3333  
3334 # my $idx = "ix_".$table."_".$VERSION_TXT;
3335 my $idx = "ix_" . $table;
3336 $sql = "create index if not exists $idx on $table " . " (ed_dgps_refiddoc, ed_id);";
3337 &logger( 7, $sql );
3338 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3339  
3340 }
3341  
3342 sub create_table_ACQUIT {
3343 my $dbh = shift;
3344 my $table = "edtk_acq";
3345  
3346 my $sql = "create table if not exists $table ";
3347 $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 $sql .= ", ed_lotname varchar2(16) not null"; #
3350 $sql .= ", ed_dtpost varchar2(8) not null"; # mailing-out date
3351 $sql .= ", ed_dtprint varchar2(8)"; # print date
3352 $sql .= ", ed_nbfaces integer not null"
3353 ; # number of sides of the batch (accounting sides, including blank recto/verso sides)
3354 $sql .= ", ed_nbplis integer not null"; # number of documents in the folded item
3355 $sql .= ", ed_dtpost2 varchar2(8)"; # mailing-out date
3356 $sql .= ", ed_dtcheck varchar2(8)"; # check date
3357 $sql .= ", ed_status varchar2(4)"; # check status
3358 $sql .= ", primary key (ed_seqlot, ed_lotname, ed_dtpost)";
3359 $sql .= " )";
3360 $sql .= _db_engine_clause($dbh);
3361  
3362 &logger( 7, $sql );
3363  
3364 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
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 sub _acquit_table_INDEX {
3372 my ( $dbh, $data, $table ) = @_;
3373 my ($pli) = ( ( $data->[ACQ_FIELD_PLI] // '' ) =~ m/_(\d*)\z/ );
3374 my $lot = $data->[ACQ_FIELD_LOT];
3375 my $annee = substr( $data->[ACQ_FIELD_DTLOT], 0, 4 );
3376 my $exped = substr( $data->[ACQ_FIELD_EXPED], 0, 8 );
3377 my $iddest = $data->[ACQ_FIELD_IDDEST];
3378 my $status = $data->[ACQ_FIELD_STATUS];
3379  
3380 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 my $sth = $dbh->prepare($sql);
3383 $sth->execute( $exped, $status, $lot, $iddest, $annee, $pli )
3384 or &logger( 3, "acquit_index: update failed: " . $sth->errstr );
3385 if ( $sth->rows == 0 ) {
3386 &logger( 3,
3387 "acquit_index: no indexed item for lot $lot, id_dest $iddest, year $annee, item $pli" );
3388 }
3389 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 sub _acquit_docid {
3396 my ( $dbh, $table, $data ) = @_;
3397 return unless defined $table && length $table;
3398 my $lot = $data->[ACQ_FIELD_LOT];
3399 my $annee = substr( $data->[ACQ_FIELD_DTLOT], 0, 4 );
3400 my $exped = substr( $data->[ACQ_FIELD_EXPED], 0, 8 );
3401 my $iddest = $data->[ACQ_FIELD_IDDEST];
3402 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 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 my $row = eval {
3411 my $sth = $dbh->prepare($sql);
3412 $sth->execute( $exped, $status, $lot, $iddest, $annee, $status, $lot, $iddest ) or return;
3413 $sth->fetchrow_arrayref();
3414 };
3415 return unless ref $row eq 'ARRAY' && defined $row->[0];
3416 my $seqpg = defined $row->[1] ? $row->[1] + 0 : 0;
3417 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 sub _acquit_API {
3427 my ( $dbh, $data, $cfg ) = @_;
3428 my $name = $cfg->{'EDTK_ACQUIT_API'};
3429 unless ( defined $name && length $name ) {
3430 &logger( 5, "acquit_api: EDTK_ACQUIT_API is not set, no API acquittal" );
3431 return 0;
3432 }
3433  
3434 my $exped = substr( $data->[ACQ_FIELD_EXPED], 0, 8 );
3435 my $docid = _acquit_docid( $dbh, $cfg->{'EDTK_DBI_OUTMNGR'}, $data );
3436 $docid = $data->[ACQ_FIELD_LOT] unless defined $docid;
3437  
3438 require oEdtk::Ext;
3439 eval { oEdtk::Ext::call_named_callable( $cfg, 'EDTK_ACQUIT_API', $docid, $exped, $cfg ) };
3440 &logger( 3, "acquit_api: callable '$name' failed: $@" ) if $@;
3441 return 0;
3442 }
3443  
3444 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 sub create_table_OUTMNGR {
3540 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 my $pk_idjob = exists $opt{pk_idjob} ? $opt{pk_idjob} : _pk_idjob_default();
3545 my @pk = qw(ed_idldoc ed_seqdoc ed_idseqpg);
3546 push @pk, 'ed_idjob' if $pk_idjob;
3547  
3548 my $sql =
3549 "create table if not exists $table ("
3550 . join( ', ', map { "$$_[0] $$_[1]" } @INDEX_COLS ) . ", "
3551 . " primary key ("
3552 . join( ', ', @pk ) . ")" . " )";
3553 $sql .= _db_engine_clause($dbh);
3554 &logger( 7, $sql );
3555  
3556 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3557  
3558 # my $idx = "ix_".$table."_".$VERSION_TXT;
3559 my $idx = "ix_" . $table;
3560 $sql = "create index if not exists $idx on $table " . " (ed_dtedtion, ed_seqlot, ed_typprod);";
3561 &logger( 7, $sql );
3562 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3563 }
3564  
3565 sub create_lot_sequence {
3566  
3567 # USED FOR BATCH CREATION IN Outmngr.pm
3568 my $dbh = shift;
3569  
3570 if ( _db_check_driver_name($dbh) eq "SQLite" ) {
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 _db_do_ddl( $dbh, "create table if not exists edtk_idlot_seq (id_val integer not null)" )
3576 or &logger( 3, $dbh->errstr );
3577 do {
3578 local $dbh->{PrintError} = 0;
3579 $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 return 1;
3585 }
3586  
3587 # method valid for most DBMS except MySQL
3588 my $sql = "create sequence if not exists edtk_idlot minvalue 0 maxvalue 999 cycle";
3589 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3590 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 sub create_SCHEMA {
3601 my ($dbh) = @_;
3602 schema_Create($dbh);
3603 my $cfg = eval { config_read('EDTK_DB') };
3604 create_table_TRACKING( $dbh, $cfg->{'EDTK_DBI_TRACKING'}, $cfg->{'EDTK_MAX_USER_KEY'} )
3605 if $cfg && $cfg->{'EDTK_DBI_TRACKING'};
3606 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 sub create_table_INDEX {
3612 my ( $dbh, $table ) = @_;
3613 create_table_OUTMNGR( $dbh, $table );
3614 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 sub get_columns_names {
3620 my ( $dbh, $table ) = @_;
3621 return () unless defined $dbh && defined $table;
3622  
3623 my @cols;
3624 my $sth = $dbh->column_info( undef, undef, $table, undef );
3625 if ( defined $sth ) {
3626 while ( my $row = $sth->fetchrow_hashref ) {
3627 my $name = $row->{COLUMN_NAME};
3628 push @cols, $name if defined $name;
3629 }
3630 }
3631  
3632 # Fallback for drivers without column_info: the statement's NAME list.
3633 unless (@cols) {
3634 my $sel = eval { $dbh->prepare("select * from $table where 1=0") };
3635 if ($sel) {
3636 $sel->execute();
3637 @cols = @{ $sel->{NAME} // [] };
3638 }
3639 }
3640 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 sub _pk_idjob_default {
3646 my $cfg = eval { config_read('EDTK_DB') };
3647 return 1 unless $cfg && defined $cfg->{'EDTK_DB_PK_IDJOB'};
3648 my $v = lc( $cfg->{'EDTK_DB_PK_IDJOB'} );
3649 return ( $v eq 'no' || $v eq '0' || $v eq 'false' || $v eq 'n' ) ? 0 : 1;
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 sub _schema_extra {
3660 require oEdtk::Ext;
3661 return {} unless oEdtk::Ext::require_optional('oEUser::Schema');
3662 my $extra = eval { oEUser::Schema::extra() };
3663 return {} unless ref $extra eq 'HASH' && %$extra;
3664 return _validate_schema_extra($extra);
3665 }
3666  
3667 # Validate the extension structure: identifiers and column types only.
3668 sub _validate_schema_extra {
3669 my ($extra) = @_;
3670 my %types = map { $_ => 1 } qw( VARCHAR2 VARCHAR CHAR INTEGER NUMBER DATE TIMESTAMP );
3671 my $tables = $extra->{tables} // {};
3672 my $columns = $extra->{columns} // {};
3673  
3674 for my $table ( keys %$tables ) {
3675 die "ERROR: oEUser::Schema::extra(): invalid table name '$table'\n"
3676 unless $table =~ /\A[A-Z][A-Z0-9_]*\z/;
3677  
3678 my $defs = $columns->{$table};
3679 die "ERROR: oEUser::Schema::extra(): no columns for table '$table'\n"
3680 unless ref $defs eq 'ARRAY' && @$defs;
3681  
3682 for my $col (@$defs) {
3683 my $name = $col->{name} // '';
3684 die "ERROR: oEUser::Schema::extra(): invalid column name '$name' in '$table'\n"
3685 unless $name =~ /\A[A-Z][A-Z0-9_]*\z/;
3686 my $type = uc( $col->{type} // '' );
3687 die "ERROR: oEUser::Schema::extra(): invalid type '$type' for $table.$name\n"
3688 unless $types{$type};
3689 }
3690  
3691 my $pk = $tables->{$table}{primary_key} // [];
3692 die "ERROR: oEUser::Schema::extra(): primary_key of '$table' must be a list\n"
3693 unless ref $pk eq 'ARRAY';
3694 }
3695 return $extra;
3696 }
3697  
3698 # Build the CREATE TABLE of one extension table from its definition.
3699 sub _create_table_extra {
3700 my ( $dbh, $table, $spec, $defs ) = @_;
3701  
3702 my @cols = map {
3703 my $type = uc( $_->{type} );
3704 $type .= "(" . $_->{size} . ")" if defined $_->{size} && $_->{size} ne '';
3705 my $null = $_->{nullable} ? '' : ' not null';
3706 "$_->{name} $type$null";
3707 } @$defs;
3708  
3709 my $sql = "create table if not exists $table ( " . join( ', ', @cols );
3710 my $pk = $spec->{primary_key};
3711 $sql .= ", primary key ( " . join( ', ', @$pk ) . " )" if ref $pk eq 'ARRAY' && @$pk;
3712 $sql .= " )";
3713 $sql .= _db_engine_clause($dbh);
3714 &logger( 7, $sql );
3715 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
3716 return 1;
3717 }
3718  
3719 # Apply every table of the extension; returns the number of tables applied.
3720 sub _schema_create_extra {
3721 my ($dbh) = @_;
3722 my $extra = _schema_extra();
3723 for my $table ( sort keys %{ $extra->{tables} // {} } ) {
3724 _create_table_extra( $dbh, $table, $extra->{tables}{$table}, $extra->{columns}{$table} );
3725 }
3726 return scalar keys %{ $extra->{tables} // {} };
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 sub create_table_ACQMGENTECH {
3736 my ( $dbh, $table ) = @_;
3737 $table //= 'EDTK_ACQMGENTECH';
3738  
3739 my $extra = _schema_extra();
3740 my $spec = $extra->{tables}{$table};
3741 my $defs = $extra->{columns}{$table};
3742 return 0 unless $spec && $defs;
3743  
3744 _create_table_extra( $dbh, $table, $spec, $defs );
3745 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 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 use constant SCHEMA_IDLDOC_F => 17;
3767 use constant SCHEMA_IDLDOC_M => 25;
3768 use constant SCHEMA_IDLDOC_T => 36;
3769  
3770 # The three documented shapes, as the feature set each one shows.
3771 sub _schema_level_defs {
3772 return (
3773 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 # The discriminators of one table, read off a SchemaScan result.
3790 sub _schema_features {
3791 my ( $scan, $table ) = @_;
3792 my $t = $scan->{tables}{$table};
3793 return unless $t;
3794  
3795 my @cols = @{ $t->{columns} // [] };
3796 my %col = map { lc( $_->{name} ) => $_ } @cols;
3797 my @key = map { lc $_->{name} } sort { $a->{pk} <=> $b->{pk} } grep { $_->{pk} } @cols;
3798  
3799 return {
3800 table => $table,
3801 key => \@key,
3802 idjob_in_key => ( grep { $_ eq 'ed_idjob' } @key ) ? 1 : 0,
3803 ecm => scalar( grep { exists $col{$_} } @SCHEMA_ECM_COLS ),
3804 idldoc_size => ( $col{ed_idldoc} ? $col{ed_idldoc}{size} : undef ),
3805 };
3806 }
3807  
3808 # Diff one table's live columns against a [name, ddl type] reference list.
3809 # Returns ( \@missing, \@shrink ). An absent table makes every reference column
3810 # missing. READ-ONLY: it works off the caller's SchemaScan result, writes nothing.
3811 sub _schema_col_diff {
3812 my ( $scan, $table, $cols ) = @_;
3813 my ( @missing, @shrink );
3814 my $t = $table ? $scan->{tables}{$table} : undef;
3815 my %live = $t ? map { lc( $_->{name} ) => $_ } @{ $t->{columns} // [] } : ();
3816 for my $c (@$cols) {
3817 my ( $name, $type ) = @$c;
3818 my $n = lc $name;
3819 unless ( $live{$n} ) {
3820 push @missing, $name;
3821 next;
3822 }
3823 my $want = oEdtk::SchemaScan::size_from_type($type);
3824 my $have = $live{$n}{size};
3825 push @shrink, "$name ($have < $want)"
3826 if defined $want && defined $have && $have < $want;
3827 }
3828 return ( \@missing, \@shrink );
3829 }
3830  
3831 # Features, level and the index-table column diff, all from a single scan. An
3832 # absent index table keeps empty missing/shrink, as schema_Detect always did.
3833 sub _schema_assess {
3834 my ( $scan, $index_table ) = @_;
3835 my $f = _schema_features( $scan, $index_table );
3836 my $level = _schema_classify($f);
3837 my ( $missing, $shrink ) =
3838 $f ? _schema_col_diff( $scan, $index_table, \@INDEX_COLS ) : ( [], [] );
3839 return ( $f, $level, $missing, $shrink );
3840 }
3841  
3842 # Which documented shape a feature set matches; 'mixte' when none does.
3843 sub _schema_classify {
3844 my ($f) = @_;
3845 return 'absente' unless $f;
3846 my %def = _schema_level_defs();
3847 for my $lvl ( sort keys %def ) {
3848 my $d = $def{$lvl};
3849 next unless $f->{idjob_in_key} == $d->{idjob_in_key};
3850 next unless $f->{ecm} == $d->{ecm};
3851 next unless defined $f->{idldoc_size};
3852 return $lvl
3853 if $f->{idldoc_size} >= $d->{idldoc_min} && $f->{idldoc_size} <= $d->{idldoc_max};
3854 }
3855 return 'mixte';
3856 }
3857  
3858 # Build the readable report from a schema_Detect result.
3859 sub _schema_report_lines {
3860 my (%p) = @_;
3861 my @lines;
3862 push @lines, "schema level: $p{level}";
3863 push @lines, "driver: $p{driver}";
3864 push @lines, "index table: $p{table}";
3865 if ( my $f = $p{features} ) {
3866 push @lines, " primary key: " . join( ', ', @{ $f->{key} } );
3867 push @lines, " ed_idjob in key: $f->{idjob_in_key}";
3868 push @lines, " ECM columns present: $f->{ecm}/" . scalar @SCHEMA_ECM_COLS;
3869 push @lines,
3870 " ed_idldoc width: " . ( defined $f->{idldoc_size} ? $f->{idldoc_size} : 'n/a' );
3871 }
3872 push @lines, "missing vs T: " . ( @{ $p{missing} } ? join( ', ', @{ $p{missing} } ) : 'none' );
3873 push @lines, "narrowed vs T: " . ( @{ $p{shrink} } ? join( ', ', @{ $p{shrink} } ) : 'none' );
3874 push @lines, "verdict: " . ( $p{ok} ? 'conforms to T' : 'does not conform to T' );
3875 return \@lines;
3876 }
3877  
3878 # Inspect a live base and report its schema level against the T definitions.
3879 # Options: index_table => 'name' (defaults to EDTK_DBI_OUTMNGR from the config).
3880 # READ-ONLY: every statement is a SELECT / PRAGMA; nothing is written.
3881 sub schema_Detect {
3882 my ( $dbh, %opt ) = @_;
3883 require oEdtk::SchemaScan;
3884  
3885 my $cfg = eval { config_read('EDTK_DB') } || {};
3886 my $index_table = $opt{index_table} // $cfg->{'EDTK_DBI_OUTMNGR'} // 'edtk_outmngr';
3887  
3888 my $scan = oEdtk::SchemaScan::scan_schema($dbh);
3889 my ( $f, $level, $missing, $shrink ) = _schema_assess( $scan, $index_table );
3890  
3891 my $ok = ( $level eq 'T' && !@$missing && !@$shrink ) ? 1 : 0;
3892 my $report = _schema_report_lines(
3893 level => $level,
3894 driver => $scan->{driver},
3895 table => $index_table,
3896 features => $f,
3897 missing => $missing,
3898 shrink => $shrink,
3899 ok => $ok,
3900 );
3901  
3902 return {
3903 driver => $scan->{driver},
3904 index_table => $index_table,
3905 level => $level,
3906 features => $f,
3907 missing => $missing,
3908 shrink => $shrink,
3909 ok => $ok,
3910 report => $report,
3911 };
3912 }
3913  
3914 # The report of schema_Detect as printable text.
3915 sub schema_Report {
3916 my ($res) = @_;
3917 return join( "\n", @{ $res->{report} // [] } ) . "\n";
3918 }
3919  
3920 # READ-ONLY assessment of the index table AND the tracking table against T.
3921 # Returns a probe hash; stale is set when either table does not conform.
3922 sub _schema_stale_probe {
3923 my ( $scan, $cfg, $index_table, $tracking_table ) = @_;
3924  
3925 my ( $f, $level, $i_missing, $i_shrink ) = _schema_assess( $scan, $index_table );
3926  
3927 my ( $t_missing, $t_shrink ) = ( [], [] );
3928 if ( defined $tracking_table && length $tracking_table ) {
3929 ( $t_missing, $t_shrink ) = _schema_col_diff( $scan, $tracking_table, \@TRACKER_COLS );
3930 }
3931  
3932 my $index_ok = ( $level eq 'T' && !@$i_missing && !@$i_shrink ) ? 1 : 0;
3933 my $track_ok = ( !@$t_missing && !@$t_shrink ) ? 1 : 0;
3934  
3935 return {
3936 stale => ( $index_ok && $track_ok ) ? 0 : 1,
3937 level => $level,
3938 index_table => $index_table,
3939 tracking_table => $tracking_table,
3940 index_missing => $i_missing,
3941 index_shrink => $i_shrink,
3942 track_missing => $t_missing,
3943 track_shrink => $t_shrink,
3944 cfg => $cfg,
3945 };
3946 }
3947  
3948 # Render a ( missing, narrowed ) pair as "missing=a,b narrowed=x (y<z)".
3949 sub _schema_diff_text {
3950 my ( $missing, $shrink ) = @_;
3951 return
3952 '(missing='
3953 . ( @$missing ? join( ',', @$missing ) : 'none' )
3954 . ' narrowed='
3955 . ( @$shrink ? join( ',', @$shrink ) : 'none' ) . ')';
3956 }
3957  
3958 # Quote a value for a copy-paste command line (single quotes, embedded quotes
3959 # escaped). An undefined/empty value is returned unchanged.
3960 sub _shell_quote {
3961 my ($s) = @_;
3962 return $s unless defined $s && length $s;
3963 $s =~ s/'/'\\''/g;
3964 return "'$s'";
3965 }
3966  
3967 # A host program may register a renderer here so the remediation hint names a
3968 # command it can actually run (the packaged tracker has no lib/db_migrate.pl);
3969 # coderef ($cfg) -> $hint_string. Defaults to the shipped lib/db_migrate.pl.
3970 our $SCHEMA_FIX_HINT;
3971  
3972 # The remediation hint. The password VALUE is never printed. Values are
3973 # shell-quoted so the hint is copy-pasteable. A failing host hook falls back to
3974 # the default form.
3975 sub _schema_fix_command {
3976 my ($cfg) = @_;
3977  
3978 if ( ref $SCHEMA_FIX_HINT eq 'CODE' ) {
3979 my $hint = eval { $SCHEMA_FIX_HINT->($cfg) };
3980 return $hint if defined $hint && length $hint;
3981 }
3982  
3983 my $dsn = $cfg->{EDTK_DBI_DSN} // '';
3984 $dsn =~ s/(pass(word)?=)[^;]*/$1***/gi; # mask an inline secret, if any
3985 $dsn = '<dsn>' unless length $dsn;
3986 $dsn = _shell_quote($dsn);
3987 my $user = $cfg->{EDTK_DBI_DSN_USER};
3988 my $cmd = "perl lib/db_migrate.pl --check-only --dsn $dsn ; then";
3989 $cmd .= " perl lib/db_migrate.pl --additive --dsn $dsn";
3990 $cmd .= ' --user ' . _shell_quote($user) if defined $user && length $user;
3991 $cmd .= ' --pass <pass>';
3992 return $cmd;
3993 }
3994  
3995 # The one-line operator message for a stale schema (see _schema_stale_probe).
3996 sub _schema_stale_message {
3997 my ($p) = @_;
3998 my @parts = ("database schema is STALE vs T (level=$p->{level})");
3999 push @parts, "$p->{index_table} " . _schema_diff_text( $p->{index_missing}, $p->{index_shrink} )
4000 if ( @{ $p->{index_missing} } || @{ $p->{index_shrink} } );
4001 push @parts,
4002 "$p->{tracking_table} " . _schema_diff_text( $p->{track_missing}, $p->{track_shrink} )
4003 if ( ( defined $p->{tracking_table} && length $p->{tracking_table} )
4004 && ( @{ $p->{track_missing} } || @{ $p->{track_shrink} } ) );
4005 push @parts, 'to fix: ' . _schema_fix_command( $p->{cfg} );
4006 return join( '; ', @parts );
4007 }
4008  
4009 # Report a stale schema ONCE, READ-ONLY, never fatal. Options: cfg, index_table,
4010 # tracking_table (all default to the EDTK_DB configuration). Returns the probe
4011 # when a warning was emitted, undef otherwise. It never writes to the database.
4012 sub schema_StaleWarning {
4013 my ( $dbh, %opt ) = @_;
4014 return unless $dbh;
4015  
4016 my $cfg = $opt{cfg} || ( eval { config_read('EDTK_DB') } || {} );
4017 my $index_table = $opt{index_table} // $cfg->{'EDTK_DBI_OUTMNGR'} // 'edtk_outmngr';
4018 my $tracking_table = $opt{tracking_table} // $cfg->{'EDTK_DBI_TRACKING'};
4019  
4020 # A warn()/die() below must not re-enter the oEdtk::Tracking __WARN__/__DIE__
4021 # handlers (they would call track() recursively). Neutralize them for this
4022 # call only; they are restored on return, so Halt-tracking still works.
4023 return do {
4024 local $SIG{__WARN__} = 'DEFAULT';
4025 local $SIG{__DIE__} = 'DEFAULT';
4026 eval {
4027 require oEdtk::SchemaScan;
4028 my $scan = oEdtk::SchemaScan::scan_schema($dbh);
4029 my $p = _schema_stale_probe( $scan, $cfg, $index_table, $tracking_table );
4030 return unless $p->{stale};
4031 &logger( 3, _schema_stale_message($p) );
4032 return $p;
4033 };
4034 };
4035 }
4036  
4037 # Additive detection / migration history (S51a). Kept out of schema_Create on
4038 # purpose: adding it there would change the T golden schema.
4039 sub create_table_SCHEMA_HISTORY {
4040 my ( $dbh, $table ) = @_;
4041 $table //= 'edtk_schema_history';
4042  
4043 my $sql = "create table if not exists $table ";
4044 $sql .= "( ed_hist_date varchar2(14) not null"; # detection / migration timestamp
4045 $sql .= ", ed_hist_from varchar2(8)"; # source level (F, M, T, mixte)
4046 $sql .= ", ed_hist_to varchar2(8)"; # target level
4047 $sql .= ", ed_hist_mode varchar2(16)"; # check / historize / additive
4048 $sql .= ", ed_hist_tool varchar2(32)"; # tool and version
4049 $sql .= ", ed_hist_counts varchar2(255)"; # row counts, "k=v;k=v"
4050 $sql .= " )";
4051 $sql .= _db_engine_clause($dbh);
4052 &logger( 7, $sql );
4053  
4054 _db_do_ddl( $dbh, $sql ) or &logger( 3, $dbh->errstr );
4055 return 0;
4056 }
4057  
4058 # Append one history row. Named parameters: date, from, to, mode, tool and
4059 # counts (a hash ref, stored as a compact "k=v;k=v" string).
4060 sub schema_History_add {
4061 my ( $dbh, %p ) = @_;
4062 my $table = $p{table} // 'edtk_schema_history';
4063 create_table_SCHEMA_HISTORY( $dbh, $table );
4064  
4065 my $date = $p{date} // strftime( '%Y%m%d%H%M%S', localtime );
4066 my $tool = $p{tool} // __PACKAGE__ . " $VERSION";
4067  
4068 my $counts = $p{counts};
4069 my $ctext = '';
4070 if ( ref $counts eq 'HASH' ) {
4071 $ctext = join( ';',
4072 map { "$_=" . ( defined $counts->{$_} ? $counts->{$_} : '' ) } sort keys %$counts );
4073 }
4074 elsif ( defined $counts ) {
4075 $ctext = "$counts";
4076 }
4077 $ctext = substr( $ctext, 0, 255 );
4078  
4079 local $dbh->{PrintError} = 0;
4080 my $ok = $dbh->do(
4081 "insert into $table "
4082 . "(ed_hist_date,ed_hist_from,ed_hist_to,ed_hist_mode,ed_hist_tool,ed_hist_counts) "
4083 . "values (?,?,?,?,?,?)",
4084 undef, $date, $p{from}, $p{to}, $p{mode}, $tool, $ctext
4085 );
4086 &logger( 3, $dbh->errstr ) unless $ok;
4087 return $ok ? 1 : 0;
4088 }
4089  
4090 # ============================================================
4091 # Update by historisation (S51b, PLAN annexe D, decision D17). The recommended
4092 # procedure: build a T-shaped target, copy the data by NAMED columns, validate by
4093 # counts and checksums, switch over, and KEEP the old schema as history. The
4094 # service schema is never modified in place; nothing is ever dropped.
4095 #
4096 # Portable algorithm (mirrors schema_Upgrade's timestamped rename):
4097 # 1. rename every live table to <table><HIST_SEP><stamp> (kept, not dropped);
4098 # 2. build the T target under the original names (schema_Create + extension);
4099 # 3. copy the common columns by name, then validate (count + md5 checksum);
4100 # 4. give the kept history its indexes back under non-colliding names;
4101 # 5. keep the stamped tables and append one EDTK_SCHEMA_HISTORY row.
4102 # Atomicity: on a driver with transactional DDL (SQLite, PostgreSQL) the whole
4103 # run is one transaction, so any failure rolls the service schema back. On the
4104 # others (MariaDB, MySQL, Oracle) the captured renames are inverted explicitly.
4105 # Nothing is written by schema_MigrationPlan (--check-only / --dry-run).
4106 # ============================================================
4107  
4108 use constant SCHEMA_HIST_SEP => '_hist_';
4109  
4110 # The ordered, de-duplicated list of tables the migration covers: the fixed base
4111 # tables, the configuration-driven ones, the tracking table and any extension
4112 # table. This is the same set schema_Create (plus create_table_TRACKING) builds.
4113 sub schema_Manifest {
4114 my ($cfg) = @_;
4115 $cfg //= eval { config_read('EDTK_DB') } || {};
4116  
4117 my @fixed = qw( edtk_acq edtk_admin edtk_agrege edtk_filieres edtk_id edtk_lots
4118 edtk_refiddoc edtk_supports );
4119 my @cfg = grep { defined && length }
4120 map { $cfg->{$_} }
4121 qw( EDTK_DBI_OUTMNGR EDTK_DBI_OUTMNGR_STATS EDTK_DBI_DISTRIB EDTK_DBI_DISTRIB_STATS );
4122 my @track = grep { defined && length } ( $cfg->{'EDTK_DBI_TRACKING'} );
4123 my @ext = sort keys %{ _schema_extra()->{tables} // {} };
4124  
4125 my %seen;
4126 return grep { !$seen{$_}++ } ( @fixed, @cfg, @track, @ext );
4127 }
4128  
4129 # Drivers whose DDL is transactional: a failure can roll the whole run back.
4130 sub _schema_txn_ddl {
4131 my ($dbh) = @_;
4132 my $driver = _db_check_driver_name($dbh);
4133 return ( $driver eq 'SQLite' || $driver eq 'PostgreSQL' ) ? 1 : 0;
4134 }
4135  
4136 # Rename a table, driver-neutrally (MariaDB/MySQL use RENAME TABLE).
4137 sub _schema_rename_table {
4138 my ( $dbh, $from, $to ) = @_;
4139 my $driver = _db_check_driver_name($dbh);
4140 my $sql =
4141 ( $driver eq 'mysql' )
4142 ? "rename table $from to $to"
4143 : "alter table $from rename to $to";
4144 &logger( 7, $sql );
4145 return _db_do_ddl( $dbh, $sql );
4146 }
4147  
4148 # A history name that is free: <table>_hist_<stamp>[_n] when taken.
4149 sub _schema_hist_name {
4150 my ( $dbh, $table, $stamp ) = @_;
4151 my $base = $table . SCHEMA_HIST_SEP . $stamp;
4152 my $name = $base;
4153 my $n = 1;
4154 $name = $base . '_' . $n++ while _table_exists( $dbh, $name );
4155 return $name;
4156 }
4157  
4158 # The secondary indexes of a table, as portable specs (name, unique, columns).
4159 # Best effort: an unreadable catalogue (unsupported driver) yields none.
4160 sub _schema_index_specs {
4161 my ( $dbh, $table ) = @_;
4162 require oEdtk::SchemaScan;
4163 my $scan = eval { oEdtk::SchemaScan::scan_schema($dbh) } or return [];
4164 my $t = $scan->{tables}{$table} or return [];
4165 return [
4166 map { { name => $_->{name}, unique => $_->{unique}, columns => $_->{columns} } }
4167 grep { $_->{name} !~ /^sqlite_autoindex_/ } @{ $t->{indexes} // [] }
4168 ];
4169 }
4170  
4171 # On SQLite/PostgreSQL/Oracle index names are unique per schema, so after the
4172 # rename the history table still owns the original names and the target's
4173 # "CREATE INDEX IF NOT EXISTS" would be skipped. Drop the history's indexes to
4174 # free the names. MariaDB/MySQL index names are table-scoped and never collide,
4175 # so nothing is touched there.
4176 sub _schema_release_indexes {
4177 my ( $dbh, $table, $specs ) = @_;
4178 return if _db_check_driver_name($dbh) eq 'mysql';
4179 for my $ix (@$specs) {
4180 eval { _db_do_ddl( $dbh, "drop index $ix->{name}" ) };
4181 }
4182 return;
4183 }
4184  
4185 # Recreate index specs on a table, appending $suffix to each name (empty to
4186 # restore the original names). Best effort: never throws.
4187 sub _schema_restore_indexes {
4188 my ( $dbh, $table, $specs, $suffix ) = @_;
4189 return if _db_check_driver_name($dbh) eq 'mysql';
4190 for my $ix (@$specs) {
4191 my $u = $ix->{unique} ? 'unique ' : '';
4192 my $cols = join( ', ', @{ $ix->{columns} } );
4193 next unless length $cols;
4194 eval {
4195 _db_do_ddl( $dbh,
4196 "create ${u}index if not exists $ix->{name}$suffix on $table ( $cols )" );
4197 };
4198 }
4199 return;
4200 }
4201  
4202 # The ordered column names of a table (catalogue read).
4203 sub _schema_columns {
4204 my ( $dbh, $table ) = @_;
4205 return get_columns_names( $dbh, $table );
4206 }
4207  
4208 # The primary-key columns of a table, in key order (lower-cased). Best effort:
4209 # an unreadable catalogue yields none and the caller falls back to all columns.
4210 sub _schema_key_columns {
4211 my ( $dbh, $table ) = @_;
4212 require oEdtk::SchemaScan;
4213 my $scan = eval { oEdtk::SchemaScan::scan_schema($dbh) } or return ();
4214 my $t = $scan->{tables}{$table} or return ();
4215 return map { lc $_->{name} }
4216 sort { $a->{pk} <=> $b->{pk} } grep { $_->{pk} } @{ $t->{columns} // [] };
4217 }
4218  
4219 # The columns common to a source and a target, in the target's order. Returned
4220 # as the target spelling so the INSERT list and the SELECT list agree.
4221 sub _schema_common_columns {
4222 my ( $dbh, $source, $target ) = @_;
4223 my @src = _schema_columns( $dbh, $source );
4224 my %src = map { lc($_) => $_ } @src;
4225 return grep { exists $src{ lc($_) } } _schema_columns( $dbh, $target );
4226 }
4227  
4228 # INSERT ... SELECT with NAMED column lists (never positional).
4229 sub _schema_copy_named {
4230 my ( $dbh, $source, $target, $cols ) = @_;
4231 my $list = join( ', ', @$cols );
4232 my $sql = "insert into $target ( $list ) select $list from $source";
4233 &logger( 7, $sql );
4234 local $dbh->{PrintError} = 0;
4235 $dbh->do($sql);
4236 return defined $dbh->err ? 0 : 1;
4237 }
4238  
4239 # A driver-neutral md5 over a table's rows, projected on $cols and ordered by
4240 # $order. Used to prove the copy preserved every value of the common columns.
4241 sub _schema_checksum {
4242 my ( $dbh, $table, $cols, $order ) = @_;
4243 my $list = join( ', ', @$cols );
4244 my $sql = "select $list from $table";
4245 $sql .= " order by " . join( ', ', @$order ) if @$order;
4246 my $sth = $dbh->prepare($sql);
4247 $sth->execute;
4248 my $md5 = Digest::MD5->new;
4249 while ( my @row = $sth->fetchrow_array ) {
4250 $md5->add( join( "\x1f", map { defined $_ ? $_ : "\x00" } @row ), "\n" );
4251 }
4252 return $md5->hexdigest;
4253 }
4254  
4255 # Build the T target once, in a throwaway in-memory SQLite base, to learn each
4256 # table's columns and the DDL schema_Create emits. Best effort: {} on failure.
4257 sub _schema_target_model {
4258 my ($cfg) = @_;
4259 $cfg //= eval { config_read('EDTK_DB') } || {};
4260 my %model;
4261 eval {
4262 my $m =
4263 DBI->connect( 'dbi:SQLite:dbname=:memory:', '', '',
4264 { RaiseError => 1, PrintError => 0, AutoCommit => 1 } )
4265 or return;
4266 {
4267 local $m->{PrintError} = 0;
4268 eval { create_lot_sequence($m) };
4269 eval { schema_Create($m) };
4270 eval {
4271 create_table_TRACKING(
4272 $m,
4273 $cfg->{'EDTK_DBI_TRACKING'},
4274 $cfg->{'EDTK_MAX_USER_KEY'}
4275 );
4276 }
4277 if $cfg->{'EDTK_DBI_TRACKING'};
4278 }
4279 my $rows =
4280 $m->selectall_arrayref(
4281 "select name, sql from sqlite_master where type='table' and name not like 'sqlite_%' order by name"
4282 );
4283 for my $r (@$rows) {
4284 my ( $name, $ddl ) = @$r;
4285 my @cols = map { lc } _schema_columns( $m, $name );
4286 $model{ lc $name } = { name => $name, columns => \@cols, ddl => $ddl };
4287 }
4288 $m->disconnect;
4289 };
4290 return \%model;
4291 }
4292  
4293 # Read-only plan for an update by historisation (--check-only / --dry-run). It
4294 # reports the detected level, the per-table column sets and the copy SQL. It
4295 # writes nothing: every statement it prepares is a SELECT / PRAGMA.
4296 sub schema_MigrationPlan {
4297 my ( $dbh, %opt ) = @_;
4298 my $cfg = eval { config_read('EDTK_DB') } || {};
4299 my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
4300 my $model = _schema_target_model($cfg);
4301 my $detect = schema_Detect( $dbh, %opt );
4302 my $stamp = $opt{stamp} // '<stamp>';
4303  
4304 my @tables;
4305 my @copy_sql;
4306 for my $t (@$manifest) {
4307 my $has = _table_exists( $dbh, $t );
4308 my $target = $model->{ lc $t };
4309 my @tcols = $target ? @{ $target->{columns} } : ();
4310 my ( $src, $rows ) = ( [], 0 );
4311 if ($has) {
4312 $src = [ map { lc } _schema_columns( $dbh, $t ) ];
4313 ($rows) = $dbh->selectrow_array("select count(*) from $t");
4314 }
4315 my %s = map { $_ => 1 } @$src;
4316 my %d = map { $_ => 1 } @tcols;
4317  
4318 # Common columns in the target's order (lower-cased, name-matched).
4319 my @common = grep { $s{$_} } @tcols;
4320 my @dropped = grep { !$d{$_} } @$src; # present in source, absent in T
4321 my @defaulted = grep { !$s{$_} } @tcols; # absent in source, filled by T
4322  
4323 push @tables,
4324 {
4325 name => $t,
4326 present => ( $has ? 1 : 0 ),
4327 rows => ( $rows + 0 ),
4328 common => \@common,
4329 dropped => \@dropped,
4330 defaulted => \@defaulted,
4331 };
4332 if ( $has && @common ) {
4333 my $list = join( ', ', @common );
4334 my $hist = $t . SCHEMA_HIST_SEP . $stamp;
4335 push @copy_sql, "insert into $t ( $list ) select $list from $hist";
4336 }
4337 }
4338  
4339 my @report;
4340 push @report, "schema level: $detect->{level}";
4341 push @report, "driver: $detect->{driver}";
4342 push @report, "target level: T";
4343 push @report, "history stamp: $stamp";
4344 push @report, sprintf( "tables: %d", scalar @tables );
4345 for my $t (@tables) {
4346 push @report,
4347 sprintf(
4348 " %-28s source rows=%-6d common=%-3d dropped=%-3d defaulted=%d",
4349 $t->{name}, $t->{rows},
4350 scalar @{ $t->{common} },
4351 scalar @{ $t->{dropped} },
4352 scalar @{ $t->{defaulted} }
4353 );
4354 }
4355  
4356 return {
4357 level => $detect->{level},
4358 driver => $detect->{driver},
4359 stamp => $stamp,
4360 tables => \@tables,
4361 copy_sql => \@copy_sql,
4362 model => $model,
4363 detect => $detect,
4364 report => \@report,
4365 };
4366 }
4367  
4368 # Perform the update by historisation. Options: stamp, manifest, checkpoint (a
4369 # code ref called after each table's copy; a die aborts and rolls back),
4370 # keep_old (default 1 -- the stamped tables are kept) and force (act even when
4371 # the base is already T). An already T base is a no-op (result field noop => 1).
4372 # Returns a result hash.
4373 sub schema_Historize {
4374 my ( $dbh, %opt ) = @_;
4375 my $cfg = eval { config_read('EDTK_DB') } || {};
4376 my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
4377 my $stamp = $opt{stamp} // strftime( '%Y%m%d_%H%M%S', localtime );
4378 my $detect = schema_Detect( $dbh, %opt );
4379 my $txn = _schema_txn_ddl($dbh);
4380 my $own = $dbh->{AutoCommit} ? 1 : 0;
4381  
4382 # Idempotent replay: an already T-conformant base is left untouched (no new
4383 # history snapshot). Detection keys on the index table (EDTK_DBI_OUTMNGR).
4384 if ( !$opt{force} && $detect->{level} eq 'T' && $detect->{ok} ) {
4385 return {
4386 ok => 1,
4387 noop => 1,
4388 from => 'T',
4389 to => 'T',
4390 stamp => $stamp,
4391 renamed => [],
4392 rows => {},
4393 };
4394 }
4395  
4396 my @renamed; # [ table, hist_name, index_specs ]
4397 my %rows; # table => source row count
4398  
4399 my $run = sub {
4400 $dbh->begin_work if $own && $txn;
4401  
4402 # 1. move every live table aside (kept) and free its index names.
4403 for my $t (@$manifest) {
4404 next unless _table_exists( $dbh, $t );
4405 my $specs = _schema_index_specs( $dbh, $t );
4406 my $hist = _schema_hist_name( $dbh, $t, $stamp );
4407 die "rename failed: $t -> $hist\n"
4408 unless _schema_rename_table( $dbh, $t, $hist );
4409 _schema_release_indexes( $dbh, $hist, $specs );
4410 push @renamed, [ $t, $hist, $specs ];
4411 }
4412  
4413 # 2. build the T target under the original names (extension included).
4414 schema_Create($dbh);
4415 create_table_TRACKING( $dbh, $cfg->{'EDTK_DBI_TRACKING'}, $cfg->{'EDTK_MAX_USER_KEY'} )
4416 if $cfg->{'EDTK_DBI_TRACKING'};
4417  
4418 # 3. copy the common columns by name, then validate.
4419 for my $pair (@renamed) {
4420 my ( $t, $hist ) = @$pair;
4421 my @common = _schema_common_columns( $dbh, $hist, $t );
4422 die "no common column between $hist and $t\n" unless @common;
4423 my @order = _schema_key_columns( $dbh, $t );
4424 @order = @common unless @order;
4425  
4426 die "copy failed: $hist -> $t\n"
4427 unless _schema_copy_named( $dbh, $hist, $t, \@common );
4428  
4429 my ($ns) = $dbh->selectrow_array("select count(*) from $hist");
4430 my ($nt) = $dbh->selectrow_array("select count(*) from $t");
4431 die "row count differs on $t: source=$ns target=$nt\n" if $ns != $nt;
4432 $rows{$t} = $ns + 0;
4433  
4434 my $cs = _schema_checksum( $dbh, $hist, \@common, \@order );
4435 my $ct = _schema_checksum( $dbh, $t, \@common, \@order );
4436 die "checksum differs on $t\n" if $cs ne $ct;
4437  
4438 $opt{checkpoint}->($t) if $opt{checkpoint};
4439 }
4440  
4441 # 4. give the kept history its indexes back, under names that cannot
4442 # collide with the freshly built target's.
4443 for my $pair (@renamed) {
4444 my ( $t, $hist, $specs ) = @$pair;
4445 _schema_restore_indexes( $dbh, $hist, $specs, SCHEMA_HIST_SEP . $stamp );
4446 }
4447  
4448 $dbh->commit if $own && $txn;
4449 return 1;
4450 };
4451  
4452 my $ok = eval { $run->(); 1 };
4453 unless ($ok) {
4454 my $err = $@ // 'unknown error';
4455 if ( $own && $txn ) {
4456 eval { $dbh->rollback };
4457 }
4458 else {
4459  
4460 # No transactional DDL: invert the captured renames explicitly.
4461 for my $pair ( reverse @renamed ) {
4462 my ( $t, $hist, $specs ) = @$pair;
4463 eval {
4464 _db_do_ddl( $dbh, "drop table if exists $t" );
4465 _schema_rename_table( $dbh, $hist, $t );
4466 _schema_restore_indexes( $dbh, $t, $specs, '' );
4467 };
4468 }
4469 }
4470 &logger( 3, "schema_Historize: aborted, service schema untouched: $err" );
4471 return {
4472 ok => 0,
4473 from => $detect->{level},
4474 to => 'T',
4475 stamp => $stamp,
4476 renamed => \@renamed,
4477 error => $err,
4478 };
4479 }
4480  
4481 # 5. keep the stamped tables and log one history row (outside the txn).
4482 schema_History_add(
4483 $dbh,
4484 from => $detect->{level},
4485 to => 'T',
4486 mode => ( $opt{keep_old} // 1 ) ? 'historize' : 'historize-drop',
4487 counts => \%rows,
4488 );
4489 return {
4490 ok => 1,
4491 from => $detect->{level},
4492 to => 'T',
4493 stamp => $stamp,
4494 renamed => \@renamed,
4495 rows => \%rows,
4496 };
4497 }
4498  
4499 # Invert a historisation before resuming the service (annexe D step 8): put the
4500 # stamped tables back under their original names, dropping the current target.
4501 # Options: stamp (required, the one the migration used).
4502 sub schema_Revert {
4503 my ( $dbh, %opt ) = @_;
4504 my $cfg = eval { config_read('EDTK_DB') } || {};
4505 my $stamp = $opt{stamp}
4506 or die "schema_Revert: a stamp is required\n";
4507 my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
4508 my $txn = _schema_txn_ddl($dbh);
4509 my $own = $dbh->{AutoCommit} ? 1 : 0;
4510  
4511 my @done;
4512 my $ok = eval {
4513 $dbh->begin_work if $own && $txn;
4514 for my $t (@$manifest) {
4515 my $hist = $t . SCHEMA_HIST_SEP . $stamp;
4516 next unless _table_exists( $dbh, $hist );
4517 _db_do_ddl( $dbh, "drop table if exists $t" );
4518 die "revert failed: $hist -> $t\n" unless _schema_rename_table( $dbh, $hist, $t );
4519 push @done, $t;
4520 }
4521 $dbh->commit if $own && $txn;
4522 1;
4523 };
4524 unless ($ok) {
4525 my $err = $@ // 'unknown error';
4526 eval { $dbh->rollback } if $own && $txn;
4527 &logger( 3, "schema_Revert: aborted: $err" );
4528 return { ok => 0, stamp => $stamp, error => $err };
4529 }
4530 schema_History_add(
4531 $dbh,
4532 from => 'T',
4533 to => 'T',
4534 mode => 'revert',
4535 counts => { tables => scalar @done },
4536 );
4537 return { ok => 1, stamp => $stamp, reverted => \@done };
4538 }
4539  
4540 # ============================================================
4541 # Update by in-place additive delta (S51c, PLAN annexe D "Mode additif"). For the
4542 # cases WITHOUT a key change: ADD COLUMN, column widening and CREATE ... IF NOT
4543 # EXISTS. Strictly monotone: never a DROP, never a narrowing, never a rename. A
4544 # NOT NULL column is only added to a populated table when the target definition
4545 # carries a default. With --with-constraints the primary key may change: a
4546 # duplicate pre-check runs first, then the key is swapped on the drivers that
4547 # allow it. Everything runs in one transaction where DDL is transactional
4548 # (SQLite, PostgreSQL); elsewhere it is applied statement by statement.
4549 # ============================================================
4550  
4551 # The T target's per-table column metadata, read off a throwaway in-memory SQLite
4552 # built with the very schema_Create T ships. Returns the SchemaScan tables hash
4553 # (name => { columns => [...], indexes => [...] }). Best effort: {} on failure.
4554 sub _schema_target_scan {
4555 my ($cfg) = @_;
4556 $cfg //= eval { config_read('EDTK_DB') } || {};
4557 my %tables;
4558 eval {
4559 my $m =
4560 DBI->connect( 'dbi:SQLite:dbname=:memory:', '', '',
4561 { RaiseError => 1, PrintError => 0, AutoCommit => 1 } )
4562 or return;
4563 {
4564 local $m->{PrintError} = 0;
4565 eval { create_lot_sequence($m) };
4566 eval { schema_Create($m) };
4567 eval {
4568 create_table_TRACKING(
4569 $m,
4570 $cfg->{'EDTK_DBI_TRACKING'},
4571 $cfg->{'EDTK_MAX_USER_KEY'}
4572 );
4573 }
4574 if $cfg->{'EDTK_DBI_TRACKING'};
4575 }
4576 require oEdtk::SchemaScan;
4577 my $scan = oEdtk::SchemaScan::scan_schema($m);
4578 %tables = %{ $scan->{tables} // {} };
4579 $m->disconnect;
4580 };
4581 return \%tables;
4582 }
4583  
4584 # The primary-key columns of a SchemaScan table hash, in key order (lower-cased).
4585 sub _schema_pk_of {
4586 my ($tbl) = @_;
4587 return map { lc $_->{name} }
4588 sort { $a->{pk} <=> $b->{pk} } grep { $_->{pk} } @{ $tbl->{columns} // [] };
4589 }
4590  
4591 # The ADD COLUMN statement for a target column, per driver. The type string comes
4592 # from the T target model (already portable: VARCHAR(n), integer, char(1)).
4593 sub _schema_add_column_sql {
4594 my ( $driver, $table, $col ) = @_;
4595 my $name = $col->{name};
4596 my $type = $col->{type} // 'varchar2(255)';
4597 my $nn = ( defined $col->{nullable} && !$col->{nullable} ) ? ' not null' : '';
4598 my $def = defined $col->{default} ? " default $col->{default}" : '';
4599 return "alter table $table add ( $name $type$def$nn )" if $driver eq 'Oracle';
4600 return "alter table $table add column $name $type$nn$def";
4601 }
4602  
4603 # Widen a character column to $size, per driver. Returns undef when the driver
4604 # cannot alter a column type in place (SQLite has no such statement).
4605 sub _schema_widen_sql {
4606 my ( $driver, $table, $col, $size ) = @_;
4607 return if $driver eq 'SQLite';
4608 my $name = $col->{name};
4609 my $type = "varchar2($size)";
4610 if ( $driver eq 'mysql' ) {
4611 my $nn = ( defined $col->{nullable} && !$col->{nullable} ) ? ' not null' : '';
4612 my $def = defined $col->{default} ? " default $col->{default}" : '';
4613 return "alter table $table modify $name $type$nn$def";
4614 }
4615 return "alter table $table alter column $name type $type" if $driver eq 'PostgreSQL';
4616 return "alter table $table modify $name $type"; # Oracle
4617 }
4618  
4619 # How many duplicate groups a column combination has (0 = the combination is a
4620 # valid key). Run before any new unique constraint (S51c pre-check).
4621 sub _schema_has_duplicates {
4622 my ( $dbh, $table, $cols ) = @_;
4623 my $list = join( ', ', @$cols );
4624 my ($n) = $dbh->selectrow_array(
4625 "select count(*) from ( select $list from $table group by $list having count(*) > 1 ) d");
4626 return $n + 0;
4627 }
4628  
4629 # The name of a table's current primary-key constraint, or undef. Best effort.
4630 sub _schema_pk_constraint_name {
4631 my ( $dbh, $table ) = @_;
4632 my $driver = _db_check_driver_name($dbh);
4633 if ( $driver eq 'PostgreSQL' ) {
4634 my ($n) = $dbh->selectrow_array(
4635 "select conname from pg_constraint where conrelid = ?::regclass and contype = 'p'",
4636 undef, $table );
4637 return $n;
4638 }
4639 elsif ( $driver eq 'Oracle' ) {
4640 my ($n) = $dbh->selectrow_array(
4641 "select constraint_name from user_constraints where table_name = upper(?) and constraint_type = 'P'",
4642 undef, $table
4643 );
4644 return $n;
4645 }
4646 return;
4647 }
4648  
4649 # Swap a table's primary key for a duplicate-free column set, per driver. On
4650 # SQLite a key cannot be changed without rebuilding the table, which is out of
4651 # scope for an additive delta. Returns an (ok, error) pair.
4652 sub _schema_change_key {
4653 my ( $dbh, $table, $cols ) = @_;
4654 my $driver = _db_check_driver_name($dbh);
4655 my $list = join( ', ', @$cols );
4656 return ( 0, "changing the key in place is not supported on $driver" )
4657 if $driver eq 'SQLite' || $driver eq 'NC';
4658  
4659 if ( $driver eq 'mysql' ) {
4660 return ( 0, "alter table $table drop primary key" )
4661 unless eval { _db_do_ddl( $dbh, "alter table $table drop primary key" ) };
4662 return ( 0, "alter table $table add primary key ( $list )" )
4663 unless eval { _db_do_ddl( $dbh, "alter table $table add primary key ( $list )" ) };
4664 return ( 1, undef );
4665 }
4666  
4667 # PostgreSQL / Oracle: drop the existing key, attach the new one.
4668 my $pkname = _schema_pk_constraint_name( $dbh, $table );
4669 _db_do_ddl( $dbh, "alter table $table drop constraint $pkname" ) if defined $pkname;
4670 my $ix = "pk_" . $table;
4671 _db_do_ddl( $dbh, "create unique index if not exists $ix on $table ( $list )" );
4672 return ( 0, "alter table $table add constraint $ix primary key" )
4673 unless
4674 eval { _db_do_ddl( $dbh, "alter table $table add constraint $ix primary key ( $list )" ) };
4675 return ( 1, undef );
4676 }
4677  
4678 # READ-ONLY preview of the in-place additive update: exactly what schema_Additive
4679 # would add, widen, create or change, without writing anything (every statement is
4680 # a SELECT / PRAGMA). Options: manifest, with_constraints (0|1). Returns a plan
4681 # hash: ok, level, driver, detect, create (list), add (table => [cols]), widen
4682 # (table => [ {col,from,to} ]), key (list), add_sql (list), widen_sql (list),
4683 # violations (list) and report (list of lines).
4684 sub schema_AdditivePlan {
4685 my ( $dbh, %opt ) = @_;
4686 my $cfg = eval { config_read('EDTK_DB') } || {};
4687 my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
4688 my $detect = schema_Detect( $dbh, %opt );
4689 my $driver = _db_check_driver_name($dbh);
4690  
4691 my $target = _schema_target_scan($cfg);
4692  
4693 require oEdtk::SchemaScan;
4694 my $scan = oEdtk::SchemaScan::scan_schema($dbh);
4695  
4696 my @create;
4697 my %add;
4698 my %widen;
4699 my @key;
4700 my @violations;
4701 my @add_sql;
4702 my @widen_sql;
4703  
4704 for my $t (@$manifest) {
4705 my $tbl = $target->{$t} or next;
4706  
4707 # A table absent from the base is created, not altered.
4708 my $live = $scan->{tables}{$t};
4709 if ( !$live ) {
4710 push @create, $t;
4711 next;
4712 }
4713  
4714 my %sc = map { lc( $_->{name} ) => $_ } @{ $live->{columns} // [] };
4715 my ($nrows) = $dbh->selectrow_array("select count(*) from $t");
4716 $nrows += 0;
4717  
4718 for my $col ( @{ $tbl->{columns} // [] } ) {
4719 my $key = lc $col->{name};
4720 if ( !exists $sc{$key} ) {
4721 my $notnull = ( defined $col->{nullable} && !$col->{nullable} ) ? 1 : 0;
4722 if ( $notnull && !defined $col->{default} && $nrows > 0 ) {
4723 push @violations,
4724 "$t.$col->{name}: NOT NULL without a default on a populated table";
4725 next;
4726 }
4727 push @{ $add{$t} }, $col->{name};
4728 push @add_sql, _schema_add_column_sql( $driver, $t, $col );
4729 next;
4730 }
4731 my $s = $sc{$key};
4732 next unless defined $col->{size} && defined $s->{size};
4733 if ( $col->{size} > $s->{size} ) {
4734 push @{ $widen{$t} },
4735 { col => $col->{name}, from => $s->{size}, to => $col->{size} };
4736 my $sql = _schema_widen_sql( $driver, $t, $col, $col->{size} );
4737 if ( defined $sql ) {
4738 push @widen_sql, $sql;
4739 }
4740 else {
4741 push @violations,
4742 "$t.$col->{name}: widening $s->{size}->$col->{size} not supported on $driver";
4743 }
4744 }
4745 elsif ( $col->{size} < $s->{size} ) {
4746 push @violations, "narrowing refused: $t.$col->{name} $s->{size}->$col->{size}";
4747 }
4748 }
4749  
4750 my @spk = _schema_pk_of($live);
4751 my @tpk = _schema_pk_of($tbl);
4752 if ( @tpk && join( ',', @spk ) ne join( ',', @tpk ) ) {
4753 push @key, { table => $t, from => join( ',', @spk ), to => join( ',', @tpk ) };
4754 push @violations,
4755 "$t: key differs ( "
4756 . join( ',', @spk ) . " -> "
4757 . join( ',', @tpk )
4758 . " ); use --with-constraints"
4759 unless $opt{with_constraints};
4760 }
4761 }
4762  
4763 my @report;
4764 push @report, "schema level: $detect->{level}";
4765 push @report, "driver: $driver";
4766 push @report, "target level: T";
4767 push @report, "mode: additive (in place, read-only preview)";
4768 push @report, sprintf( "tables to create: %d", scalar @create );
4769 push @report, sprintf( "columns to add: %d", scalar( map { @$_ } values %add ) );
4770 push @report, sprintf( "columns to widen: %d", scalar( map { @$_ } values %widen ) );
4771 push @report, sprintf( "key changes: %d", scalar @key );
4772 push @report, sprintf( "violations: %d", scalar @violations );
4773 push @report, sprintf( " create %s", $_ ) for @create;
4774  
4775 for my $t ( sort keys %add ) {
4776 push @report, sprintf( " add %-28s %s", $t, join( ',', @{ $add{$t} } ) );
4777 }
4778 for my $t ( sort keys %widen ) {
4779 push @report,
4780 sprintf(
4781 " widen %-28s %s",
4782 $t,
4783 join( ',',
4784 map { sprintf( '%s %s->%s', $_->{col}, $_->{from}, $_->{to} ) } @{ $widen{$t} } )
4785 );
4786 }
4787 push @report, sprintf( " key %s ( %s -> %s )", $_->{table}, $_->{from}, $_->{to} ) for @key;
4788 push @report, " violation: $_" for @violations;
4789  
4790 return {
4791 ok => 1,
4792 level => $detect->{level},
4793 driver => $driver,
4794 detect => $detect,
4795 create => \@create,
4796 add => \%add,
4797 widen => \%widen,
4798 key => \@key,
4799 add_sql => \@add_sql,
4800 widen_sql => \@widen_sql,
4801 violations => \@violations,
4802 report => \@report,
4803 };
4804 }
4805  
4806 # Perform the in-place additive update. Options: manifest, with_constraints (0|1),
4807 # checkpoint (a code ref called after each table) and force. A base that already
4808 # conforms to T with nothing to add or widen is a no-op (result field noop => 1).
4809 # Returns a result hash: created (list), added (table => [cols]), widened
4810 # (table => [ {col,from,to} ]), key_changed (list), violations (list) and error.
4811 sub schema_Additive {
4812 my ( $dbh, %opt ) = @_;
4813 my $cfg = eval { config_read('EDTK_DB') } || {};
4814 my $manifest = $opt{manifest} // [ schema_Manifest($cfg) ];
4815 my $detect = schema_Detect( $dbh, %opt );
4816 my $driver = _db_check_driver_name($dbh);
4817 my $txn = _schema_txn_ddl($dbh);
4818 my $own = $dbh->{AutoCommit} ? 1 : 0;
4819  
4820 my $target = _schema_target_scan($cfg);
4821  
4822 my @created;
4823 my %added;
4824 my %widened;
4825 my @key_changed;
4826 my @violations;
4827  
4828 my $run = sub {
4829 $dbh->begin_work if $own && $txn;
4830  
4831 require oEdtk::SchemaScan;
4832 my $scan = oEdtk::SchemaScan::scan_schema($dbh);
4833  
4834 # 1. add the missing columns, widen the narrower ones and, when asked,
4835 # change the key -- on the tables that already exist.
4836 for my $t (@$manifest) {
4837 my $tbl = $target->{$t} or next;
4838 my $live = $scan->{tables}{$t} or next;
4839 my %sc = map { lc( $_->{name} ) => $_ } @{ $live->{columns} // [] };
4840 my ($nrows) = $dbh->selectrow_array("select count(*) from $t");
4841 $nrows += 0;
4842  
4843 for my $col ( @{ $tbl->{columns} // [] } ) {
4844 my $key = lc $col->{name};
4845 if ( !exists $sc{$key} ) {
4846 my $notnull = ( defined $col->{nullable} && !$col->{nullable} ) ? 1 : 0;
4847 if ( $notnull && !defined $col->{default} && $nrows > 0 ) {
4848 push @violations,
4849 "$t.$col->{name}: NOT NULL without a default on a populated table";
4850 next;
4851 }
4852 my $sql = _schema_add_column_sql( $driver, $t, $col );
4853 die "add column failed on $t.$col->{name}\n" unless _db_do_ddl( $dbh, $sql );
4854 push @{ $added{$t} }, $col->{name};
4855 next;
4856 }
4857 my $s = $sc{$key};
4858 next unless defined $col->{size} && defined $s->{size};
4859 if ( $col->{size} > $s->{size} ) {
4860 my $sql = _schema_widen_sql( $driver, $t, $col, $col->{size} );
4861 next unless defined $sql;
4862 die "widen failed on $t.$col->{name}\n" unless _db_do_ddl( $dbh, $sql );
4863 push @{ $widened{$t} },
4864 { col => $col->{name}, from => $s->{size}, to => $col->{size} };
4865 }
4866 elsif ( $col->{size} < $s->{size} ) {
4867 push @violations, "narrowing refused: $t.$col->{name} $s->{size}->$col->{size}";
4868 }
4869 }
4870  
4871 # Change the key only when explicitly asked to.
4872 my @spk = _schema_pk_of($live);
4873 my @tpk = _schema_pk_of($tbl);
4874 if ( @tpk && join( ',', @spk ) ne join( ',', @tpk ) ) {
4875 if ( !$opt{with_constraints} ) {
4876 push @violations,
4877 "$t: key differs ( "
4878 . join( ',', @spk ) . " -> "
4879 . join( ',', @tpk )
4880 . " ); use --with-constraints";
4881 }
4882 else {
4883 my $dup = _schema_has_duplicates( $dbh, $t, \@tpk );
4884 die "duplicate rows on $t ( " . join( ',', @tpk ) . " ): $dup\n" if $dup;
4885 my ( $kok, $kerr ) = _schema_change_key( $dbh, $t, \@tpk );
4886 die "key change failed on $t: $kerr\n" unless $kok;
4887 push @key_changed, $t;
4888 }
4889 }
4890  
4891 $opt{checkpoint}->($t) if $opt{checkpoint};
4892 }
4893  
4894 # 2. create the still-missing tables last, once the existing ones carry
4895 # every column their indexes reference (schema_Create is "IF NOT EXISTS").
4896 for my $t (@$manifest) {
4897 push @created, $t unless $scan->{tables}{$t};
4898 }
4899 if (@created) {
4900 schema_Create($dbh);
4901 create_table_TRACKING( $dbh, $cfg->{'EDTK_DBI_TRACKING'}, $cfg->{'EDTK_MAX_USER_KEY'} )
4902 if $cfg->{'EDTK_DBI_TRACKING'};
4903 }
4904  
4905 $dbh->commit if $own && $txn;
4906 return 1;
4907 };
4908  
4909 my $ok = eval { $run->(); 1 };
4910 unless ($ok) {
4911 my $err = $@ // 'unknown error';
4912 eval { $dbh->rollback } if $own && $txn;
4913 &logger( 3, "schema_Additive: aborted: $err" );
4914 return {
4915 ok => 0,
4916 from => $detect->{level},
4917 to => 'T',
4918 created => \@created,
4919 added => \%added,
4920 widened => \%widened,
4921 key_changed => \@key_changed,
4922 violations => \@violations,
4923 error => $err,
4924 };
4925 }
4926  
4927 # 3. nothing changed at all -> no-op, and no history row.
4928 unless ( @created || %added || %widened || @key_changed ) {
4929 return {
4930 ok => 1,
4931 noop => 1,
4932 from => $detect->{level},
4933 to => 'T',
4934 created => [],
4935 added => {},
4936 widened => {},
4937 key_changed => [],
4938 violations => \@violations,
4939 };
4940 }
4941  
4942 schema_History_add(
4943 $dbh,
4944 from => $detect->{level},
4945 to => 'T',
4946 mode => 'additive',
4947 counts => {
4948 created => scalar @created,
4949 added => scalar( map { @$_ } values %added ),
4950 },
4951 );
4952 return {
4953 ok => 1,
4954 from => $detect->{level},
4955 to => 'T',
4956 created => \@created,
4957 added => \%added,
4958 widened => \%widened,
4959 key_changed => \@key_changed,
4960 violations => \@violations,
4961 };
4962 }
4963  
4964 # ============================================================
4965 # PUBLIC : probe whether the connected DB user may run the DDL that schema_Create
4966 # and schema_Upgrade issue, so a missing right is reported early instead of failing
4967 # later on a CREATE TABLE / INDEX / SEQUENCE or an ALTER TABLE. Best effort: it only
4968 # reads the data dictionary and never dies.
4969 #
4970 # Returns { driver => 'SQLite'|'Oracle'|'PostgreSQL'|'mysql'|'NC',
4971 # checked => 0|1, # 0 when the driver has no privilege model
4972 # create => 0|1, # undef when left unknown
4973 # drop => 0|1,
4974 # index => 0|1,
4975 # alter => 0|1,
4976 # sequence=> 0|1,
4977 # missing => [ 'CREATE', ... ],
4978 # error => '...' } # set when the probe itself failed
4979 # Options: table => 'name' targets a specific table for the ownership checks
4980 # (PostgreSQL); ignored by the other backends.
4981 # ============================================================
4982 sub db_check_privileges {
4983 my ( $dbh, %opt ) = @_;
4984  
4985 # Rights probed, in the order they are reported in 'missing'.
4986 my @RIGHTS = qw(CREATE DROP INDEX ALTER SEQUENCE);
4987  
4988 my %res = ( driver => 'NC', checked => 0, missing => [] );
4989 return \%res unless defined $dbh;
4990  
4991 my $driver = _db_check_driver_name($dbh);
4992 $res{driver} = $driver;
4993  
4994 # SQLite has no GRANT/privilege model: the file owner may do everything.
4995 if ( $driver eq 'SQLite' ) {
4996 $res{ lc $_ } = 1 for @RIGHTS;
4997 $res{checked} = 1;
4998 &logger( 7,
4999 "db_check_privileges: SQLite has no privilege model, "
5000 . "assuming every right is allowed" );
5001 return \%res;
5002 }
5003  
5004 # No privilege model we can query: report nothing rather than guess.
5005 if ( $driver eq 'NC' ) {
5006 &logger( 7, "db_check_privileges: unknown driver, " . "cannot check privileges" );
5007 return \%res;
5008 }
5009  
5010 my %rights;
5011 my $ok = eval {
5012 %rights =
5013 $driver eq 'PostgreSQL' ? _db_priv_pg( $dbh, %opt )
5014 : $driver eq 'mysql' ? _db_priv_mysql( $dbh, %opt )
5015 : $driver eq 'Oracle' ? _db_priv_oracle( $dbh, %opt )
5016 : ();
5017 1;
5018 };
5019 unless ($ok) {
5020 $res{error} = $@ || 'unknown error';
5021 &logger( 3, "db_check_privileges: privilege probe failed: $res{error}" );
5022 return \%res;
5023 }
5024  
5025 $res{checked} = 1;
5026 for my $right (@RIGHTS) {
5027 my $have = $rights{ lc $right };
5028 $res{ lc $right } = $have;
5029 next if !defined $have || $have;
5030 push @{ $res{missing} }, $right;
5031 &logger( 3,
5032 "db_check_privileges: DB user lacks the $right privilege on the "
5033 . "current database/schema ; schema_Create and schema_Upgrade may fail" );
5034 }
5035 return \%res;
5036 }
5037  
5038 # PostgreSQL: CREATE is a database/schema privilege; owning the table grants DROP,
5039 # INDEX and ALTER. Ownership is tested on the target table (option 'table') or on
5040 # any table of the current schema, and a superuser always passes; an empty schema
5041 # does not raise a false alarm. Returns a hash of rights.
5042 sub _db_priv_pg {
5043 my ( $dbh, %opt ) = @_;
5044  
5045 my ($super) =
5046 $dbh->selectrow_array("SELECT rolsuper FROM pg_roles WHERE rolname = current_user");
5047 return map { $_ => 1 } qw(create drop index alter sequence) if $super;
5048  
5049 my ($create) = $dbh->selectrow_array(
5050 "SELECT has_database_privilege(current_user, current_database(), 'CREATE') "
5051 . "AND has_schema_privilege(current_user, current_schema(), 'CREATE')" );
5052  
5053 my $owns;
5054 if ( defined $opt{table} && length $opt{table} ) {
5055 ($owns) = $dbh->selectrow_array(
5056 "SELECT pg_get_userbyid(c.relowner) = current_user "
5057 . "FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
5058 . "WHERE c.relname = ? AND n.nspname = current_schema()",
5059 undef, $opt{table}
5060 );
5061 }
5062 else {
5063 ($owns) =
5064 $dbh->selectrow_array( "SELECT bool_or(pg_get_userbyid(c.relowner) = current_user) "
5065 . "FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
5066 . "WHERE n.nspname = current_schema() AND c.relkind = 'r'" );
5067 }
5068 my $owning = defined $owns ? ( $owns ? 1 : 0 ) : 1;
5069  
5070 return (
5071 create => $create ? 1 : 0,
5072 drop => $owning,
5073 index => $owning, # CREATE INDEX needs table ownership
5074 alter => $owning, # ALTER TABLE needs table ownership
5075 sequence => $create ? 1 : 0, # CREATE SEQUENCE needs CREATE on the schema
5076 );
5077 }
5078  
5079 # MySQL / MariaDB: SHOW GRANTS lists the effective grants. A statement that grants
5080 # ALL PRIVILEGES, or the specific right, on '*.*' or on the current database gives
5081 # the right. CREATE INDEX needs INDEX or ALTER; CREATE SEQUENCE (MariaDB) needs
5082 # CREATE. Returns a hash of rights.
5083 sub _db_priv_mysql {
5084 my ( $dbh, %opt ) = @_;
5085  
5086 my ($db) = $dbh->selectrow_array("SELECT DATABASE()");
5087 $db = '' unless defined $db;
5088  
5089 my $rows = $dbh->selectall_arrayref("SHOW GRANTS FOR CURRENT_USER()");
5090 my %have;
5091 for my $r ( @{ $rows || [] } ) {
5092 my $grant = $r->[0] // '';
5093 next unless $grant =~ /^\s*GRANT\s+(.+?)\s+ON\s+(\S.*?)\s+TO\s/i;
5094 my ( $privs, $scope ) = ( uc $1, $2 );
5095 $scope =~ s/`//g;
5096 my $global = ( $scope eq '*.*' );
5097 my $local = ( $db ne '' && lc($scope) eq lc("$db.*") );
5098 next unless $global || $local;
5099 if ( $privs =~ /ALL PRIVILEGES/ ) {
5100 $have{$_} = 1 for qw(CREATE DROP INDEX ALTER);
5101 }
5102 else {
5103 $have{$_} = 1 for grep { $privs =~ /\b$_\b/ } qw(CREATE DROP INDEX ALTER);
5104 }
5105 }
5106 return (
5107 create => $have{CREATE} ? 1 : 0,
5108 drop => $have{DROP} ? 1 : 0,
5109 index => ( $have{INDEX} || $have{ALTER} ) ? 1 : 0,
5110 alter => $have{ALTER} ? 1 : 0,
5111 sequence => $have{CREATE} ? 1 : 0,
5112 );
5113 }
5114  
5115 # Oracle: system privileges; those held directly sit in USER_SYS_PRIVS, those held
5116 # through an enabled role in ROLE_SYS_PRIVS. Creating the tables (CREATE TABLE) makes
5117 # us their owner, so we may then INDEX and ALTER them. Returns a hash of rights.
5118 sub _db_priv_oracle {
5119 my ( $dbh, %opt ) = @_;
5120  
5121 my $ref = $dbh->selectcol_arrayref(
5122 "SELECT PRIVILEGE FROM USER_SYS_PRIVS " . "UNION SELECT PRIVILEGE FROM ROLE_SYS_PRIVS" );
5123 my %priv = map { uc($_) => 1 } @{ $ref || [] };
5124  
5125 my $create_table = ( $priv{'CREATE TABLE'} || $priv{'CREATE ANY TABLE'} ) ? 1 : 0;
5126 return (
5127 create => $create_table,
5128 drop => ( $create_table || $priv{'DROP ANY TABLE'} ) ? 1 : 0,
5129 index => ( $create_table || $priv{'CREATE ANY INDEX'} ) ? 1 : 0,
5130 alter => ( $create_table || $priv{'ALTER ANY TABLE'} ) ? 1 : 0,
5131 sequence => ( $priv{'CREATE SEQUENCE'} || $priv{'CREATE ANY SEQUENCE'} ) ? 1 : 0,
5132 );
5133 }
5134  
5135 sub schema_Upgrade {
5136  
5137 # EXAMPLE CALL:
5138 # schema_Upgrade (CFG => $cfg);
5139 my %p = @_;
5140  
5141 # D50 (H2): schema_Upgrade is now an envelope of schema_Historize, which
5142 # frees the index names before schema_Create (so the ix_* indexes are really
5143 # rebuilt on the new table instead of being silently skipped while the
5144 # renamed table still holds their names), copies the rows by NAMED columns
5145 # (never positionally) and inverts the renames if a step fails. The call form
5146 # schema_Upgrade(CFG => $cfg) is unchanged.
5147 #
5148 # PREREQUISITES FOR THIS OPERATION:
5149 #- DISK SPACE (the previous schema is kept as history, see below)
5150 #- HISTORIZATION
5151 my $dbh = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
5152  
5153 # Repatriate any pending backup rows before renaming / copying the schema.
5154 eval { _db_maybe_reconcile( $dbh, $p{CFG} ); };
5155  
5156 # Best effort: alert (never block) when the DB user cannot CREATE/DROP.
5157 eval { db_check_privileges($dbh) };
5158  
5159 # force => the upgrade always rebuilds (as before), even on an already
5160 # conformant base; the current schema is set aside as <table>_hist_<stamp>.
5161 &logger( 3,
5162 "schema_Upgrade: the previous schema is kept as history "
5163 . "(<table>_hist_<stamp>) and consumes disk space" );
5164  
5165 my $result = schema_Historize(
5166 $dbh,
5167 manifest => [ schema_Manifest( $p{CFG} ) ],
5168 keep_old => 1,
5169 force => 1,
5170 );
5171  
5172 die "schema_Upgrade: " . ( $result->{error} // 'unknown error' ) . "\n"
5173 unless $result->{ok};
5174 db_invalidate_meta_cache();
5175 return $result;
5176 }
5177  
5178 sub schema_Create {
5179  
5180 # my ($dbh, $table, $maxkeys) = @_;
5181 my $dbh = shift;
5182 my $cfg = config_read('EDTK_DB');
5183  
5184 # Best effort: alert (never block) when the DB user cannot CREATE/DROP.
5185 eval { db_check_privileges($dbh) };
5186  
5187 #if ( $cfg->{'EDTK_DBI_DSN'} =~ m/SQLite/i) {
5188 if ( $dbh->{'Driver'}->{'Name'} =~ m/mysql/i ) {
5189  
5190 # MySQL uses its own AUTO_INCREMENT emulation, nothing to create here.
5191 &logger( 5, "MySQL uses its own sequence emulation, ignoring." );
5192 }
5193 else {
5194 # Oracle/PostgreSQL create a SEQUENCE; SQLite creates a counter table.
5195 create_lot_sequence($dbh);
5196 }
5197  
5198 create_table_ADMIN($dbh);
5199 create_table_ACQUIT($dbh);
5200 create_table_AGREGE($dbh);
5201 create_table_FILIERES($dbh);
5202 create_table_ID($dbh);
5203 create_table_LOTS($dbh);
5204 create_table_REFIDDOC($dbh);
5205 create_table_SUPPORTS($dbh);
5206  
5207 #create_table_DATAGROUPS($dbh);
5208 #create_table_PARA($dbh);
5209  
5210 # CHECK THE PRIMARY KEY AND INDEX PROPOSALS (BE CAREFUL NOT TO DO ANYTHING DAFT)
5211 create_table_OUTMNGR( $dbh, $cfg->{'EDTK_DBI_OUTMNGR'} );
5212 create_table_OUTMNGR( $dbh, $cfg->{'EDTK_DBI_OUTMNGR_STATS'} );
5213 create_table_DISTRIB( $dbh, $cfg->{'EDTK_DBI_DISTRIB'} );
5214 create_table_DISTRIB( $dbh, $cfg->{'EDTK_DBI_DISTRIB_STATS'} );
5215  
5216 # Optional extension schema (oEUser::Schema, D19): absent -> nothing extra.
5217 _schema_create_extra($dbh);
5218  
5219 db_invalidate_meta_cache();
5220 }
5221  
5222 sub _db_with_lock {
5223 my (%p) = @_; # CFG, CODE-REF
5224 my $dbh = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
5225 my $date = strftime( "%Y-%m-%d", localtime );
5226 my $pid = $$;
5227  
5228 # Try to insert the lock
5229 eval {
5230 local $dbh->{PrintError} = 0;
5231 $dbh->do(
5232 'insert into edtk_admin (ed_action_date,ed_action_pid,ed_action_status,ed_oedtk_release) values (?,?,?,?)',
5233 undef, $date, $pid, 'START', $VERSION
5234 );
5235 };
5236 if ($@) { # conflict, another process already holds it
5237 $dbh->disconnect;
5238 return 0;
5239 }
5240  
5241 # Check that it is really us
5242 my ($got_pid) =
5243 $dbh->selectrow_array( 'select ed_action_pid from edtk_admin where ed_action_date = ?',
5244 undef, $date );
5245 unless ( $got_pid == $pid ) {
5246 $dbh->disconnect;
5247 return 0;
5248 }
5249  
5250 # Run the body
5251 eval { $p{code}->($dbh) };
5252 my $err = $@;
5253  
5254 # Mark the end
5255 my $duration = _elapsed_seconds($^T);
5256 $dbh->do(
5257 'update edtk_admin set ed_action_status = ?, ed_action_duration = ? where ed_action_date = ?',
5258 undef, 'DONE', $duration, $date
5259 );
5260 $dbh->disconnect;
5261  
5262 die $err if $err;
5263 return 1;
5264 }
5265  
5266 sub _db_check_driver_name {
5267 my ($dbh) = shift;
5268  
5269 # Guard against an invalid or disconnected $dbh
5270 return "NC" unless defined $dbh;
5271 my $driver_name = eval { $dbh->{'Driver'}->{'Name'} };
5272 return "NC" unless defined $driver_name;
5273  
5274 if ( $driver_name =~ m/SQLite/i ) { return "SQLite"; }
5275 elsif ( $driver_name =~ m/Oracle/i ) { return "Oracle"; }
5276 elsif ( $driver_name =~ m/Pg/i ) { return "PostgreSQL"; }
5277 elsif ( $driver_name =~ m/(?:mysql|maria)/i ) { return "mysql"; }
5278 else { return "NC"; }
5279 }
5280  
5281 # Returns the MySQL storage-engine clause appended to CREATE TABLE statements.
5282 # The engine is configurable through EDTK_DB_STORAGE_ENGINE (default: MyISAM,
5283 # kept for its bulk-load performance). Empty string for non-MySQL drivers.
5284 sub _db_engine_clause {
5285 my ($dbh) = @_;
5286 return '' unless _db_check_driver_name($dbh) eq 'mysql';
5287 unless ( defined $_DB_ENGINE_CACHE ) {
5288 my $cfg = eval { config_read('EDTK_DB') } || {};
5289 $_DB_ENGINE_CACHE = $cfg->{'EDTK_DB_STORAGE_ENGINE'} || 'MyISAM';
5290 }
5291 return ' engine=' . $_DB_ENGINE_CACHE . ' ';
5292 }
5293  
5294 # Does an object (table, index or sequence) already exist in the current schema?
5295 # Queries each driver's data dictionary; returns 1/0 (0 for an unknown driver,
5296 # so that the CREATE attempt is still allowed to run).
5297 sub _db_object_exists {
5298 my ( $dbh, $kind, $name ) = @_;
5299 my $driver = _db_check_driver_name($dbh);
5300 my ( $schema, $obj ) = ( $name =~ /^(\w+)\.(\w+)$/ ) ? ( $1, $2 ) : ( undef, $name );
5301  
5302 if ( $driver eq 'SQLite' ) {
5303 my ($n) = $dbh->selectrow_array( 'select 1 from sqlite_master where type = ? and name = ?',
5304 undef, $kind, $obj );
5305 return $n ? 1 : 0;
5306 }
5307 elsif ( $driver eq 'PostgreSQL' ) {
5308  
5309 # PostgreSQL folds unquoted identifiers to lower case (EDTK_ACQMGENTECH is
5310 # stored as edtk_acqmgentech), so compare case-insensitively, as the Oracle
5311 # branch does with upper().
5312 my ($n) = $dbh->selectrow_array(
5313 'select 1 from pg_class c join pg_namespace n on n.oid = c.relnamespace '
5314 . 'where lower(c.relname) = lower(?) and n.nspname = current_schema()',
5315 undef, $obj
5316 );
5317 return $n ? 1 : 0;
5318 }
5319 elsif ( $driver eq 'mysql' ) {
5320 if ( $kind eq 'index' ) {
5321 my ($n) = $dbh->selectrow_array(
5322 'select 1 from information_schema.statistics '
5323 . 'where table_schema = database() and index_name = ?',
5324 undef, $obj
5325 );
5326 return $n ? 1 : 0;
5327 }
5328 my ($n) = $dbh->selectrow_array( 'show tables like ?', undef, $obj );
5329 return $n ? 1 : 0;
5330 }
5331 elsif ( $driver eq 'Oracle' ) {
5332 my ($n) = $dbh->selectrow_array( 'select 1 from user_objects where object_name = upper(?)',
5333 undef, $obj );
5334 return $n ? 1 : 0;
5335 }
5336 return 0;
5337 }
5338  
5339 # Extracts the kind ('table'|'index'|'sequence') and name from a CREATE statement.
5340 sub _db_parse_create {
5341 my ($sql) = @_;
5342 return ( 'index', $1 )
5343 if $sql =~ /\bcreate\s+(?:unique\s+)?index\s+(?:if\s+not\s+exists\s+)?(\S+)/i;
5344 return ( 'table', $1 ) if $sql =~ /\bcreate\s+table\s+(?:if\s+not\s+exists\s+)?(\S+)/i;
5345 return ( 'sequence', $1 ) if $sql =~ /\bcreate\s+sequence\s+(?:if\s+not\s+exists\s+)?(\S+)/i;
5346 return;
5347 }
5348  
5349 # Runs a DDL statement through the driver-specific fixup. On drivers that lack
5350 # "CREATE ... IF NOT EXISTS" (Oracle, MySQL) the clause is emulated by checking
5351 # existence first and stripping it. PostgreSQL supports the clause natively, but
5352 # the server then emits a "relation ... already exists, skipping" NOTICE straight
5353 # to STDERR; pre-checking it too turns that notice into a regular Information log
5354 # line and skips the redundant DDL. Returns the underlying do() result.
5355 sub _db_do_ddl {
5356 my ( $dbh, $sql ) = @_;
5357 my $driver = _db_check_driver_name($dbh);
5358 $sql = _sql_fixup( $dbh, $sql, 'casse' );
5359  
5360 if ( ( $driver eq 'Oracle' || $driver eq 'mysql' || $driver eq 'PostgreSQL' )
5361 && $sql =~ /\bcreate\b.*\bif\s+not\s+exists\b/is )
5362 {
5363 my ( $kind, $name ) = _db_parse_create($sql);
5364 if ( defined $name && _db_object_exists( $dbh, $kind, $name ) ) {
5365 &logger( 6, "INFO: relation \"$name\" already exists, skipping\n" );
5366 return 1;
5367 }
5368 $sql =~ s/\s+if\s+not\s+exists\b//ig
5369 if $driver eq 'Oracle' || $driver eq 'mysql';
5370 }
5371 return do { local $dbh->{PrintError} = 0; $dbh->do($sql) };
5372 }
5373  
5374 # Per-engine table-maintenance command templates, as (repair, optimize) hash refs
5375 # keyed by _db_check_driver_name() class. A template without %s is a portable no-op
5376 # ("select 1"), so an engine that has no such command still runs harmlessly. Kept in
5377 # one place so every engine's coverage is declared and unit-testable.
5378 sub _db_maintenance_commands {
5379 my ($driver) = @_;
5380 my %repair = (
5381 NC => "select 1",
5382 mysql => "repair table %s",
5383 Oracle => "select 1 from dual",
5384 PostgreSQL => "select 1",
5385 SQLite => "select 1",
5386 );
5387 my %optm = (
5388 NC => "select 1",
5389 mysql => "optimize table %s",
5390 Oracle => "select 1 from dual",
5391  
5392 # VACUUM FULL takes an exclusive lock and rewrites the whole table: it does
5393 # not belong in the routine maintenance path. Plain VACUUM ANALYZE reclaims
5394 # space without blocking writers and refreshes the planner statistics.
5395 PostgreSQL => "vacuum analyze %s",
5396  
5397 # SQLite has no per-table VACUUM; ANALYZE %s refreshes the statistics it uses.
5398 SQLite => "analyze %s",
5399 );
5400 return ( \%repair, \%optm );
5401 }
5402  
5403 sub admin_optimize_db {
5404  
5405 # EXAMPLE CALL:
5406 # admin_optimize_db (CFG => $cfg);
5407  
5408 my %p = @_;
5409  
5410 # Single connection for the whole operation (it used to open two per table).
5411 $p{DBH} = db_connect( $p{CFG}, 'EDTK_DBI_DSN' );
5412  
5413 # Repatriate any pending backup rows before optimizing / repairing.
5414 eval { _db_maybe_reconcile( $p{DBH}, $p{CFG} ); };
5415 &logger( 3, "admin_optimize_db: reconciliation failed: $@" ) if $@;
5416  
5417 my @tListeTables = grep { defined $_ && $_ ne '' } (
5418 "edtk_acq",
5419 "edtk_admin",
5420 "edtk_agrege",
5421 "edtk_filieres",
5422 "edtk_id",
5423 "edtk_lots",
5424 "edtk_refiddoc",
5425 "edtk_supports",
5426  
5427 # "edtk_datagroups",
5428 # "edtk_para",
5429 $p{CFG}->{EDTK_DBI_DISTRIB},
5430 $p{CFG}->{EDTK_DBI_DISTRIB_STATS},
5431 $p{CFG}->{EDTK_DBI_OUTMNGR},
5432 $p{CFG}->{EDTK_DBI_OUTMNGR_STATS},
5433 "edtk_tracking"
5434 );
5435  
5436 # Detect the driver once, on the live handle.
5437 my $dbName = _db_check_driver_name( $p{DBH} );
5438 &logger( 7, "admin_optimize_db: driver=$dbName, " . scalar(@tListeTables) . " tables" );
5439  
5440 # PostgreSQL maintenance can spawn parallel workers that allocate dynamic shared
5441 # memory in /dev/shm; on a small /dev/shm the segment resize aborts with
5442 # "could not resize shared memory segment ... No space left on device". Routine
5443 # per-table maintenance gains nothing from parallelism, so force it serial.
5444 if ( $dbName eq 'PostgreSQL' ) {
5445 eval { local $p{DBH}->{PrintError} = 0; $p{DBH}->do($_) }
5446 for (
5447 'set max_parallel_maintenance_workers = 0',
5448 'set max_parallel_workers_per_gather = 0'
5449 );
5450 }
5451  
5452 my ( $hCdeRepair, $hCdeOptm ) = _db_maintenance_commands($dbName);
5453  
5454 foreach my $table (@tListeTables) {
5455  
5456 # Repair
5457 my $tpl_repair = $hCdeRepair->{$dbName} // "select 1";
5458  
5459 # sprintf only when the template contains %s
5460 my $sql_repair = ( $tpl_repair =~ /\%s/ ) ? sprintf( $tpl_repair, $table ) : $tpl_repair;
5461 &logger( 7, "repair: $sql_repair" );
5462 _db_maintenance_run( $p{DBH}, _sql_fixup( $p{DBH}, $sql_repair, 'casse' ),
5463 "repair $table" );
5464  
5465 # Optimize
5466 my $tpl_optm = $hCdeOptm->{$dbName} // "select 1";
5467 my $sql_optm = ( $tpl_optm =~ /\%s/ ) ? sprintf( $tpl_optm, $table ) : $tpl_optm;
5468 &logger( 7, "optimize: $sql_optm" );
5469 _db_maintenance_run( $p{DBH}, _sql_fixup( $p{DBH}, $sql_optm, 'casse' ),
5470 "optimize $table" );
5471 }
5472 $p{DBH}->disconnect;
5473 return 1;
5474 }
5475  
5476 # Run one maintenance statement. Catches driver errors so a single table cannot
5477 # abort the whole pass, and reports them as one concise logger line instead of the
5478 # raw DBI/PrintError dump (e.g. a PostgreSQL shared-memory exhaustion). Never dies.
5479 sub _db_maintenance_run {
5480 my ( $dbh, $sql, $what ) = @_;
5481 my $res = do {
5482 local $dbh->{PrintError} = 0;
5483 local $dbh->{RaiseError} = 0;
5484 eval { $dbh->do($sql) };
5485 };
5486 return 1 if defined $res;
5487 &logger( 3, "can't $what: " . ( $dbh->errstr // $@ // 'unknown error' ) );
5488 return 0;
5489 }
5490  
5491 sub _sql_fixup {
5492 my ( $dbh, $sql, $mysqlCasse ) = @_;
5493 my $driver = $dbh->{'Driver'}->{'Name'};
5494  
5495 # Driver class, so that MariaDB (Driver.Name 'MariaDB') is handled like MySQL.
5496 my $class = _db_check_driver_name($dbh);
5497  
5498 # POSTGRESQL specifics
5499 if ( $class eq 'PostgreSQL' ) {
5500  
5501 # --- Empty strings '' for non-string types ---
5502 if ( $sql =~ /VALUES\s*\((.*)\)/si ) {
5503 my $values_part = $1;
5504  
5505 # Replace standalone '' with NULL
5506 $values_part =~ s/''(?=\s*,|\s*\))/NULL/g;
5507 $sql =~ s/VALUES\s*\(.*\)/VALUES ($values_part)/si;
5508 }
5509  
5510 # Handle the update form "SET column = ''"
5511 $sql =~ s/=\s*''(\s*,|\s+WHERE|=)/ = NULL$1/gi;
5512 }
5513  
5514 # Generic logic / other drivers: Oracle keeps VARCHAR2, everyone else gets VARCHAR.
5515 if ( $class ne 'Oracle' ) {
5516 $sql =~ s/VARCHAR2 *(\(\d+\))/VARCHAR$1/gi;
5517 }
5518  
5519 # MySQL forced case (keyed on the real MySQL driver only; MariaDB is left untouched).
5520 if ( $driver eq 'mysql' and $mysqlCasse and $sql !~ /\b(INSERT|REPLACE)\b/i ) {
5521 $sql = uc($sql);
5522 }
5523  
5524 return $sql;
5525 }
5526  
5527 sub db_backup_agent {
5528  
5529 # Archives the 3 production tables (EDTK_DBI_TRACKING / OUTMNGR / ACQUIT) into a
5530 # date-stamped snapshot, then purges the rows older than EDTK_ENTIRE_YEARS_KEPT.
5531 # The snapshot copies the whole table (not just the old rows), so a re-run on the
5532 # same day must not overwrite it with the now-smaller source: the existing archive
5533 # is kept as is. Called from Outmngr::omgr_purge_fs.
5534 my ( $dbh, $cfg ) = @_;
5535 $cfg ||= config_read('EDTK_DB');
5536 unless ( defined( $cfg->{'EDTK_ENTIRE_YEARS_KEPT'} ) && $cfg->{'EDTK_ENTIRE_YEARS_KEPT'} > 0 ) {
5537 &logger( 6,
5538 "EDTK_ENTIRE_YEARS_KEPT not defined for optimization purge. db_backup_agent not needed."
5539 );
5540 return 1;
5541 }
5542  
5543 my $suffixe = strftime( "%Y%m%d", localtime ) . "_BAK";
5544 my $cur_year = strftime( "%Y", localtime );
5545 my $kept_year = $cur_year - $cfg->{'EDTK_ENTIRE_YEARS_KEPT'};
5546  
5547 # (table, date column, purge threshold) of the tables to archive and purge.
5548 my @plan = (
5549 [ $cfg->{'EDTK_DBI_TRACKING'}, 'ed_tstamp', $kept_year . "0101000000" ],
5550 [ $cfg->{'EDTK_DBI_OUTMNGR'}, 'ed_dtedtion', $kept_year . "0101" ],
5551 [ $cfg->{'EDTK_DBI_ACQUIT'}, 'ed_dtpost', $kept_year . "0101" ],
5552 );
5553  
5554 foreach my $spec (@plan) {
5555 my ( $table, $datecol, $check ) = @$spec;
5556 next unless defined $table && $table ne '';
5557  
5558 my $sql_check = "select count($datecol) from $table where $datecol < ? ";
5559 my $sth = $dbh->prepare($sql_check);
5560 do { local $sth->{PrintError} = 0; $sth->execute($check) }
5561 or &logger( 3, "SQL execute failed " . $sth->err . "-" . $sth->errstr );
5562 my ($result) = $sth->fetchrow_array;
5563 unless ($result) {
5564 &logger( 5, "db_backup_agent has nothing to do with $table" );
5565 next;
5566 }
5567  
5568 my $cible = $table . "_" . $suffixe;
5569  
5570 # MySQL stores the archive under its uppercase name (copy_table DDL is uppercased).
5571 my $exists = _db_object_exists( $dbh, 'table', $cible )
5572 || _db_object_exists( $dbh, 'table', uc $cible );
5573 if ($exists) {
5574 &logger( 6, "db_backup_agent: archive $cible already exists for today, keeping it" );
5575  
5576 # H13: a row older than the threshold may have arrived since the archive was
5577 # made. Archive the rows we are about to purge, so none is deleted without
5578 # first being saved (the same-day re-run used to purge them unarchived).
5579 my $arch = ( _db_check_driver_name($dbh) eq 'mysql' ) ? uc $cible : $cible;
5580 my $sql_a = "insert into $arch select * from $table where $datecol < ?";
5581 _db_do_log(
5582 $dbh, _sql_fixup( $dbh, $sql_a, 'casse' ),
5583 "ERROR: can't archive into $cible",
5584 bind => [$check],
5585 fatal => 1
5586 );
5587 }
5588 else {
5589 copy_table( $dbh, $table, $cible, '-create' );
5590 &logger( 5, "db_backup_agent archived $table into $cible" );
5591 }
5592  
5593 my $sql_clean = "delete from $table where $datecol < ? ";
5594 _db_do_log(
5595 $dbh, $sql_clean, "ERROR: can't delete from $table",
5596 bind => [$check],
5597 fatal => 1
5598 );
5599  
5600 &logger( 6, "db_backup_agent DONE with $table for data older than $check." );
5601 }
5602  
5603 return 1;
5604 }
5605  
5606 1;
5607  
5608 =head1 NAME
5609  
5610 oEdtk::DBAdmin - oEdtk database administration, schema upkeep and bulk CSV loading
5611  
5612 =head1 SYNOPSIS
5613  
5614 use oEdtk::DBAdmin qw(db_connect schema_Create csv_import);
5615  
5616 my $dbh = db_connect( $cfg, 'EDTK_DBI_DSN' );
5617 schema_Create($dbh); # build the whole schema
5618 csv_import( $dbh, $table, $file, ref_col => 'id' );
5619  
5620 =head1 DESCRIPTION
5621  
5622 oEdtk::DBAdmin creates, detects, upgrades and maintains the oEdtk database and
5623 loads CSV data into it, across PostgreSQL, MySQL / MariaDB, Oracle and SQLite.
5624 The hardening work of the DBAdmin chantier (see F<docs/dbadmin/>) added the
5625 tuning keys and the schema-detection / staleness helpers documented below. The
5626 public entry points are grouped by area; the private helpers are not listed.
5627  
5628 =head1 CONNECTION
5629  
5630 =head2 db_connect( $cfg, $key )
5631  
5632 Connect to the database named by the configuration key I<$key> (for example
5633 C<EDTK_DBI_DSN>), applying the per-driver normalisation the module expects.
5634  
5635 =head2 db_check_privileges( $dbh, %opt )
5636  
5637 Read-only probe of the privileges the account holds (CREATE, DROP, INDEX, ALTER,
5638 SEQUENCE); never blocking. Returns a hash with the granted set, the missing one
5639 and an optional error. Option C<table> targets the ownership checks (PostgreSQL).
5640  
5641 =head2 db_invalidate_meta_cache
5642  
5643 Drop the column-metadata cache used by C<csv_import>. Call it after a schema
5644 change (C<schema_Create> / C<schema_Upgrade>) so the next import re-reads the
5645 columns instead of reusing a stale description.
5646  
5647 =head1 SCHEMA
5648  
5649 =head2 schema_Create( $dbh )
5650  
5651 Create the whole T schema: the base tables, the configuration-driven tables and
5652 the tracking table.
5653  
5654 =head2 schema_Upgrade( $dbh, %opt )
5655  
5656 Bring an existing base up to the current schema (delegates to the historisation
5657 path, see C<schema_Historize>).
5658  
5659 =head2 schema_Detect( $dbh, %opt )
5660  
5661 Inspect a live base and report its detected level against the T definitions.
5662 Option C<index_table> names the index table (defaults to C<EDTK_DBI_OUTMNGR>).
5663 READ-ONLY: every statement is a SELECT / PRAGMA; nothing is written.
5664  
5665 =head2 schema_Report( $dbh, %opt )
5666  
5667 The C<schema_Detect> result as printable text.
5668  
5669 =head2 schema_Manifest( ... )
5670  
5671 The ordered, de-duplicated list of tables the migration covers: the fixed base
5672 tables, the configuration-driven ones, the tracking table and any extension
5673 table.
5674  
5675 =head2 schema_MigrationPlan( $dbh, %opt )
5676  
5677 Read-only plan of an update by historisation (C<--check-only> / C<--dry-run>):
5678 the detected level, the per-table column sets and the copy SQL. Writes nothing.
5679  
5680 =head2 schema_Historize( $dbh, %opt )
5681  
5682 Perform the update by historisation. Options: C<stamp>, C<manifest>,
5683 C<checkpoint> (a code ref called after each table's copy; a die aborts and rolls
5684 back), C<keep_old> (default 1, the stamped tables are kept) and C<force>. An
5685 already-T base is a no-op (result field C<noop>). Returns a result hash.
5686  
5687 =head2 schema_Revert( $dbh, %opt )
5688  
5689 Invert a historisation before resuming the service: put the stamped tables back
5690 under their original names, dropping the current target. Option C<stamp>
5691 (required) is the one the migration used.
5692  
5693 =head2 schema_AdditivePlan( $dbh, %opt )
5694  
5695 Read-only preview of the in-place additive update: what C<schema_Additive> would
5696 add, widen, create or change. Option C<with_constraints> (0|1). Writes nothing
5697 (every statement is a SELECT / PRAGMA). Returns a plan hash: C<ok>, C<level>,
5698 C<driver>, C<detect>, C<create>, C<add>, C<widen>, C<key>, C<add_sql>, C<widen_sql>,
5699 C<violations> and C<report>.
5700  
5701 =head2 schema_Additive( $dbh, %opt )
5702  
5703 Perform the in-place additive update. Options: C<manifest>, C<with_constraints>
5704 (0|1), C<checkpoint> and C<force>. A base that already conforms to T with
5705 nothing to add or widen is a no-op (result field C<noop>). Returns a result hash:
5706 C<created>, C<added>, C<widened>, C<key_changed>, C<violations> and C<error>.
5707  
5708 =head2 schema_StaleWarning( $dbh, %opt )
5709  
5710 Report a stale schema ONCE, READ-ONLY, never fatal. Options: C<cfg>,
5711 C<index_table>, C<tracking_table> (all default to the EDTK_DB configuration).
5712 Returns the probe when a warning was emitted, undef otherwise. It never writes.
5713  
5714 =head2 schema_History_add( $dbh, %named )
5715  
5716 Append one history row: C<date>, C<from>, C<to>, C<mode>, C<tool> and C<counts>
5717 (a hash ref, stored as a compact "k=v;k=v" string).
5718  
5719 =head2 historicize_table( $dbh, %opt )
5720  
5721 Historise one table (used by the migration).
5722  
5723 =head2 create_SCHEMA( $dbh, $table, $maxkeys )
5724  
5725 Legacy entry point kept for the fork: it creates the whole schema (the canonical
5726 C<schema_Create>) plus the TRACKING table the fork also created.
5727  
5728 =head2 create_lot_sequence( $dbh )
5729  
5730 Create the lot-sequence counter table (needed by SQLite, which has no SEQUENCE).
5731  
5732 =head2 create_table_TRACKING / OUTMNGR / DISTRIB / ACQUIT / ACQMGENTECH / ... ( $dbh, ... )
5733  
5734 Create one table of the schema: TRACKING, OUTMNGR, DISTRIB, ACQUIT, ACQMGENTECH,
5735 SCHEMA_HISTORY, ADMIN, AGREGE, DATAGROUPS, FILIERES, ID, INDEX, LOTS, PARA,
5736 REFIDDOC, SUPPORTS. C<create_table_INDEX> is a fork alias of
5737 C<create_table_OUTMNGR>; C<create_table_ACQMGENTECH> targets the optional oEUser
5738 extension and is a silent no-op when it is not installed.
5739  
5740 =head1 LOADING DATA
5741  
5742 =head2 csv_import( $dbh, $table, $file, %opt )
5743  
5744 Import a CSV file into a table (the historic row-by-row API, unchanged). The
5745 keys and parameters that tune the PostgreSQL bulk path are below.
5746  
5747 =head2 insert_tData( $dbh, %opt )
5748  
5749 Insert one row (used by the C<csv_import> row-by-row path).
5750  
5751 =head1 BULK LOAD TUNING (PostgreSQL)
5752  
5753 =head2 EDTK_DB_BURST_MO
5754  
5755 Above this size, in MiB, a PostgreSQL insert switches to the ELT staging path:
5756 the file is copied raw into an unconstrained TEMP table and moved with a single
5757 INSERT ... SELECT, skipping the per-row Perl parse. 0 disables the path; the
5758 shipped default is 50 MiB. The caller parameter C<burst_mo> overrides it,
5759 C<pg_copy_staging> (0 or 1) forces either path regardless of size, and
5760 C<force_copy> (true) forces the parsed COPY path ahead of every other setting
5761 (the packaged tracker exposes it as C<--forceCopy>).
5762  
5763 =head2 EDTK_DB_COPY_ENCODING
5764  
5765 Source encoding declared to the PostgreSQL COPY. When unset, the historical
5766 LATIN1 is used; an unknown value is rejected with a message instead of being
5767 passed silently. The caller parameter C<pg_copy_encoding> takes precedence.
5768  
5769 =head2 EDTK_DB_DEFER_INDEX_RATIO, EDTK_DB_DEFER_INDEX_MIN_ROWS
5770  
5771 A PostgreSQL bulk insert drops the secondary indexes up-front and rebuilds them
5772 afterwards only when the incoming row count is at least
5773 C<EDTK_DB_DEFER_INDEX_RATIO> times the table's estimated row count (default
5774 0.1) and at least C<EDTK_DB_DEFER_INDEX_MIN_ROWS> rows (default 10000). The
5775 caller parameters C<pg_defer_index_ratio> and C<pg_defer_index_min_rows> take
5776 precedence.
5777  
5778 =head1 MAINTENANCE
5779  
5780 =head2 acheck_db_admin( %opt )
5781  
5782 The daily "first process of the day" maintenance, driven by the edtk_admin day
5783 row.
5784  
5785 =head2 acheck_db_admin_on_connect( $dbh, $cfg )
5786  
5787 Claim the day lock on connect and run the maintenance once per day.
5788  
5789 =head2 admin_optimize_db( $dbh, %opt )
5790  
5791 Dispatch a per-engine REPAIR / OPTIMIZE (VACUUM ANALYZE on PostgreSQL) over the
5792 maintenance tables, on a single connection.
5793  
5794 =head2 agrege_idJob( %opt )
5795  
5796 Aggregate one job's distribution rows.
5797  
5798 =head2 copy_table / move_table / db_drop_table ( $dbh, $table, $target, %opt )
5799  
5800 Copy a table, move it (copy then drop) or drop it.
5801  
5802 =head2 get_columns_names( $dbh, $table )
5803  
5804 Read the driver-neutral column catalogue; the names keep the catalogue's case.
5805  
5806 =head1 BACKUP BUFFER
5807  
5808 =head2 db_backup_available( $dbh ) / db_on_backup( $dbh )
5809  
5810 Whether a distinct backup database is configured, and whether this handle points
5811 at the backup buffer.
5812  
5813 =head2 db_backup_pending( $dbh )
5814  
5815 Count the pending rows per buffer table (read-only).
5816  
5817 =head2 db_backup_prepare( $dbh )
5818  
5819 Guarantee the backup buffer can hold the event tables.
5820  
5821 =head2 db_backup_agent( %opt )
5822  
5823 Archive the event tables into the buffer, then purge them (the daily backup job).
5824 It is not deprecated: it archives three tables and then purges.
5825  
5826 =head2 db_reconcile_backup( %opt )
5827  
5828 Copy every pending row of the backup buffer back into the main database. Never
5829 dies; returns a report hashref. Options: C<CFG>, C<tables>, C<dry_run>,
5830 C<keep_backup>.
5831  
5832 =head1 EXPORTED VARIABLES
5833  
5834 =head2 @INDEX_COLS / @TRACKER_COLS
5835  
5836 The ordered C<[ name, ddl-type ]> lists of the index table's and the tracking
5837 table's columns.
5838  
5839 =head1 SEE ALSO
5840  
5841 F<docs/dbadmin/>, F<dbadmin_optim.md>,
5842 F<PLAN-DBAdmin-optimisation-durcissement.md>.
5843  
5844 =head1 AUTHOR
5845  
5846 The oEdtk team.
5847  
5848 =cut