blib/lib/Trigger.pm untested

filter: Statementstmt 0.0% 0 / 217 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 58 MC/DCmcdc 0.0% 0 / 36 Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 448 CC 60 SCAR 54.9
CC
60
Cov
0%
create_data_audit
462.0
prepare
272.0
create_data_trigger
210.0
CRAP 243.0
1 package Oracle::Trigger;
2  
3 # Perl standard modules
4 use strict;
5 use warnings;
6 use Carp;
7 # use CGI::Carp qw(fatalsToBrowser warningsToBrowser);
8 # warningsToBrowser(1);
9 # use CGI;
10 # use Getopt::Std;
11 use DBI;
12 use Debug::EchoMessage;
13 use Oracle::DML::Common qw(:db_conn);
14 use Oracle::Schema qw(:table);
15  
16 require 5.003;
17 $Oracle::Trigger::VERSION = 0.22;
18  
19 require Exporter;
20 our @ISA = qw(Exporter);
21 our @EXPORT = qw();
22 our @EXPORT_OK = qw( prepare execute
23 create_data_trigger create_data_audit
24 );
25 our %EXPORT_TAGS = (
26 all => [@EXPORT_OK],
27 data => [qw(create_data_trigger create_data_audit)],
28 );
29 our @IMPORT_OK = qw(
30 get_dbh is_object_exist get_table_definition
31 debug echoMSG disp_param
32 );
33  
34 =head1 NAME
35  
36 Oracle::Trigger - Perl class for creating Oracle triggers
37  
38 =head1 SYNOPSIS
39  
40 use Oracle::Trigger;
41  
42 my %cfg = ('conn_string'=>'usr/pwd@db', 'table_name'=>'my_ora_tab');
43 my $ot = Oracle::Trigger->new;
44 # or combine the two together
45 my $ot = Oracle::Trigger->new(%cfg);
46 my $sql= $ot->prepare(%cfg);
47 $ot->execute(); # actually create the audit table and trigger
48  
49 # call the methods directly
50 my $sql = $ot->create_data_trigger($tn,$cns,$dbh,$trg,$aud);
51 my $ar = $ot->create_data_audit($tn,$cns,$dbh,$aud,$drp);
52  
53  
54 =head1 DESCRIPTION
55  
56 This class contains methods to create audit tables and triggers for
57 Oracle tables.
58  
59 =cut
60  
61 =head2 new (conn_string=>'usr/pwd@db',table_name=>'my_table')
62  
63 Input variables:
64  
65 $cs - Oracle connection string in usr/pwd@db
66 $tn - Oracle table name without schema
67  
68 Variables used or routines called:
69  
70 None
71  
72 How to use:
73  
74 my $obj = new Oracle::Trigger; # or
75 my $obj = Oracle::Trigger->new; # or
76 my $cs = 'usr/pwd@db';
77 my $tn = 'my_table';
78 my $obj = Oracle::Trigger->new(cs=>$cs,tn=>$tn); # or
79 my $obj = Oracle::Trigger->new('cs',$cs, 'tn',$tn);
80  
81 Return: new empty or initialized Oracle::Trigger object.
82  
83 This method constructs a Perl object and capture any parameters if
84 specified. It creates and defaults the following variables:
85
86 $self->{conn_string} = ""; # or $self->{cs}
87 $self->{table_name} = ""; # or $self->{tn}
88  
89 =cut
90  
91 sub new {
92 my $caller = shift;
93 my $caller_is_obj = ref($caller);
94 my $class = $caller_is_obj || $caller;
95 my $self = bless {}, $class;
96 my %arg = @_; # convert rest of inputs into hash array
97 foreach my $k ( keys %arg ) {
98 if ($caller_is_obj) {
99 $self->{$k} = $caller->{$k};
100 } else {
101 $self->{$k} = $arg{$k};
102 }
103 }
104 my $vs = 'conn_string,table_name,cs,tn';
105 foreach my $k (split /,/, $vs) {
106 $self->{$k} = "" if ! exists $arg{$k};
107 $self->{$k} = $arg{$k} if exists $arg{$k};
108 }
109 my $cs1 = $self->{conn_string};
110 my $tn1 = $self->{table_name};
111 $self->{cs} = ($cs1)?$cs1:$self->{cs};
112 $self->{tn} = ($tn1)?$tn1:$self->{tn};
113 $self->{conn_string} = ($self->{cs})?$self->{cs}:$cs1;
114 $self->{table_name} = ($self->{tn})?$self->{tn}:$tn1;
115 return $self;
116 }
117  
118 =head1 METHODS
119  
120 The following are the common methods, routines, and functions
121 defined in this class.
122  
123 =head2 Exported Tag: All
124  
125 The I<:all> tag includes all the methods or sub-rountines
126 defined in this class.
127  
128 use Oracle::Trigger qw(:all);
129  
130 It includes the following sub-routines:
131  
132 =head3 prepare($cs, $tn, $tp)
133  
134 Input variables:
135  
136 $cs - Oracle connection string in usr/pwd@db
137 $tn - Oracle table name without schema
138 $tp - trigger type
139 DATA - trigger to audit a table. This is the default.
140  
141 Variables used or routines called:
142  
143 Debug::EchoMessage
144 echoMSG - display message
145 {cs} - connection string
146 {tn} - table name
147 {drop_audit} - whether to drop audit table if it exists
148 {audit_table} - audit table name, default to aud${$tn}
149 {trigger_name} - trigger name, default to trg${$tn}
150  
151 How to use:
152  
153 my $ar = $self->prepare('usr/pwd@db','my_tab');
154  
155 Return: $hr - a hash array ref containing the following keys:
156  
157 dbh - the database handler
158 sql_audit - SQL statement for creating the audit table
159 sql_trigger - SQL statement for creating the trigger
160  
161 This method performs the following tasks:
162  
163 1) create a database handler
164 2) check the existance of the table
165 3) generate script for creating audit table
166 4) generate script for creating trigger
167  
168 And it sets the following internal variable as well:
169  
170 {dbh} - database handler
171 {sql_audit} - sql statements to create audit table
172 {sql_trigger} - sql statement to create trigger
173  
174 =cut
175  
176 sub prepare {
177 my $s = shift;
178 my ($cs, $tn, $tp) = @_;
179 $s->echoMSG("+++ Preparing SQL statement +++",1);
180 #
181 # 0. check inputs
182 $s->echoMSG("0 - checking inputs...", 1);
183 $cs = $s->{cs} if !$cs;
184 $tn = $s->{tn} if !$tn;
185 $tp = 'DATA' if !$tp;
186 $s->echoMSG("Connection string is not specified.", 1) if ! $cs;
187 $s->echoMSG("Table name is not specified.", 1) if ! $tn;
188 my %r = (); # result hash
189 return \%r if !$cs || !$tn;
190 $s->echoMSG("CS=$cs\nTN=$tn",3);
191 $s->echoMSG("ARGV: @ARGV",3);
192 #
193 # 1. create and save database handler
194 $s->echoMSG("1 - creating database handler...", 1);
195 my $dbh = $s->get_dbh($cs,'Oracle');
196 $s->{dbh} = $dbh;
197 #
198 # 2. check the existence of the table
199 $s->echoMSG("2 - checking the existence of table $tn...", 1);
200 my $tex = $s->is_object_exist($dbh,$tn);
201 $s->echoMSG("Table $tn: could not be found.", 1) if ! $tex;
202 return \%r if ! $tex;
203 #
204 # 3. generate SQL for creating audit table
205 $s->echoMSG("3 - generating SQL for creating audit table...", 1);
206 my ($aud, $trg, $drop, $sql) = (0,0,0,0);
207 $aud = $s->{audit_table} if exists $s->{audit_table};
208 $aud = "AUD\$$tn" if ! $aud;
209 $trg = $s->{trigger_name} if exists $s->{trigger_name};
210 $trg = "TRG\$$tn" if ! $trg;
211 $r{$aud} = bless [], ref($s);
212 # 3.1 check whether $aud table exist
213 $drop = $s->{drop_audit} if exists $s->{drop_audit};
214 $s->{create_audit} = 1;
215 if ($tp =~ /^data/i) {
216 $r{$aud} = $s->create_data_audit($tn,'',$dbh,$aud,$drop);
217 }
218 $s->{sql_audit} = $r{$aud};
219 #
220 # 4. generate SQL for creating trigger
221 $s->echoMSG("4 - generating SQL for creating trigger...", 1);
222 $s->{create_trigger} = 1;
223 $s->echoMSG(" Trigger $trg will be created or replaced.", 2);
224 $r{$trg} = bless [], ref($s);
225 if ($tp =~ /^data/i) {
226 $sql = $s->create_data_trigger($tn,'',$dbh,$trg,$aud);
227 push @{$r{$trg}}, $sql;
228 }
229 $s->{sql_trigger} = $r{$trg};
230 return \%r;
231 }
232  
233 =head3 execute($typ)
234  
235 Input variables:
236  
237 $typ - action type:
238 TRIGGER - create trigger only
239 AUDIT - create audit table only
240 default - null and will create both
241  
242 Variables used or routines called:
243  
244 {dbh} - database handler
245 {sql_audit} - sql statements to create audit table
246 {sql_trigger} - sql statement to create trigger
247  
248 How to use:
249  
250 my $status = $self->execute();
251 $self->execute();
252  
253 Return: 0|1: 0 - OK; 1 - failed
254  
255 This method submits the sql statement to Oracle server to create
256 audit table or trigger or both. The default is to create both.
257 If the audit table exists, it will skip creating the audit table. You
258 either need to manually drop the table or set {drop_audit} to '1'
259 before you run prepare().
260  
261 =cut
262  
263 sub execute {
264 my $s = shift;
265 my ($tp) = @_;
266 $tp = 'both' if ! $tp;
267 $s->echoMSG("+++ Executing SQL statement +++",1);
268 $s->echoMSG("1 - getting variables...", 1);
269 my $dbh = $s->{dbh};
270 my $aud = $s->{sql_audit};
271 my $trg = $s->{sql_trigger};
272 my $crt_aud = $s->{create_audit};
273 my $crt_trg = $s->{create_trigger};
274 # $s->disp_param($aud);
275 # $s->disp_param($trg);
276 $s->echoMSG("2 - executing SQL statement...", 1);
277 my @a = ();
278 if ($tp && $tp =~ /^(aud|both)/i && $crt_aud) {
279 $s->echoMSG(" creating audit table...", 2);
280 push @a, @$aud;
281 } else {
282 $s->echoMSG(" creating audit table: skipped.", 2);
283 }
284 if ($tp && $tp =~ /^(tri|both)/i && $crt_trg) {
285 $s->echoMSG(" creating trigger...", 2);
286 push @a, @$trg;
287 } else {
288 $s->echoMSG(" creating trigger: skipped.", 2);
289 }
290 $s->echoMSG("No SQL statements.", 1) if ! @a;
291 foreach my $q (@a) {
292 $s->echoMSG($q, 5);
293 my $s1=$dbh->prepare($q) || croak "ERR: Stmt - $dbh->errstr";
294 $s1->execute() || croak "ERR: Stmt - $dbh->errstr";
295 }
296 return 0;
297 }
298  
299 =head3 create_data_trigger($tn, $cns, $dbh, $trg, $aud)
300  
301 Input variables:
302  
303 $tn - Oracle table name without schema
304 $cns - a list of column names separated by comma
305 $dbh - database handler
306 $trg - trigger name defaults to "TRG${$tn}"
307 $aud - audit table name defaults to "AUD${$tn}"
308  
309 Variables used or routines called:
310  
311 How to use:
312  
313 my $tn = 'mytab';
314 my $tg = 'mytab_trg';
315 my $cns = 'id,name';
316 my $dbh = $self->get_dbh('usr/pwd@db');
317 # No DB connection: $tn,$cns and default trigger name to trg${$tn}:
318 my $sql = $self->create_data_trigger($tn,$cns);
319 # Need DB connection: $tn,$dbh
320 $sql = $self->create_data_trigger($tn,'',$dbh,$tg);
321 # table does not exist, $cns will be used; if table exists, then
322 # $cns will be checked agaign column names from table
323 $sql = $self->create_data_trigger($tn,$cns,$dbh);
324  
325 Return: $sql - SQL statement to create a DATA trigger.
326  
327 This method performs the following tasks:
328  
329 1) check inputs, table name is required
330 2) check the existance of the table.
331 3) compose columns
332 4) compose SQL code for creating trigger
333  
334 An empty string will be returned if the inputs do not meet one of
335 the following cases:
336 a) table name and column list are provided;
337 b) table name and database handler are provided so that column
338 names are obtained from the table;
339 c) table name, column list, and database handler are provided, then
340 column names are obtained from the table and compared with the column
341 list are well. None existing columns in the column list will be
342 excluded from trigger.
343  
344 =cut
345  
346 sub create_data_trigger {
347 my $s = shift;
348 my ($tn, $cns, $dbh, $trg, $aud) = @_;
349 $s->echoMSG("+ - generating SQL for creating DATA trigger...", 1);
350 my $sql = ""; # result code
351 # 1. check inputs
352 my $msg = "Database handler or column list is required.";
353 $s->echoMSG(" No table name: abort!") if !$tn;
354 $s->echoMSG(" $msg") if !$cns && !$dbh;
355 $trg = "TRG\$$tn" if !$trg;
356 $aud = "AUD\$$tn" if !$aud;
357 return $sql if !$tn || (!$cns && !$dbh);
358  
359 # 2 check whether the table exist
360 # $cn1 - a list of column names separated by comma
361 # $cda - column definition array in ${$cda}[$i]{$cn}
362 # $cmt - comment array in {$cn}
363 my ($cn0,$cn1,$cn2,$cda,$cmt) = ("","","","","");
364 if ($dbh && $s->is_object_exist($dbh,$tn)) {
365 ($cn0,$cda,$cmt)=$s->get_table_definition($dbh,$tn,'','ah1');
366 if ($cns) { # we need to check whether they exist in table
367 foreach my $c (split /,/, $cns) {
368 $cn1 .= "$c," if !exists ${$cmt}{$c};
369 $cn2 .= "$c," if exists ${$cmt}{$c};
370 }
371 $cn1 =~ s/,$// if $cn1;
372 $cn2 =~ s/,$// if $cn2;
373 $s->echoMSG("WARN: $cn1 not in $cns!", 2) if $cn1;
374 # only use those exist in table excluding $cn1
375 $cns = $cn2 if $cn1;
376 } else { # use all the columns from table
377 $cns = $cn0;
378 }
379 }
380 # 3 compose the columns
381 my ($c1, $c2, $c3);
382 foreach my $c (split /,/, $cns) {
383 $c = uc $c; # convert to upper case
384 $c1 .= " $c,\n"; # original columns
385 $c2 .= " :new.$c,\n"; # new values
386 $c3 .= " :old.$c,\n"; # old values
387 }
388 $c1 .= " AUDIT_ACTION,\n AUDIT_DTM,\n AUDIT_USER";
389 $c2 .= " v_operation, \n SYSDATE, \n USER";
390 $c3 .= " v_operation, \n SYSDATE, \n USER";
391 # 4 compose the sql statement
392 $sql = "CREATE OR REPLACE TRIGGER $trg\n";
393 $sql .= " AFTER INSERT OR DELETE OR UPDATE ON $tn\n";
394 $sql .= " FOR EACH ROW\n";
395 $sql .= "DECLARE\n v_operation VARCHAR2(10) := NULL;\n";
396 $sql .= "BEGIN\n IF INSERTING THEN\n v_operation := 'INS';\n";
397 $sql .= " ELSIF UPDATING THEN\n v_operation := 'UPD';\n";
398 $sql .= " ELSE\n v_operation := 'DEL';\n END IF;\n";
399 $sql .= " IF INSERTING OR UPDATING THEN\n";
400 $sql .= " INSERT INTO $aud (\n$c1\n ) VALUES (\n";
401 $sql .= "$c2\n );\n";
402 $sql .= " ELSE\n";
403 $sql .= " INSERT INTO $aud (\n$c1\n ) VALUES (\n";
404 $sql .= "$c3\n );\n";
405 $sql .= " END IF;\nEND;\n";
406 return $sql;
407 }
408  
409 =head3 create_data_audit($tn, cnsp, $dbh, $aud, $drp)
410  
411 Input variables:
412  
413 $tn - source table name without schema
414 $cns - column names separated by comma
415 $dbh - database handler
416 $aud - audit table name
417 $drp - whether to drop audit table before creating it
418 default is 0 (no)
419  
420 Variables used or routines called:
421  
422 How to use:
423  
424 my $tn = 'mytab';
425 my $aud = 'aud$mytab';
426 my $dbh = $self->get_dbh('usr/pwd@db');
427 # create audit table
428 # and default audit name is aud${$tn}:
429 my $ar = $self->create_data_audit($tn,$cns);
430  
431 # give a trigger name
432 $sql = $self->create_data_audit($tn,$tg);
433 # table does not exist, but colun names are provided:
434 $sql = $self->create_data_audit($tn,'','id,name');
435 # if $dbh is provided, the table existence will be checked
436 $sql = $self->create_data_audit($tn,'','',$dbh);
437  
438 Return: $ar - array ref containing SQL statements for dropping and
439 creating audit table.
440  
441 This method performs the following tasks:
442  
443 1) check inputs, table name is required
444 2) check the existance of the table.
445 3) compose columns
446 4) compose SQL code for creating trigger
447  
448 An empty string will be returned if the inputs do not meet one of
449 the following cases:
450 a) table name and column list are provided;
451 b) table name and database handler are provided so that column
452 names are obtained from the table;
453 c) table name, column list, and database handler are provided, then
454 column names are obtained from the table and compared with the column
455 list are well. None existing columns in the column list will be
456 excluded from trigger.
457  
458 =cut
459  
460 sub create_data_audit {
461 my $s = shift;
462 my ($tn, $cns, $dbh, $aud, $drp) = @_;
463 $s->echoMSG("+ - generating SQL for creating audit table...", 1);
464 my $r = bless [], ref($s);
465  
466 # 1. check inputs
467 my $msg = "Database handler or column list is required.";
468 $s->echoMSG(" No table name: abort!") if !$tn;
469 $s->echoMSG(" $msg") if !$cns && !$dbh;
470 $aud = "AUD\$$tn" if !$aud;
471 $drp = 0 if !$drp;
472 return $r if !$tn || (!$cns && !$dbh);
473  
474 # 2 check whether we need to drop the audit table
475 my $at_ext = 0; # audit table exist?
476 $at_ext = $s->is_object_exist($dbh,$aud) if $dbh;
477 my $sql = ""; # result code
478 $s->echoMSG(" Audit table $aud does not exist.", 2) if !$at_ext;
479 $sql = "DROP TABLE $aud";
480 push @{$r}, $sql if $drp && $at_ext;
481 $msg = " Audit table $aud will be dropped before being created.";
482 $s->echoMSG($msg, 2) if $drp && $at_ext;
483 $msg = " Audit table $aud exists and will not be created.";
484 $s->echoMSG($msg, 2) if !$drp && $at_ext;
485 return $r if !$drp && $at_ext;
486  
487 # 3. check column names
488 my ($cn0,$cn1,$cn2,$cda,$cmt) = ("","","","","");
489 if ($dbh && $$at_ext) {
490 ($cn0,$cda,$cmt)=$s->get_table_definition($dbh,$tn,'','ah1');
491 if ($cns) { # we need to check whether they exist in table
492 foreach my $c (split /,/, $cns) {
493 $cn1 .= "$c," if !exists ${$cmt}{$c};
494 $cn2 .= "$c," if exists ${$cmt}{$c};
495 }
496 $cn1 =~ s/,$// if $cn1;
497 $cn2 =~ s/,$// if $cn2;
498 $s->echoMSG("WARN: $cn1 not in $cns!", 2) if $cn1;
499 # only use those exist in table excluding $cn1
500 $cns = $cn2 if $cn1;
501 } else { # use all the columns from table
502 $cns = $cn0;
503 }
504 }
505 $cns = '*' if ! $cns;
506  
507 # 4. compose SQL statement
508 $sql = "CREATE TABLE $aud AS \n SELECT $cns \n FROM $tn \n";
509 $sql .= " WHERE 1=0";
510 push @{$r}, $sql;
511 $sql = "ALTER TABLE $aud ADD (\n audit_action CHAR(3),\n";
512 $sql .= " audit_dtm DATE,\n audit_user VARCHAR2(30)\n )";
513 push @{$r}, $sql;
514 return $r;
515 }
516  
517 1;
518  
519 =head1 HISTORY
520  
521 =over 4
522  
523 =item * Version 0.1
524  
525 This version is to test the procedures and create DATA trigger.
526  
527 04/22/2005 (htu) - finished creating DATA trigger rountines.
528  
529 =item * Version 0.2
530  
531 04/29/2005 (htu) - modified some descriptions and moved the common
532 routines to Oracle::DML::Common.
533  
534 =item * Version 0.21
535  
536 Since get_table_definition is moved to Oracle::Schema, we change it
537 here to use Oracle::Schema.
538  
539 =item * Version 0.22
540  
541 Re-wrote I<prepare> method so that it can prepare SQL statments based
542 on trigger type.
543  
544 Added I<create_data_trigger> and I<create_data_audit> methods.
545  
546 =cut
547  
548 =head1 SEE ALSO (some of docs that I check often)
549  
550 Data::Describe, Oracle::Loader, CGI::Getopt, File::Xcopy,
551 perltoot(1), perlobj(1), perlbot(1), perlsub(1), perldata(1),
552 perlsub(1), perlmod(1), perlmodlib(1), perlref(1), perlreftut(1).
553  
554 =head1 AUTHOR
555  
556 Copyright (c) 2005 Hanming Tu. All rights reserved.
557  
558 This package is free software and is provided "as is" without express
559 or implied warranty. It may be used, redistributed and/or modified
560 under the terms of the Perl Artistic License (see
561 http://www.perl.com/perl/misc/Artistic.html)
562  
563 =cut
564  
565