blib/lib/DML.pm untested

filter: Statementstmt 0.0% 0 / 579 Branchbran 0.0% 0 / 240 Conditioncond 0.0% 0 / 102 MC/DCmcdc 0.0% 0 / 60 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 1004 CC 121 SCAR 65.8
CC
121
Cov
0%
check_records
1482.0
update_records
930.0
insert_into
306.0
CRAP 723.5
1 package Oracle::DML;
2  
3 # Perl standard modules
4 use strict;
5 use warnings;
6 use Carp;
7 require Exporter;
8 our @ISA = qw(Exporter);
9 # use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
10 # warningsToBrowser(1);
11 # use CGI;
12 # use Getopt::Std;
13 use DBI;
14 use Debug::EchoMessage;
15 use Oracle::DML::Common qw(:db_conn :table check_input_drf);
16 use Oracle::Schema qw(get_table_definition);
17 # use Oracle::SQL::Builder qw(build_sql_stmt split_cns);
18  
19 require 5.003;
20 $Oracle::DML::VERSION = 0.10;
21  
22 our @EXPORT = qw();
23 our @EXPORT_OK = qw(
24 select_records insert_records delete_records update_records
25 check_records insert_into
26 check_input_arf
27 );
28 our @IMPORT_OK = qw(
29 get_dbh is_object_exist get_table_definition
30 debug echoMSG disp_param
31 );
32 our %EXPORT_TAGS = (
33 all => [@EXPORT_OK],
34 all_ok=>[@EXPORT_OK,@IMPORT_OK],
35 );
36  
37 =head1 NAME
38  
39 Oracle::DML - Perl class for Oracle batch DML
40  
41 =head1 SYNOPSIS
42  
43 use Oracle::DML;
44  
45 my %cfg = ('conn_string'=>'usr/pwd@db', 'table_name'=>'my_ora_tab');
46 my $ot = Oracle::DML->new;
47 # or combine the two together
48 my $ot = Oracle::DML->new(%cfg);
49 my $sql= $ot->prepare(%cfg);
50 $ot->execute(); # actually create the audit table and trigger
51  
52  
53 =head1 DESCRIPTION
54  
55 This class contains methods to create audit tables and triggers for
56 Oracle tables.
57  
58 =cut
59  
60 =head2 Object Constructor
61  
62 =head3 new (%arg)
63  
64 Input variables:
65  
66 $cs - Oracle connection string in usr/pwd@db
67 $tn - Oracle table name without schema
68  
69 Variables used or routines called:
70  
71 None
72  
73 How to use:
74  
75 my $obj = new Oracle::DML; # or
76 my $obj = Oracle::DML->new; # or
77 my $cs = 'usr/pwd@db';
78 my $tn = 'my_table';
79 my $obj = Oracle::DML->new(cs=>$cs,tn=>$tn); # or
80 my $obj = Oracle::DML->new('cs',$cs, 'tn',$tn);
81  
82 Return: new empty or initialized Oracle::DML object.
83  
84 =cut
85  
86 sub new {
87 my $caller = shift;
88 my $caller_is_obj = ref($caller);
89 my $class = $caller_is_obj || $caller;
90 my $self = bless {}, $class;
91 my %arg = @_; # convert rest of inputs into hash array
92 foreach my $k ( keys %arg ) {
93 if ($caller_is_obj) {
94 $self->{$k} = $caller->{$k};
95 } else {
96 $self->{$k} = $arg{$k};
97 }
98 }
99 return $self;
100 }
101  
102 =head1 METHODS
103  
104 The following are the common methods, routines, and functions
105 defined in this class.
106  
107 =head2 Exported Tag: All
108  
109 The I<:all> tag includes all the methods or sub-rountines
110 defined in this class.
111  
112 use Oracle::DML qw(:all);
113  
114 =cut
115  
116 =head3 insert_into ($dbh,$tab,$crf,$pr)
117  
118 Input variables:
119  
120 $dbh - database handler
121 $tab - table name
122 $crf - table definition array: $crf->[$i]{$itm}
123 $i - column number
124 $k - items: col, typ, req, wid, dft, etc.
125 PK, CK, MP_TABLE, MP are in the last element of the array
126 $pr - additional parameters
127  
128 Variables used or routines called:
129  
130 None
131  
132 How to use:
133  
134 my $obj = new Oracle::DML; # or
135 my $obj = Oracle::DML->new; # or
136 my $cs = 'usr/pwd@db';
137 my $tn = 'my_table';
138 my $def = 'tables.def';
139 my $crf = $self->read_tab_def($def);
140 my $sql = $obj->insert_into($dbh,$tn,$def->{$tn});
141  
142 Return: SQL statement
143  
144 =cut
145  
146 sub insert_into {
147 my $s = (ref($_[0])) ? shift : Oracle::DML->new;
148 my ($dbh,$tab,$crf,$pr) = @_;
149 print "WARN: no table name is defined.\n" if !$tab;
150 print "WARN: no table def array.\n" if !$crf || $crf !~ /ARRAY/;
151 return "" if !$tab || !$crf || $crf !~ /ARRAY/;
152  
153 $pr = {} if !$pr || $pr !~ /HASH/;
154 my $n = $#$crf;
155 my $stn = (exists $crf->[$n]{MP_TABLE}[0])?$crf->[$n]{MP_TABLE}[0]:"";
156 print "WARN: no mapping table for $tab.\n" if !$stn;
157 return "" if !$stn;
158 my @mp = (exists $crf->[$n]{MP}) ? @{$crf->[$n]{MP}} : ();
159 my %mp = ();
160 if (@mp) {
161 foreach (@mp) {
162 my ($k, $v) = ($_ =~ /\s*(\w+)\s*=\s*(.+)/);
163 $mp{lc $k} = $v;
164 }
165 }
166 my $t = "INSERT INTO $tab\n SELECT ";
167 for my $i (0..$#$crf) {
168 my $k = lc $crf->[$i]{col};
169 my $v = (exists $mp{$k}) ? $mp{$k} : $k;
170 if ($i == 0) {
171 $t .= ($n==0) ? "$v\n" : "$v,\n";
172 } elsif ($i==$n && $n > 0) {
173 $t .= " $v\n";
174 } else { $t .= " $v,\n"; }
175 }
176 my $whr = (exists $pr->{where}) ? $pr->{where} : "";
177 $t .= " FROM $stn\n";
178 $t .= " WHERE $whr\n" if $whr;
179 return $t;
180 }
181  
182 =head3 select_records($dbh,$tn,$cns,$whr,$rtp)
183  
184 Input variables:
185  
186 $dbh - a database handler.
187 $tn - table name.
188 $cns - column names separated by comma.
189 $whr - conditions used in WHERE clause
190 $rtp - returned array type:
191 ARRAY - default, array does not contain column names.
192 SFR_ARRAY - first row contains column names, i.e.,
193 skip first row when processing data
194 HASH - hashed array
195 lc_hash - column name in lower case
196 $dtp - database type: Oracle|CSV|ODBC
197  
198 Variables used or routines called:
199  
200 echoMSG - display messages
201  
202 How to use:
203  
204 my $arf = $self->select_records($dbh,'emp',
205 'firstname,lastname', 'sal > 10000','lc_hash');
206  
207 Return: an array reference contain the records in sequence while
208 columns can be in sequence or in hash.
209  
210 The returned array can be accessed through ${$arf}[$i][$j] or
211 ${$arf}[$i]{$col}. When it is ${$arf}[$i][$j], no column name is
212 returned from it. When $atp = 'SFR_ARRAY', then the first row contains
213 column names.
214  
215 =cut
216  
217 sub select_records {
218 my $self = shift;
219 my($dbh,$tn,$cns,$whr,$rtp,$dtp) = @_;
220 croak "No database handler is specified.\n" if ! $dbh;
221 croak "No table name is specified.\n" if ! $tn;
222 if (!$dtp) {
223 if ($dbh =~ /ODBC/) { $dtp = 'ODBC'; # Win32::ODBC=HASH()
224 } else {
225 $dtp = 'Oracle';
226 }
227 }
228 $cns = "*" if ! $cns;
229 $self->echoMSG(" getting data from table $tn...",1);
230 my $sel = $cns;
231 my ($dft,$cdf);
232 if ($dft && !$cdf) {
233 $self->echoMSG("WARN: no column definition array ref.");
234 $self->echoMSG("WARN: date format - $dft will not be applied.");
235 my ($cn1,$cd1,$cd2) =
236 $self->get_table_definition($dbh,$tn,'','hash');
237 $cdf = $cd1;
238 }
239 my (%ha, $i, $k, $msg);
240 if ($dft && $cdf && "$cdf" =~ /ARRAY/) {
241 $self->echoMSG(" setting date format to $dft...",2);
242 my $scn = "";
243 for $i (0..$#{$cdf}) {
244 $k = lc(${$cdf}[$i][0]); # cname
245 $scn .= "$k,";
246 $ha{$k} = uc(${$cdf}[$i][1]); # coltype
247 }
248 $scn =~ s/,$//; # remove last comma
249 $sel = "";
250 $cns = $scn if $cns eq '*';
251 # foreach $i (split /,/, $scn) {
252 # $k = lc($i);
253 # if ($sel) { $sel .= ","; } else { $sel = ""; }
254 # if ($ha{$k} eq 'DATE') {
255 # $sel .= "to_char($k,'$dft') AS $k";
256 # } else {
257 # $sel .= "$k";
258 # }
259 # }
260 foreach $i (split /,/, $cns) {
261 $k = lc($i);
262 if ($sel) { $sel .= ","; } else { $sel = ""; }
263 if (!exists $ha{$k} && $k =~ /^(rowid|rownum)/i) {
264 $sel .= "$k"; next;
265 }
266 if (!exists $ha{$k}) {
267 $msg = "Excluded: $k not in table def arf.";
268 $self->echoMSG(" $msg",2);
269 next;
270 }
271 if ($ha{$k} eq 'DATE') {
272 $sel .= "to_char($k,'$dft') AS $k";
273 } else {
274 $sel .= "$k";
275 }
276 }
277 }
278 my $q = "SELECT $sel \n FROM $tn";
279 my $m1 = $self->split_cns("SELECT $sel",65,',',4);
280 $msg = "$m1 FROM $tn";
281 if ($whr) {
282 my $m2 = $self->split_cns(" $whr",65,',',4);
283 $q .= "\n $whr"; $msg .= "\n$m2";
284 } else { $msg .= "<p>"; }
285 $self->echoMSG("$msg",2);
286 my ($s,$arf,$hrf);
287 $s=$dbh->prepare($q) || print "ERR: Stmt - $dbh->errstr";
288 $s->execute() || print "ERR: Stmt - $s->errstr";
289 $i = -1;
290 if ($rtp && $rtp =~ /^(hash|lc_hash)/i) {
291 while ($hrf = $s->fetchrow_hashref) {
292 ++$i;
293 if ($rtp =~ /^lc_hash/i) {
294 my $ar = bless {}, ref($self)||$self;
295 foreach my $k (keys %{$hrf}) {
296 ${$ar}{lc $k} = ${$hrf}{$k};
297 }
298 ${$arf}[$i] = $ar;
299 } else {
300 ${$arf}[$i] = $hrf;
301 }
302 }
303 } else {
304 $arf = $s->fetchall_arrayref;
305 if ($rtp && $rtp =~ /^(sfr_array)/i) {
306 my ($cn1,$cd1,$cmt) =
307 $self->get_table_definition($dbh,$tn);
308 # insert the column names in the very begining of the array
309 splice(@$arf, 0,0,[split /,/, $cn1]);
310 }
311 }
312 return $arf;
313 }
314  
315 =head3 delete_records($dbh,$tab,$col,$op,$val,$dft)
316  
317 Input variables:
318  
319 $dbh - database handler
320 $tab - table name
321 $col - column name
322 $op - operator such as '=','<','in','like','btw', etc.
323 $val - value or values separated by space
324 $dft - date format, default to 'YYYYMMDD.HH24MISS'
325  
326 Variables used or routines called:
327  
328 echoMSG - echo message
329  
330 How to use:
331  
332 my $cs = "usr/pwd@db";
333 my $dbh = $self->getDBHandler($cs, 'Oracle');
334 $self->insert($dbh, 'myTab', 'ID', 'in', 'A B C');
335  
336 Return: None.
337  
338 If operator is 'like', then you can use wildcard such as '%' or '?'
339 in the $val. You can only use one string, and the others after the
340 first blank space will be ignored.
341  
342 =cut
343  
344 sub delete_records {
345 my $self = shift;
346 my ($dbh,$tab,$col,$op,$val,$dft) = @_;
347 $dft = 'YYYYMMDD.HH24MISS' if !$dft;
348 my ($msg, $q, $v, $r);
349 my $mtd = 'Fax::DataFax::OraSub::delete_records';
350 if (!defined($dbh) || !defined($tab) || !defined($col) ||
351 !defined($op) || !defined($val)) {
352 $msg = "Missing inputs for $mtd.";
353 $self->echoMSG($msg); return;
354 }
355 $self->echoMSG(" - deleting records from $tab...");
356 $col = lc($col);
357 $op = uc($op) ;
358 if (!$self->is_object_exist($dbh, $tab, 'column', $col)) {
359 $self->echoMSG(" Column $col does not exist in $tab");
360 return;
361 }
362 my $dbg = $self->debug;
363 $self->debug(-1); # turn off all the message
364 my ($c1,$df3,$cmt)=$self->get_table_definition($dbh,$tab,$col,'HASH');
365 $self->debug($dbg); # restore message level
366 $q = "DELETE FROM $tab\n WHERE $col ";
367 my $typ = ${$df3}{$col}{typ}; # column data type
368 my @a = split / /, $val;
369 if ($typ =~ /^(V|C)/) {
370 for my $i (0..$#a) { $a[$i] = "'$a[$i]'"; }
371 } elsif ($typ =~ /^D/i) {
372 for my $i (0..$#a) { $a[$i] = "TO_DATE('$a[$i]','$dft')"; }
373 }
374 if ($op =~ /^IN$/i) {
375 $q .= "$op (" . (join ',', @a) . ")";
376 } elsif ($op =~ /^(BETWEEN|BTW|BTN)/i) {
377 $q .= "BETWEEN $a[0] AND $a[1]";
378 } elsif ($op =~ /^(LK|LIKE)/i) {
379 $q .= "LIKE '$a[0]'";
380 } else {
381 $q .= "$op @a";
382 }
383 $msg = " $q";
384 $self->echoMSG($msg, 2);
385 my $sth=$dbh->prepare($q) || die "Stmt error: $dbh->errstr";
386 $sth->execute() || die "Stmt error: $dbh->errstr";
387 my $nr = $sth->rows;
388 $self->echoMSG(" $nr rows deleted.",1);
389 # $dbh->commit || die "ERR: $dbh->errstr";
390 return 1;
391 }
392  
393 =head3 insert_records($dbh,$tab,$drf,$pk,$dft)
394  
395 Input variables:
396  
397 $dbh - database handler
398 $tab - target table name
399 $drf - data array reference: ${$arf}[$i]{$col} or
400 a source table.
401 $pk - primary key.
402 $dft - date format. Defaults to 'YYYYMMDD.HH24MISS'
403  
404 Variables used or routines called:
405  
406 echoMSG - echo message
407 check_input_drf - check input array ref
408 is_object_exist - check object existence
409 get_table_definition - get table definitions
410 select_records - get table data
411  
412 How to use:
413  
414 my $cs = 'usr/pwd@db';
415 my $dbh = $self->getDBHandler($cs, "Oracle");
416 my $drf = $self->select_records($dbh,$srctab,'*','','hash');
417 my $tab = "test_table";
418 $self->insert_records($dbh,$tab,$drf);
419  
420 Return: None.
421  
422 This method inserts records in a data array ($drf) into a table.
423 If the primary key is specified, it checks to see if the
424 primary key does not exist in the table. If the primary key exists,
425 it will skip inserting the record. Here are the steps involved
426 in this method:
427 1) Checks whether the table exists;
428 2) Gets the table definition;
429 3) Compares the column names with the column names in the array;
430 4) Gets a list of primary keys in the table;
431 5) Loops through each records in the array;
432 6) Inserts records only if the primary key does not exist in the
433 table.
434  
435 =cut
436  
437 sub insert_records {
438 my $self = shift;
439 my ($dbh, $tab, $drf,$pk,$dft) = @_;
440 $self->echoMSG("\n - inserting records for $tab ...");
441 croak "ERR: no DB handler is specified.\n" if !$dbh;
442 croak "ERR: no table name is specified.\n" if !$tab;
443 croak "ERR: no data array is specified.\n" if !$drf;
444 $drf = $self->check_input_drf($drf,$dbh);
445 $dft = 'YYYYMMDD.HH24MISS' if !$dft;
446 my ($cns,$df3, $cmt) =
447 $self->get_table_definition($dbh,$tab,'','hash');
448 # ${$df1}[$i][$j], ${$df3}{$cn}{$itm}
449 $cns = lc $cns;
450 my $cnt = 0; my $cn1 = "";
451 for my $k (split /,/, $cns) {
452 if (! exists ${$drf}[0]{$k}) { ++$cnt;
453 if ($cn1) { $cn1 .= ",$k"; } else { $cn1 = $k; }
454 }
455 }
456 if ($cnt) {
457 $self->echoMSG("WARN: missing $cnt columns - $cn1");
458 $self->echoMSG(" insert process abandoned.");
459 return 0;
460 }
461 my ($id,$kr) = ($pk,""); # get id column
462 my %key = ();
463 if ($id) {
464 # get a list of keys
465 # select_records($dbh,$tn,$cns,$whr,$atp,$dft,$cdf)
466 $kr = $self->select_records($dbh,$tab,$id,'','array');
467 for my $i (0..$#$kr) { $key{lc ${$kr}[$i][0]} = 1; }
468 }
469 #
470 # insert new records
471 my $vnp = "";
472 # $vnp =~ s/(\w+)/\?/g;
473 my $v = ""; my $p = "";
474 for my $k (split /,/, $cns) {
475 if (${$df3}{$k}{typ} =~ /^DATE/i) {
476 $p = "to_date(?,'$dft')";
477 } else { $p = '?'; }
478 if ($vnp) { $vnp .= ",$p"; } else { $vnp = "$p"; };
479 }
480 my $m3 = $cns; $m3 =~ s/,/,\n/g;
481 my $q = "INSERT INTO $tab\n ($m3)\n VALUES ($vnp)\n";
482 my $m1 = $self->split_cns("($cns)",65,',',6);
483 my $m2 = $self->split_cns("($vnp)",65,',',6);
484 my $msg = " INSERT INTO $tab\n$m1 VALUES \n$m2";
485 $self->echoMSG($msg, 2);
486 my $s = $dbh->prepare($q);
487 my @a = (); $cnt = 0;
488 my ($err,$scc,$idv) = (0,0,0);
489 my @k_inserted = ();
490 my @k_exist = ();
491 for my $i (0..$#{$drf}) {
492 if ($id) {
493 $idv = lc ${$drf}[$i]{$id}; # premier key value
494 if (exists $key{$idv}) {
495 $msg = " Key ($id = $idv) is alread in table $tab";
496 $self->echoMSG($msg, 2);
497 ++$scc; push @k_exist, $idv;
498 next; # skip insert
499 }
500 }
501 @a = ();
502 for my $k (split /,/, $cns) {
503 $v = ${$drf}[$i]{$k};
504 push @a, $self->build_sql_stmt($k,$v,$df3,$dft);
505 }
506 $self->echoMSG((join ',', @a),2);
507 if (!$s->execute(@a)) {
508 ++$err; $self->echoMSG("ERR: Stmt - $s->errstr");
509 } else { ++$cnt; push @k_inserted, $idv; }
510 }
511 my $tot = $#{$drf}+1;
512 $msg = " $cnt out of $tot rows inserted with $err errors.\n";
513 $msg .= " $scc records were skipped due to key already exists.";
514 $self->echoMSG($msg, 2);
515 return (\@k_inserted, \@k_exist);
516 }
517  
518 =head3 check_records($dbh,$tab,$drf,$ckc,$dft)
519  
520 Input variables:
521  
522 $dbh - database handler
523 $tab - target table name
524 $drf - data array reference: ${$arf}[$i]{$col} or
525 a source table.
526 $chc - a list of column names separated by comma and
527 to be checked against the column definition.
528 $dft - date format. Defaults to 'YYYYMMDD.HH24MISS'
529 $pk - primary key. Defaults to the first column
530  
531 Variables used or routines called:
532  
533 echoMSG - echo message
534 check_input_drf - check input array ref
535 is_object_exist - check object existence
536 get_table_definition - get table definitions
537 select_records - get table data
538  
539 How to use:
540  
541 my $cs = 'usr/pwd@db';
542 my $dbh = $self->getDBHandler($cs, "Oracle");
543 my $drf = $self->select_records($dbh,$srctab,'*','','hash');
544 my $tab = "test_table";
545 my $rrf = $self->check_records($dbh,$tab,$drf);
546  
547 Return: $rrf - report hash array reference. The $rrf contains
548 ${$rrf}{$cat}{$itm}{...}, where
549  
550 cn - column name
551 {cn}{no_missing_in_array} - number of colunm name missing
552 in the array comparing to the column names in the
553 table.
554 {cn}{nm_missing_in_array} - a list of column names separated
555 by comma, which are missing in the array comparing to
556 the column names in the table.
557 rec - record related statistics
558 {rec}{total} - total number of records in the array
559 col - column statistics
560 {col}{$cn}{wid} - statistics related to width and range
561 {ok_cnt} - number of records within max and min width and
562 not null requirement if there is any
563 {ok_pct} - percentage of the ok records
564 {emp_rec} - number of empty records, which is excluded
565 from ok_cnt if it is 'not null' column.
566 {bad_typ} - number of bad datatype records.
567 {out_rng} - number of record which is out of range.
568 The range is determined by max and min width
569 for char columns and max and dec width for
570 number fields.
571 {rownum} - a list of row numbers for the records that
572 exceed the max width for char columns or
573 is out of range for numeric fields.
574  
575 This method checks data fields against column definition and report
576 any records that do not confirm with the column definition.
577 Here are the steps involved in this method:
578  
579 1) Checks inputs and data array;
580 2) Gets the table definition;
581 3) Compares the column names with the column names in the array;
582 4) Check data fields
583 5) Report results
584  
585 =cut
586  
587 sub check_records {
588 my $self = shift;
589 my ($dbh, $tab, $drf,$ckc,$dft) = @_;
590 $self->echoMSG("\n - checking records for $tab ...");
591 croak "ERR: no DB handler is specified.\n" if !$dbh;
592 croak "ERR: no table name is specified.\n" if !$tab;
593 croak "ERR: no data array is specified.\n" if !$drf;
594 # 1. check data array
595 $drf = $self->check_input_drf($drf,$dbh);
596 $dft = 'YYYYMMDD.HH24MISS' if !$dft;
597 # 2. get table definition
598 my ($cns,$df3, $cmt) =
599 $self->get_table_definition($dbh,$tab,'','hash');
600 # my ($x1, $x2, $df3) = $self->getTableDef($dbh,$tab);
601 # ${$df1}[$i][$j], ${$df3}{$cn}{$itm}, ${$df2}[$i]{$itm}
602 $cns = lc $cns;
603 $ckc = $cns if (!defined($ckc) || $ckc eq "*" || $ckc eq "");
604 # 3. compare column names
605 my %rpt = ();
606 my $cnt = 0; my $cn1 = "";
607 for my $k (split /,/, $cns) {
608 if (! exists ${$drf}[0]{$k}) { ++$cnt;
609 if ($cn1) { $cn1 .= ",$k"; } else { $cn1 = $k; }
610 }
611 }
612 $rpt{cn}{no_missing_in_array} = $cnt;
613 $rpt{cn}{nm_missing_in_array} = $cn1;
614 $cnt = 0; $cn1 = "";
615 foreach my $k (keys %{${$drf}[0]}) {
616 if (! exists ${$df3}{$k}) { ++$cnt;
617 if ($cn1) { $cn1 .= ",$k"; } else { $cn1 = $k; }
618 }
619 }
620 $rpt{cn}{no_missing_in_table} = $cnt;
621 $rpt{cn}{nm_missing_in_table} = $cn1;
622 # 4. check data fields
623 $rpt{rec}{total} = $#{$drf}+1;
624 for my $k (split /,/, $ckc) { # for each check column name
625 my $j = ${$df3}{$k}{seq};
626 my $typ = ${$df3}{$k}{typ};
627 my $wid = ${$df3}{$k}{wid};
628 my $max = ${$df3}{$k}{max};
629 my $min = ${$df3}{$k}{min};
630 my $dec = ${$df3}{$k}{dec};
631 my $req = ${$df3}{$k}{req};
632 my $fmt = ${$df3}{$k}{dft};
633 my ($max_no,$min_no) = (0,0);
634 if ($typ =~ /^N/i) { # need to define max and min numbers
635 $max_no = ('9' x $max)+0;
636 if ($min > 0) { $min_no = ('1' . ('0' x ($min-1))) + 0; }
637 }
638 if (!exists $rpt{col}{$k}{wid}{max}) {
639 $rpt{col}{$k}{wid}{max} = -1;
640 }
641 if (!exists $rpt{col}{$k}{wid}{min}) {
642 $rpt{col}{$k}{wid}{min} = 9999.99;
643 }
644 if (!exists $rpt{col}{$k}{wid}{avg}) {
645 $rpt{col}{$k}{wid}{avg} = 0;
646 }
647 if (!exists $rpt{col}{$k}{wid}{emp_rec}) {
648 $rpt{col}{$k}{wid}{emp_rec} = 0;
649 }
650 if (!exists $rpt{col}{$k}{wid}{bad_typ}) {
651 $rpt{col}{$k}{wid}{bad_typ} = 0;
652 }
653 if (!exists $rpt{col}{$k}{wid}{out_rng}) {
654 $rpt{col}{$k}{wid}{out_rng} = 0;
655 }
656 if (!exists $rpt{col}{$k}{wid}{ok_cnt}) {
657 $rpt{col}{$k}{wid}{ok_cnt} = 0;
658 }
659 for my $i (0..$#$drf) {
660 my $v = ${$drf}[$i]{$k};
661 my $len = undef;
662 if ($typ =~ /^(C|V|D)/i) { # check width
663 if (!defined($v) || !$v) {
664 ++$rpt{col}{$k}{wid}{emp_rec};
665 next if ($req =~ /^not null/i || $req =~ /^Y/i);
666 $v = "";
667 }
668 $len = ($v)?length($v):0;
669 if ($len>$rpt{col}{$k}{wid}{max}) {
670 $rpt{col}{$k}{wid}{max} = $len;
671 }
672 if ($len<$rpt{col}{$k}{wid}{min}) {
673 $rpt{col}{$k}{wid}{min} = $len;
674 }
675 if (length($v) <= $wid) {
676 ++$rpt{col}{$k}{wid}{ok_cnt}
677 } else {
678 $rpt{col}{$k}{wid}{rownum} .= "$i,"
679 }
680 } elsif ($typ =~ /^N/i) { # check range
681 if (!defined($v) || ($v !~ /^0$/ && !$v)) {
682 ++$rpt{col}{$k}{wid}{emp_rec};
683 next if ($req =~ /^not null/i || $req =~ /^Y/i);
684 ++$rpt{col}{$k}{wid}{ok_cnt};
685 next;
686 }
687 if ($v =~ /^[\d\.]+$/) {
688 $len = $v+0;
689 } else {
690 ++$rpt{col}{$k}{wid}{bad_typ};
691 next;
692 }
693 if ($min_no <= $v && $v <= $max_no ) {
694 ++$rpt{col}{$k}{wid}{ok_cnt};
695 } else {
696 ++$rpt{col}{$k}{wid}{out_rng};
697 $rpt{col}{$k}{wid}{rownum} .= "$i,"
698 }
699 } elsif ($typ =~ /^D/i) { # check date format
700 } else {
701 }
702 if ($len>$rpt{col}{$k}{wid}{max}) {
703 $rpt{col}{$k}{wid}{max} = $len;
704 }
705 if ($len<$rpt{col}{$k}{wid}{min}) {
706 $rpt{col}{$k}{wid}{min} = $len;
707 }
708 $rpt{col}{$k}{wid}{avg} += $len;
709 }
710 }
711 # 5. report results
712 my $msg = " Compared the array against table $tab and here is";
713 $msg .= "the result:\n Total records comparied: ";
714 $msg .= "$rpt{rec}{total}\n";
715 $msg .= " $rpt{cn}{no_missing_in_array} column(s) ";
716 $msg .= "missing in the array.\n";
717 if ($rpt{cn}{no_missing_in_array} > 0) {
718 $msg .= " They are $rpt{cn}{nm_missing_in_array}.";
719 }
720 $msg .= " $rpt{cn}{no_missing_in_table} column(s) ";
721 $msg .= "missing in the table.\n";
722 if ($rpt{cn}{no_missing_in_table} > 0) {
723 $msg .= " They are $rpt{cn}{nm_missing_in_table}.";
724 }
725 $msg .= " Column Statistics:\n";
726 $msg .= sprintf "%3s %35s %7s %7s %7s %5s %7s %5s %5s\n",
727 "Seq", "ColName[data_type(max,min)]",
728 "Max", "Min", "Avg", "#OK", "OK%", "Empty", "BadRC";
729 $msg .= sprintf "%3s %35s %7s %7s %7s %5s %7s %5s %5s \n",
730 "-"x3, "-"x35, "-"x7, "-"x7, "-"x7, "-"x5, "-"x7,
731 "-"x5, "-"x5;
732 my $ft1 = "%3d %35s %7.2f %7.2f %7.2f %5d %7.2f %5d %5d\n";
733 for my $k (split /,/, $ckc) { # for each check column name
734 my $j = ${$df3}{$k}{seq};
735 my $c = "$k\[${$df3}{$k}{typ}";
736 if (${$df3}{$k}{typ} =~ /^N/i) {
737 $c .= "(${$df3}{$k}{max},${$df3}{$k}{dec})";
738 } else {
739 $c .= "(${$df3}{$k}{max},${$df3}{$k}{min})";
740 }
741 if (${$df3}{$k}{req} =~ /^(not null|y)/i) {
742 $c .= ",${$df3}{$k}{req}]";
743 } else {
744 $c .= "]";
745 }
746 my $avg = $rpt{col}{$k}{wid}{avg} / $rpt{rec}{total};
747 $rpt{col}{$k}{wid}{avg} = $avg;
748 $rpt{col}{$k}{wid}{ok_pct} = 100 * $rpt{col}{$k}{wid}{ok_cnt}
749 / $rpt{rec}{total};
750 $msg .= sprintf $ft1, $j, $c, $rpt{col}{$k}{wid}{max},
751 $rpt{col}{$k}{wid}{min}, $rpt{col}{$k}{wid}{avg},
752 $rpt{col}{$k}{wid}{ok_cnt}, $rpt{col}{$k}{wid}{ok_pct},
753 $rpt{col}{$k}{wid}{emp_rec},
754 $rpt{col}{$k}{wid}{bad_typ};
755 }
756 $self->echoMSG($msg, 1);
757 return \%rpt;
758 }
759  
760 =head3 update_records($dbh,$tab,$drf,$pk,$dft,$skn)
761  
762 Input variables:
763  
764 $dbh - database handler
765 $tab - target table name
766 $drf - data array reference: ${$arf}[$i]{$col} or
767 a source table.
768 $pk - primary key. Defaults to the first column or specified as
769 my_id
770 my_id:upper
771 my_id=u_id
772 my_id:lpad('0',?)=u_id:lpad('0',?)
773 $dft - date format. Defaults to 'YYYYMMDD.HH24MISS'
774 $skn - skip null: 1|0.
775 1 - default to skip updating the column if the new value
776 is null but the target column is not null.
777 0 - update the column any way.
778  
779 Variables used or routines called:
780  
781 echoMSG - echo message
782 is_object_exist - check object existence
783 get_table_definition - get table definitions
784 select_records - get table data
785  
786 How to use:
787  
788 my $cs = 'usr/pwd@db';
789 my $dbh = $self->getDBHandler($cs, "Oracle");
790 my $drf = $self->select_records($dbh,$srctab,'*','','hash');
791 my $tab = "test_table";
792 $self->update_records($dbh,$tab,$drf);
793  
794 Return: None.
795  
796 This method updates records in a data array ($drf) into a table if the
797 primary key does not exist in the table. Here are the steps involved
798 in this method:
799 1) Checks whether the table exists;
800 2) Gets the table definition;
801 3) Get common column names in table and in the array;
802 4) Gets a list of primary keys in the table;
803 5) Loops through each records in the array;
804 6) Updates records only if the primary key does exist in the table.
805  
806 =cut
807  
808 sub update_records {
809 my $self = shift;
810 my ($dbh,$tab,$drf,$pk,$dft,$skn) = @_;
811 $self->echoMSG("\n - updateing records for $tab ...");
812 croak "ERR: no DB handler is specified.\n" if !$dbh;
813 croak "ERR: no table name is specified.\n" if !$tab;
814 croak "ERR: no data array is specified.\n" if !$drf;
815 $dft = 'YYYYMMDD.HH24MISS' if !$dft;
816 $skn = 1 if (!defined $skn || $skn !~ /^0$/);
817 if (!$self->is_object_exist($dbh,$tab,'table')) {
818 $self->echoMSG("WARN: table - $tab does not exist!");
819 return 0;
820 }
821 $drf = $self->check_input_drf($drf,$dbh);
822 my ($cn1,$cn2,$dfa,$dfb,$df3,$cmt,$df4,$cns);
823 ($cn2,$df3,$cmt)=$self->get_table_definition($dbh,$tab,'','hash');
824 ($cn2,$df4,$cmt)=$self->get_table_definition($dbh,$tab,'','ah2');
825 $cns = lc $cn2;
826 my $cnt = 0;
827 my $ucn = ""; # columns will be updated
828 my $cnx = ""; # columns will not be updated
829 for my $k (split /,/, $cns) {
830 if (! exists ${$drf}[0]{$k}) { ++$cnt;
831 if ($cnx) { $cnx .= ",$k"; } else { $cnx = $k; }
832 } else {
833 if ($ucn) { $ucn .= ",$k"; } else { $ucn = $k; }
834 }
835 }
836 my $m1 = $self->split_cns("($ucn)",65,',',4);
837 my $msg = " columns \n $m1 will be updated.\n";
838 $msg .= " $cnt columns will not be updated.";
839 $self->echoMSG("$msg",2) if ($cnt);
840 my ($id1,$id2,$fn1,$fn2)= ("","","","");
841 if ($pk && index($pk,'=')) { # composite keys
842 my ($s2,$s1) = ("","");
843 ($s2,$s1) = split /=/, $pk; # to_id=from_id
844 ($id1,$fn1) = split /:/, $s1
845 if $s1; # id:lpad('0',?)
846 ($id2,$fn2) = split /:/, $s2; # id:function, ex: id:upper
847 }
848 $id2 = $pk if !$id2; # get id column
849 ($id2) = ($cns =~ /^(\w+),/) if !$id2;# default to 1st column
850 $id1 = $id2 if !$id1;
851 if ($fn1) { # user specified a function
852 if (index($fn1, '?') < 0) { $fn1 = (uc $fn1) . "($id1)";
853 } else { $fn1 =~ s/\?/$id1/g; }
854 }
855 if ($fn2) { # user specified a function
856 if (index($fn2, '?') < 0) { $fn2 = (uc $fn2) . "($id2)";
857 } else { $fn2 =~ s/\?/$id2/g; }
858 }
859 # get a list of keys from target table
860 my $kr = $self->select_records($dbh,$tab,$id2,'','array');
861 my %key = ();
862 for my $i (0..$#$kr) { $key{lc ${$kr}[$i][0]} = 1; }
863 # get a list of keys from source data array
864 my $idv = ""; # id value
865 my $id1_lst = ""; # source id list
866 my %ktm = ();
867 for my $i (0..$#{$drf}) {
868 $idv = ${$drf}[$i]{$id2};
869 next if exists $ktm{$idv};
870 $ktm{$idv} = 1;
871 $id1_lst .= $self->build_sql_stmt($id2,$idv,$df3,$dft,1);
872 }
873 $id1_lst =~ s/,$//; # remove the last comma
874 # get records matching with source keys from target table
875 my $wh2 = "WHERE $id2 IN ($id1_lst)";
876 print "WH2: $wh2<br>\n"; # XXX
877 my $d2r = $self->select_records($dbh,$tab,'',$wh2,'lc_hash',
878 $dft,$df4);
879 # convert sequence based array into hash array with id as key
880 my %d2 = (); # target records
881 for my $i (0..$#$d2r) {
882 foreach my $k (keys %{${$d2r}[$i]}) {
883 my $ik = ${$d2r}[$i]{$id2}; # primary key
884 my $cv = ${$d2r}[$i]{$k}; # column value
885 $d2{$ik}{$k} = $cv;
886 }
887 }
888 #
889 # update records
890 my $vnp = $ucn; $vnp =~ s/(\w+)/\?/g;
891 # my $q = "UPDATE $tab SET\n ($ucn) =\n";
892 my $q = "UPDATE $tab SET \n";
893 my @a = (); $cnt = 0;
894 my ($err,$scc,$er2,$tcn) = (0,0,0,0);
895 $msg = " looping through each record in array...";
896 $self->echoMSG("$msg",2);
897 # $self->disp_param($drf); $self->disp_param(\%d2);
898 for my $i (0..$#{$drf}) { # loop thru each record
899 $idv = ${$drf}[$i]{$id2};
900 if (! exists $key{$idv}) {
901 $msg = " Key ($id2 = $idv) not in table $tab: skipped";
902 $self->echoMSG($msg, 2);
903 next;
904 }
905 my $whr = " WHERE "; # update condition
906 if ($fn1) { $whr .= "$fn1 = "; } else { $whr .= "$id1 = "; }
907 if ($fn2) { $whr .= $fn2;
908 } else {
909 $whr .= $self->build_sql_stmt($id1,$idv,$df3,$dft);
910 }
911 # $self->echoMSG("FN1=$fn1;FN2=$fn2; WHR=$whr", 2);
912 for my $k (split /,/, $ucn) { # loop thru each updating col
913 ++$tcn;
914 my $v = ${$drf}[$i]{$k}; # new value
915 $v = '' if (!defined $v || $v =~ /^null$/i);
916 my $v2 = $d2{$idv}{$k}; # value from target table
917 if ($skn && $v eq '' && defined($v2)) {
918 # When new value is null while target value is not,
919 # we are going to preserve the existing value.
920 ++$er2;
921 next;
922 }
923 $v = "" if ! defined $v;
924 $v2 = "" if ! defined $v2;
925 # print "V1=$v; V2=$v2\n";
926 # compare the two value. If they are the same, there is
927 # no need to update the column
928 if (uc "$v" eq uc "$v2") {
929 ++$scc; # skipped column count
930 next; # no need to update
931 }
932 $q = "UPDATE $tab SET \n $k = ";
933 $q .= $self->build_sql_stmt($k,$v,$df3,$dft,1);
934 $q =~ s/,$/\n/; # remove last comma
935 $q .= " $whr";
936 $self->echoMSG("Q: $q", 2);
937 my $s = $dbh->prepare($q) ||
938 print "ERR: Stmt - $dbh->errstr";
939 if (!$s->execute()) {
940 ++$err; print "ERR: Stmt - $s->errstr";
941 }
942 }
943 ++$cnt;
944 }
945 my $tot = $#{$drf}+1;
946 $msg = " $cnt out of $tot rows updated with $err errors.\n";
947 $msg .= " $scc out of $tcn columns were skipped due to ";
948 $msg .= "no change in values.\n";
949 $msg .= " $er2 columns have null value ";
950 $msg .= "and updating was skipped.";
951 $self->echoMSG($msg, 2);
952 return 1;
953 }
954  
955 =head2 Exported Tag: Misc
956  
957 The I<:misc> tag includes all the miscellaneous methods or sub-rountines
958 defined in this class.
959  
960 use Oracle::DML qw(:misc);
961  
962 =cut
963  
964 1;
965  
966 =head1 HISTORY
967  
968 =over 4
969  
970 =item * Version 0.10
971  
972 This version is to test the concept.
973  
974 =item * Version 0.2
975  
976  
977 =cut
978  
979 =head1 SEE ALSO (some of docs that I check often)
980  
981 Data::Describe, Oracle::Loader, Oracle::Trigger,
982 CGI::Getopt, File::Xcopy, Oracle::DDL, Oracle::DML, etc
983  
984 =head1 AUTHOR
985  
986 Copyright (c) 2005 Hanming Tu. All rights reserved.
987  
988 This package is free software and is provided "as is" without express
989 or implied warranty. It may be used, redistributed and/or modified
990 under the terms of the Perl Artistic License (see
991 http://www.perl.com/perl/misc/Artistic.html)
992  
993 =cut
994