blib/lib/PLSQL.pm untested

filter: Statementstmt 0.0% 0 / 431 Branchbran 0.0% 0 / 198 Conditioncond 0.0% 0 / 64 MC/DCmcdc 0.0% 0 / 40 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 757 CC 100 SCAR 69.6
CC
100
Cov
0%
exec_plsql
2256.0
call_plsql
462.0
read_plsql
240.0
CRAP 1051.8
1 package CGI::AppBuilder::PLSQL;
2  
3 # Perl standard modules
4 use strict;
5 use warnings;
6 use Getopt::Std;
7 use POSIX qw(strftime);
8 use Carp;
9 use CGI::AppBuilder;
10 use CGI::AppBuilder::Message qw(:echo_msg);
11 use File::Path;
12 use Net::Rexec 'rexec';
13  
14 our $VERSION = 0.12;
15 require Exporter;
16 our @ISA = qw(Exporter CGI::AppBuilder);
17 our @EXPORT = qw();
18 our @EXPORT_OK = qw( exec_plsql call_plsql read_plsql _parseline2
19 expand_vars expand_code
20 );
21 our %EXPORT_TAGS = (
22 plsql => [qw(exec_plsql call_plsql read_plsql)],
23 all => [@EXPORT_OK]
24 );
25  
26 =head1 NAME
27  
28 CGI::AppBuilder::PLSQL - Oracle PL/SQL Procedures
29  
30 =head1 SYNOPSIS
31  
32 use CGI::AppBuilder::PLSQL;
33  
34 my $sec = CGI::AppBuilder::PLSQL->new();
35 my ($sta, $msg) = $sec->exe_sql($ar);
36  
37 =head1 DESCRIPTION
38  
39 This class provides methods for reading and parsing configuration
40 files.
41  
42 =cut
43  
44 =head2 new (ifn => 'file.cfg', opt => 'hvS:')
45  
46 This is a inherited method from CGI::AppBuilder. See the same method
47 in CGI::AppBuilder for more details.
48  
49 =cut
50  
51 sub new {
52 my ($s, %args) = @_;
53 return $s->SUPER::new(%args);
54 }
55  
56 =head2 exec_plsql($q,$ar)
57  
58 Input variables:
59  
60 $q - CGI class
61 $ar - array ref containing the following variables:
62 pid : project id such as ckpt, owb, dba, etc.
63 task : task name required such as task1,task2,etc.
64 target(sel_sn1) : select one (DB/server name) defining sid
65 args(sel_sn2) : select two (Arguments)
66 task_fn : task file name containing all the tasks defined
67 svr_conn : host/server connection info
68 db_conn : db connection info for each target/server
69 task_conn : special connection for tasks.
70 It overwrites db_conn for the task
71 HA_* : hash array
72  
73 Variables used or routines called:
74  
75 None
76  
77 How to use:
78  
79 First define the parameters in the initial file or define all the parameters
80 in a hash array reference as $ar->{$p} where $p are
81 #
82 # parameters in initial file
83 pid = ckpt
84 task = task2
85 target = owb1
86 args = val1:val2
87 task_fn = ora_jobs.txt
88 outdir = /opt/www/logs
89 excl_callsql = run_xmlrpt|run_genrpt # tasks excluded from calling call_plsql
90 svr_conn = { # server connection
91 usr => 'usr_name',
92 pwd => 'security',
93 svr => 'svr_name',
94 orahome => '/opt/app/oracle/product/10.2.0/db_1',
95 }
96 db_conn = {
97 tgt1 => 'system/pwd@dbl_1',
98 tgt2 => 'system/pwd@dbl_2',
99 }
100 task_conn = {
101 tgt1 => { task1 => 'owb_rep2/pwd@owb1', },
102 tgt2 => { },
103 }
104 out_dir = { # overwrite general out_dir
105 ckpt => 'd:/www/logs/ckpt/rpts',
106 owb1 => '/opt/www/logs/owb1/rpts',
107 }
108 arg_required = {
109 task1 => 'obj_name',
110 }
111 svr_allowed = {
112 task1 => {cdx1=>1},
113 }
114 task_sql = {
115 task5 => 'chkts.sql',
116 task8 => 'owb/owbcollect_exit.sql',
117 }
118  
119
120 #
121 # Tasks defined in task file (task_fn)
122 task1 = # staigth SQL statement example
123 ALTER session SET nls_date_format='YYYYMMDD.HH24MISS';
124 SET linesize 999 serveroutput ON SIZE 1000000 FORMAT WRAPPED;
125 PROMPT <b> Get instance status </b>;
126 PROMPT <hr>;
127 COL host_name FOR a25;
128 COL up_days FOR 9999.99;
129 SELECT a.*, sysdate-startup_time as up_days FROM v\$instance a;
130 task2 = #
131  
132 my ($q, $ar, $ar_log) = $self->start_app($0, \@ARGV);
133 or
134 my $ar = $self->read_init_file('/tmp/my_init.cfg');
135 $self->exec_plsql($q, $ar);
136  
137 You can use variables in the definition file. We have provided a list of
138 pre-defined variables such as
139  
140 $a0~$a9 = arguments in sel_sn2 separated by colon (:)
141 $sid = <db_id_or_svr_id> ($sn)
142 $dtm = <date_and_time> ("%Y%m%d_%H%M%S")
143 $dt = <date> ("%Y%m%d")
144 $tm = <time> ("%H%M%S")
145 $y4 = <four_digit_year> ("%Y")
146 $mm = <month> ("%m")
147 $dd = <date> ("%d")
148 $hh = <hour> ("%H")
149 $mi = <minute> ("%M")
150 $ss = <second> ("%S")
151  
152 Return: $pr will contain the parameters adn output from running the PL/SQL.
153  
154 plsql_out - output from running the PL/SQL
155 is_callsql - whether to run call_plsql
156  
157 =cut
158  
159 sub exec_plsql {
160 my ($s, $q, $ar) = @_;
161  
162 # print $s->disp_form($q, $ar);
163 print $s->disp_header($q, $ar);
164  
165 my @c0 = caller(0); my @c1 = caller(1);
166 my $cls = (exists $c1[3]) ? $c1[3] : '';
167 my $prg = "$cls [$c0[2]] -> $c0[3]";
168
169 # 1. check required parameters
170 $s->echo_msg("1. checking required parameters...", 2);
171 my $vs = 'pid,task,task_fn,svr_conn,db_conn';
172 foreach my $t (split /,/, $vs) {
173 if (! exists $ar->{$t}) {
174 $s->echo_msg("ERR($prg): Parameter $t does not exist.",0); return;
175 }
176 }
177 my $pr = $s->def_inputvars($ar);
178 my $sn = $pr->{sid}; # sel_sn1 or target
179 my $pid = $ar->{pid}; # project id
180 my $tsk = lc $ar->{task}; # task name
181 my $ds = $pr->{ds}; # directory separator
182 my ($m) = ();
183 my $avs = 'svr_conn,db_conn,task_conn,out_dir,arg_required,svr_allowed';
184 $avs .= ',task_sql';
185 foreach my $t (split /,/, $avs) {
186 if ($t eq $tsk) {
187 $m = "ERR($prg): you could not use a preserved word to name your ";
188 $m .= "task - $tsk";
189 $s->echo_msg($m, 0); return;
190 }
191 }
192
193 # 2. read the task files
194 $s->echo_msg("2. reading task file...", 2);
195 my ($fn,$tsk_txt,$tsk_fn,$tsq) = ();
196 my $p = {};
197 my $tfn = $s->set_param('task_fn', $ar); # task file name:jp2.txt
198 my $ifn = $s->set_param('ifn', $ar); # parent init file name
199 my $tmp = $ifn; $tmp =~ s/\.(\w+)//;
200 my $tf2 = join $ds, $tmp, $pid, "$tsk.txt"; # task file name: jp2/ckpt/tsk1.txt
201 $ar->{ifn_dir} = $tmp; # init file dir
202 if (-f $tfn) {
203 $s->echo_msg("INFO: ($prg) reading $tfn...", 3);
204 $p = $s->read_init_file($tfn);
205 $tsk_txt = (exists $p->{$tsk}) ? $p->{$tsk} : "";
206 $s->echo_msg("INFO: ($prg) did not find $tsk in $tfn.", 3) if !$tsk_txt;
207 } else {
208 $s->echo_msg("INFO: ($prg) did not $tfn.", 3);
209 }
210 if (!$tsk_txt) {
211 if (-f $tf2) {
212 $s->echo_msg("INFO: ($prg) reading $tf2...", 3);
213 $p = $s->read_init_file($tf2);
214 $tsk_txt= (exists $p->{$tsk}) ? $p->{$tsk} : "";
215 $s->echo_msg("INFO: ($prg) did not find $tsk in $tf2.", 3) if !$tsk_txt;
216 } else {
217 $s->echo_msg("INFO: ($prg) did not find $tf2.", 3);
218 }
219 }
220 if (!$tsk_txt) { # look it in task_sql
221 if (! exists $ar->{task_sql}) {
222 $s->echo_msg("ERR: ($prg) no task sql is defined for $tsk.", 0); return;
223 }
224 $tsq = eval $ar->{task_sql};
225 if (! exists $tsq->{$tsk}) {
226 $s->echo_msg("ERR: ($prg) no task is defined in task sql for $tsk.", 0); return;
227 }
228 $tsk_fn = $tsq->{$tsk};
229 $p->{is_tasksql} = 1; # in sql file
230 } else {
231 $p->{is_tasksql} = 0; # in sql code
232 }
233  
234 # 3. explode parameters
235 $s->echo_msg("3. exploding parameters...", 2);
236 foreach my $t (split /,/, $avs) {
237 $ar->{$t} = $s->expand_vars($ar->{$t}, $pr);
238 }
239 # my $opf = eval $s->set_param('opf_labels', $ar); # DB names
240 my $scn = eval $s->set_param('svr_conn', $ar); # Server connections
241 my $dbc = eval $s->set_param('db_conn', $ar); # DB connections
242 my $amr = eval $s->set_param('arg_required', $ar); # ARG is required
243  
244 # my $tcn = {}; # Task connections
245 # $tcn = eval $ar->{task_conn}
246 # if exists $ar->{task_conn} && $ar->{task_conn};
247 # my $odr = {}; # Out dir
248 # $odr = eval $s->set_param('out_dir', $ar)
249 # if exists $ar->{out_dir} && $ar->{out_dir};
250 # $s->disp_param($ar);
251 # print "AMR: $amr<br>\n";
252 # print "ODR: $odr, $odr->{$sn}{db}, $odr->{$sn}{web}<br>\n";
253 # print "TCN: $tcn<br>\n";
254 # print "DBC: $dbc<br>\n";
255 # set outdir
256 # if (exists $odr->{$sn}) {
257 # $pr->{db_outdir} = $odr->{$sn}{db};
258 # $pr->{web_outdir} = $odr->{$sn}{web};
259 # } else {
260 # $pr->{db_outdir} = $ar->{outdir} if exists $ar->{outdir};
261 # $pr->{web_outdir} = $ar->{outdir} if exists $ar->{outdir};
262 # }
263 if (! exists $pr->{web_outdir}) {
264 $s->echo_msg("ERR: out_dir was not defined.", 0); return;
265 }
266 # $pr->{tgt_dir} = join $ds, $pr->{web_outdir}, $sn, $tsk;
267 # $pr->{log_dir} = join $ds, $pr->{tgt_dir}, $pr->{y4}, $pr->{mm};
268 # $pr->{sql_fn} = join $ds, $pr->{log_dir}, "s$pr->{dtm}.sql";
269 # set db connection
270 my $cs = $pr->{cs};
271 if (!$cs) {
272 $s->echo_msg("ERR: ($prg) db connection was not defined.", 0); return;
273 }
274 my $cr = {}; # code array ref
275 if ($ar->{preload_code} && !$p->{is_tasksql}) {
276 $cr->{plsql_dir} = $ar->{plsql_dir} if exists $ar->{plsql_dir};
277 $cr->{plsql_dir} = $ar->{ifn_dir} if !$cr->{plsql_dir};
278 my $pdr = $cr->{plsql_dir};
279 $s->echo_msg("INFO: ($prg) loading codes from $pdr...", 3);
280 if (-d $pdr) {
281 opendir DD, "$pdr" or croak "ERR: could not opendir - $pdr: $!\n";
282 my @a = sort grep !/\.bak$/, (grep !/^\./, readdir DD);
283 # map { $s->read_plsql("$pdr/$_",$cr); } sort grep !/\.bak$/, (grep !/^\./, readdir DD);
284 closedir DD;
285 for my $x (0..$#a) { my $f = $a[$x];
286 $s->read_plsql("$pdr/$f",$cr); }
287 $s->echo_msg($cr,9);
288 } else {
289 $s->echo_msg("ERR: ($prg) could not find plsql code dir - $pdr", 0);
290 }
291 }
292 ($pr->{mtr_sch}) = ($cs =~ /^(\w+)\//); # db schema
293 if (!$p->{is_tasksql}) {
294 # $txt =~ s/,\s*/,\n/g;
295 $tsk_txt =~ s/;\s*/;\n/g; # add line break back
296 $tsk_txt =~ s/(declare|begin)/$1\n/ig; # add line break
297 $tsk_txt = $s->expand_vars($tsk_txt, $pr); # expand param variables
298 $tsk_txt = $s->expand_vars($tsk_txt, $ar); # expand param variables
299 $tsk_txt =~ s/(\'?\$a\d+\'?)/null/g; # nullify the missing $a1,$a2,
300 $tsk_txt =~ s{\/\;\s*}{\/\n}g; # remove ; for /;
301 $tsk_txt =~ s/(\s*,\s*\w+\s*=>)/\n $1/ig; # add line break
302 $tsk_txt =~ s/\s+(where|order by|group by)/\n $1/ig; # add line break
303 $tsk_txt =~ s/(union all|union)/\n$1\n/ig; # add line break
304 $s->echo_msg("TXT: <pre>\n$tsk_txt\n</pre>",3);
305 }
306  
307 # 4. set output directories
308 $s->echo_msg("4. setting output directories...", 2);
309 # mkdir $pr->{out_dir}, 0777 if (! -d $pr->{out_dir});
310 # mkdir $pr->{tgt_dir}, 0777 if (! -d $pr->{tgt_dir});
311 if (! -d $pr->{log_dir}) {
312 eval { mkpath($pr->{log_dir},0,0777) };
313 croak "ERR: could not mkdir - $pr->{log_dir}: $!: $@<br>\n" if ($@);
314 if ($^O !~ /^MSWin/i) { # non window
315 system("chmod -R ugo+w $pr->{log_dir}");
316 }
317 }
318 my $radr = $ENV{REMOTE_ADDR}; $radr =~ s/\./_/g;
319 my $tmpd = join $ds,$pr->{web_outdir},$sn,$radr,$pr->{y4},$pr->{mm},$pr->{dd};
320 if (! -d $tmpd && ! $pr->{is_tasksql}) {
321 eval { mkpath($tmpd,0,0777) };
322 croak "ERR: could not mkdir - $tmpd: $!: $@<br>\n" if ($@);
323 if ($^O !~ /^MSWin/i) { # non window
324 system("chmod -R ugo+w $tmpd");
325 }
326 }
327 my $tpf1 = join $ds, $tmpd, "${tsk}_$pr->{tm}.sql";
328  
329 # 5. compose command
330 $s->echo_msg("5. composing commands...", 2);
331 my $rc = {'0'=>'OK', '1'=>'Command is not invoked', '2'=>'Failed'};
332 my ($svr,$usr,$pwd,$ohm) = ();
333 my $vhm = 'ORACLE_HOME';
334 $ohm = $ENV{$vhm} if exists $ENV{$vhm} && $ENV{$vhm};
335 $ohm = $scn->{orahome} if !$ohm && exists $scn->{orahome};
336 $svr = $scn->{svr} if exists $scn->{svr};
337 $usr = $scn->{usr} if exists $scn->{usr};
338 $pwd = $scn->{pwd} if exists $scn->{pwd};
339 # my ($svr,$usr,$pwd,$ohm) =
340 # ($scn->{svr},$scn->{usr},$scn->{pwd},$scn->{orahome});
341  
342 my $cfn = join $ds, $ohm, 'bin', 'sqlplus'; # command file name
343 $cfn .= ".exe" if ($^O =~ /^MSWin/i);
344 $s->echo_msg("INFO: ($prg) CFN set to $cfn", 2);
345 # if (! -f $cfn) {
346 # $s->echo_msg("ERR: could not find - $cfn", 0); return;
347 # }
348 $pr->{sql_cfn} = $cfn; # command file name
349 $pr->{sql_cs} = $cs; # connection string
350 # keep the variables
351 $ar->{sql_cfn} = $cfn; # command file name
352 $ar->{sql_cs} = $cs; # connection string
353 $s->echo_msg($pr, 4);
354 my ($r1, @a) = ();
355 if ($^O !~ /^MSWin/i) { # non window
356 ($r1, @a) = rexec($svr, 'ls -l $cfn', $usr, $pwd);
357 $s->echo_msg("INFO: ($prg) R1: $r1 - $rc->{$r1}", 3); $s->echo_msg(\@a,3);
358 if ($r1 > 0) {
359 $s->echo_msg("ERR: ($prg) could not run command - $cfn: $!.", 0);
360 return;
361 }
362 }
363 my $cmd;
364 if ($^O !~ /^MSWin/i) { # non window
365 $cmd = "ORACLE_HOME=$ohm;\nexport ORACLE_HOME;\n";
366 } else { # window
367 $cmd = '';
368 }
369 if ($p->{is_tasksql}) {
370 $cmd .= "$cfn -S $cs \@$tsk_fn";
371 } else {
372 $s->echo_msg("TXT: <pre>\n$tsk_txt\n</pre>",3);
373 $s->echo_msg("INFO: ($prg) Writing SQL to $tpf1...",2);
374 open TMPSQL,">$tpf1" or carp "ERR: could not write to $tpf1: $!\n";
375 print TMPSQL "$tsk_txt\nexit;\n";
376 close TMPSQL;
377 if ($cr) {
378 $s->expand_code($tpf1, $cr); # expand code variables
379 $s->expand_code($tpf1, $cr); # expand code variables
380 $s->expand_code($tpf1, $cr); # expand code variables
381 }
382 $cmd .= "$cfn -S $cs \@$tpf1";
383 croak "ERR: did not find sql file - $tpf1<br>\n" if ! -f $tpf1;
384 }
385 my $cmd2 = $cmd; $cmd2 =~ s/\</&lt;/g;
386 $s->echo_msg("CMD: <pre>\n$cmd2\n</pre>",2);
387  
388  
389 # 6. Execute the command
390 $s->echo_msg("6. executing the command...", 2);
391 # $s->echo_msg(" $p->{$tsk}",2);
392 # if ($^O !~ /^MSWin/i) { # non window
393 # ($r1, @a) = rexec($svr, $cmd, $usr, $pwd);
394 # } else {
395 $s->echo_msg("INFO: ($prg) set ORACLE_HOME=$ohm and PATH=$ohm/bin",3);
396 $ENV{ORACLE_HOME}=$ohm;
397 $ENV{PATH}="$ohm/bin";
398 open SQL, "$cmd|" or croak "ERR: could not run $cmd: $!<br>\n";
399 @a = <SQL>; close SQL;
400 # }
401 $pr->{plsql_out} = \@a;
402 $pr->{is_callsql} = 1;
403 $pr->{is_callsql} = 0 if (!$pr || ! exists $pr->{a0});
404 $pr->{is_callsql} = 0 if (exists $ar->{excl_callsql} &&
405 $tsk =~ /^($ar->{excl_callsql})/i);
406 $s->echo_msg("INFO: ($prg) output lines: $#a.", 3);
407 if ($s->debug > 4) { for my $i (0..$#a) { print "$i: $a[$i]<br>\n"; } }
408 # print "<pre><tt>\n@a\n</tt></pre>\n";
409
410 # get data records in the display and assign them into $ar
411 my $rr = $s->parse_record2(\@a, undef, '==',',');
412 foreach my $k (keys %{$rr->[0]}) { $ar->{$k} = $rr->[0]{$k}; }
413 # $s->set_cookies($q, $ar) if ($tsk =~ /^run_login/i);
414 $ar->{_sql_output} = \@a;
415 if ($tsk && $tsk =~ /^(run_login|run_logout)/i) {
416 my $u_vs = 'user_sid,user_uid,user_tmo';
417 my ($u_sid,$u_uid,$u_tmo) = $s->get_params($u_vs,$ar);
418 $u_sid = ($u_sid) ? $u_sid : '';
419 $u_uid = ($u_uid) ? $u_uid : '';
420 $u_tmo = ($u_tmo) ? $u_tmo : '';
421 $ar->{guid} = "$u_sid:$u_uid:$u_tmo";
422 $s->disp_index($q, $ar);
423 } else {
424 print "<pre>\n@a\n</pre>\n";
425 }
426  
427 # $s->echo_msg(\@a,0);
428  
429 wantarray ? %$pr : $pr;
430
431 # $s->call_plsql(\@a, $ar);
432  
433 }
434  
435 sub call_plsql {
436 my ($s, $rr, $ar) = @_;
437
438 my @c0 = caller(0); my @c1 = caller(1);
439 my $cls = (exists $c1[3]) ? $c1[3] : '';
440 my $prg = "$cls [$c0[2]] -> $c0[3]";
441  
442 my $vs = 'dir_sep,sql_cfn,sql_cs';
443 my ($ds,$cfn,$cs) = $s->get_params($vs, $ar);
444 my $scn = eval $s->set_param('svr_conn', $ar); # Server connections
445 my $dbc = eval $s->set_param('db_conn', $ar); # DB connections
446 my ($svr,$usr,$pwd,$ohm) = ();
447 $ohm = $ar->{ohm} if exists $ar->{ohm};
448 $ohm = $scn->{orahome} if !$ohm && exists $scn->{orahome};
449 # my $vhm = 'ORACLE_HOME';
450 # $ohm = $ENV{$vhm} if exists $ENV{$vhm} && $ENV{$vhm};
451 $svr = $scn->{svr} if exists $scn->{svr};
452 $usr = $scn->{usr} if exists $scn->{usr};
453 $pwd = $scn->{pwd} if exists $scn->{pwd};
454
455 my $sn = $ar->{sid};
456 $sn = $ar->{sel_sn1} if !$sn;
457 $ds = '/' if !$ds;
458 $cs = $dbc->{$sn} if !$cs;
459 if (!$cfn) {
460 if ($^O !~ /^MSWin/i) {
461 $cfn = join $ds, $ohm, 'bin', 'sqlplus';
462 } else {
463 $cfn = join $ds, $ohm, 'bin', 'sqlplus.exe';
464 }
465 }
466 if (! -f $cfn) {
467 $s->echo_msg("ERR: ($prg) could not find sqlplus program - $cfn.", 0);
468 return;
469 }
470 if (!$cs) {
471 $s->echo_msg("ERR: ($prg) no db connect string.", 0);
472 return;
473 }
474 $s->echo_msg("INFO: ($prg) CFN set to $cfn.", 2);
475 #
476 # get a list of PL/SQL files
477 my ($f1, $d1, $r1) = ("","",""); # PL/SQL file name and folder name
478 # File - vw_acorda_stg_co.sql was written to /opt/ora/ufd/owbprod.
479 # N:\Client\owb_dir\owbprod
480 my @a = (); my @b = ();
481 my $re = qr/[\w\/\.\:\\\-\[\]\$]+/;
482 foreach my $i (0..$#$rr) {
483 my $rec = $rr->[$i];
484 if ($rec =~ m/^\s*File was spooled to ($re)/) {
485 push @b, $1;
486 } elsif ($rec =~ m/^\s*File - ([\w\.\-\$]+)\s* was written to ($re)/) {
487 ($f1, $d1) = ($1, $2); push @b, (join $ds, $d1, $f1);
488 }
489 }
490 if ($#b < 0) {
491 $s->echo_msg("WARN: ($prg) did not find any sql file.", 2);
492 return;
493 } else {
494 $s->echo_msg("INFO: $#b SQL files will be executed.", 2);
495 }
496 #
497 # loop through each PL/SQL file
498 my ($cmd, $cmd2) = ();
499 my $r = [];
500 foreach my $f (@b) {
501 if (! -f $f) {
502 $s->echo_msg("ERR: ($prg) could not find sql file - $f.",0);
503 next;
504 }
505 push @$r, $f;
506 my $f2 = "$f.tmp";
507 $s->copy_file($f, $f2, "exit");
508 # $s->disp_file($f2);
509 if ($^O !~ /^MSWin/i) {
510 $cmd = "ORACLE_HOME=$ohm;\nexport ORACLE_HOME;\n";
511 } else {
512 # $cmd = "set ORACLE_HOME=$ohm;\n";
513 $s->echo_msg("INFO: ($prg) set ORACLE_HOME=$ohm and PATH=$ohm/bin",3);
514 $ENV{ORACLE_HOME}=$ohm;
515 $ENV{PATH}="$ohm/bin";
516 $cmd = '';
517 }
518 $cmd .= "$cfn -S $cs \@$f2";
519  
520 $cmd2 = $cmd; $cmd2 =~ s/\</&lt;/g;
521 $s->echo_msg("CMD: <pre>\n$cmd2\n</pre>",1);
522 # if ($^O !~ /^MSWin/i) {
523 # ($r1, @a) = rexec($svr, $cmd, $usr, $pwd);
524 # } else {
525 open SQL, "$cmd|" or croak "ERR: ($prg) could not run $cmd: $!<br>\n";
526 @a = <SQL>; close SQL;
527 # }
528 print "<pre>\n";
529 my $ofn = $f; $ofn =~ s/\.(\w+)$/\.txt/;
530 push @$r, $ofn;
531 open OFN, ">$ofn" or
532 croak "ERR: ($prg) could not write to $ofn: $!<br>\n";
533 foreach my $i (@a) {
534 next if $i =~ /^\s*$/;
535 # $s->echo_msg($i,0);
536 print OFN $i;
537 }
538 close OFN;
539 print "</pre>\n";
540 unlink $f2;
541 }
542 wantarray ? @$r : $r;
543 }
544  
545  
546 sub expand_vars {
547 my ($s, $v, $hr) = @_;
548 return if !$v || $v =~ /^\s*$/;
549  
550 # Case 1: $plsql->echo
551 my @n = ( $v =~ /(\$\w+\-\>\w+)/g );
552 $s->echo_msg("INFO: expand_vars N1: @n<br>", 3) if @n;
553 foreach my $x (@n) {
554 my ($a, $b) = ( $x =~ /\$(\w+)\-\>(\w+)/g );
555 $s->echo_msg("INFO: (a,b) = ($a,$b)<br>", 3);
556 if (! exists $hr->{$b} && $a =~ /^plsql/i) {
557 $s->read_plsql("$b.sql",$hr); # read the plsql code
558 }
559 $v =~ s#\$$a\-\>$b\s*\;#$hr->{$b}# if exists $hr->{$b};
560 carp " No code for \$$a\-\>{$b}." if ! exists $hr->{$b};
561 };
562
563 # Case 2: $ar->{ifn}
564 @n = ( $v =~ /(\$\w+\-\>\{\w+\})/g );
565 $s->echo_msg("INFO: expand_vars N2: @n<br>",3) if @n;
566 foreach my $x (@n) {
567 my ($a, $b) = ( $x =~ /\$(\w+)\-\>\{(\w+)\}/g );
568 $s->echo_msg("INFO: (a,b) = ($a,$b)<br>",3);
569 $v =~ s#\$$a\-\>\{$b\}#$$a->{$b}# if exists $$a->{$b};
570 };
571  
572 # Case 3: $hr{param}
573 @n = ( $v =~ /(\$\w+\{\w+\})/g );
574 $s->echo_msg("INFO: expand_vars N3: @n<br>",3) if @n;
575 foreach my $x (@n) {
576 my ($a, $b) = ( $x =~ /\$(\w+)\{(\w+)\}/g );
577 $s->echo_msg("INFO: (a,b) = ($a,$b)<br>",3);
578 $v =~ s#\$$a\{$b\}#$$a->{$b}# if exists $$a->{$b};
579 };
580  
581 # Case 4: $v1, $v2
582 my @m = ( $v =~ /[^\\](\$\w+)\s*/g ); # matched variables
583 $s->echo_msg("INFO: expand_vars M: @m<br>",3) if @m;
584 return $v if (!@m);
585 foreach my $x (@m) {
586 my $y = $x; $y =~ s/^\$//;
587 $v =~ s{\$$y}{$hr->{$y}} if exists $hr->{$y};
588 }
589 return $v;
590 }
591  
592 sub expand_code {
593 my ($s, $fn, $hr) = @_;
594 return if !$fn || $fn =~ /^\s*$/;
595 croak "ERR: could not find file - $fn: $!\n" if ! -f $fn;
596
597 open FF, "<$fn" or croak "ERR: could not read file - $fn: $!\n";
598 my @a = <FF>;
599 close FF;
600 open FF, ">$fn" or croak "ERR: could not write to file - $fn: $!\n";
601 foreach my $v (@a) {
602 # Case 1: $plsql->echo
603 if ($v =~ m/(\$\w+\-\>\w+)/g ) {
604 my $x = $1;
605 $s->echo_msg("INFO: expand_code : $x<br>", 3);
606 my ($a, $b) = ( $x =~ /\$(\w+)\-\>(\w+)/g );
607 $s->echo_msg("INFO: (a,b) = ($a,$b)<br>", 3);
608 $s->read_plsql("$b.sql",$hr) if (! exists $hr->{$b} && $a =~ /^plsql/i);
609 if (exists $hr->{$b}) {
610 print FF "\n$hr->{$b}\n";
611 } else {
612 $s->echo_msg("INFO: No code for \$$a\-\>{$b}.",1);
613 print FF " -- $v # sorry, no code";
614 }
615 } else {
616 print FF $v;
617 }
618 }
619 close FF;
620 }
621  
622 =head2 read_plsql($fn, $pr)
623  
624 Input variables:
625  
626 $fn - full path to a file name
627 $pr - parameter array
628 plsql_dir - directory where plsql files reside
629  
630 Variables used or routines called:
631  
632 CGI::AppBuilder::Message
633 echo_msg - echo messages
634  
635 How to use:
636  
637 my $pr = $self->read_plsql('code_lib.ini');
638  
639 Return: Hash array or ref of hash array - $pr
640  
641 This method reads PL/SQL code files containing functions and procedures
642 in the format of key=values. Multiple lines is allowed for values as long
643 as the lines after the "key=" line are indented as least with two
644 blanks. For instance:
645  
646 echo = procedure each ( msg clob, lvl NUMBER DEFAULT 999 ) IS
647 BEGIN
648 IF lvl <= p_lvl THEN dbms_output.put_line(msg); END IF;
649 END;
650  
651 # you can define perl hash araay as well
652 msg = {
653 101 => "msg 101",
654 102 => "msg 102"
655 }
656 # you can use variable as well
657 js_var = /my/js/var_file.js
658 js_src = /my/first/js/prg.js,$js_var
659 # a comma (,) after sharp (#) make it not a comment
660 my_sql = select sid, serial#,username from v\$session;
661 # you can use the ##include: to include more code files
662 ##include: /my/codes/function_lib.sql
663  
664 This will create a hash array of
665  
666 $pr->{echo} = proc ... end;
667 $pr->{desc} = "This is a long description about the value"
668 $pr->{msg} = {101=>"msg 101",102=>"msg 102"}
669 $pr->{js_var}= "/my/js/var_file.js";
670 $pr->{js_src}= "/my/first/js/prg.js,/my/js/var_file.js";
671  
672 =cut
673  
674 sub read_plsql {
675 my $s = shift;
676 my ($fn, $pr) = @_;
677 if (!$fn) { carp " No file name is specified."; return; }
678 if (! $pr || ! exists $pr->{plsql_dir}) {
679 carp " No plsql directory is specified."; return;
680 }
681 # if file name does not have full path, we use plsql_dir
682 $fn = join '/', $pr->{plsql_dir}, $fn if index($fn,'/') < 0;
683 if (!-f $fn) { carp " File - $fn does not exist!"; return; }
684 $s->echo_msg(" reading plsql code file - $fn...",2);
685
686 my ($k, $v, %h);
687 open FILE, "< $fn" or
688 croak "ERR: could not read to file - $fn: $!\n";
689 while (<FILE>) {
690 # 07/21/2010 (htu): enable included files
691 if ($_ =~ /^\s*##include:\s*([\w\.\/]+)/i) {
692 # we find a included file
693 my $f2 = $1;
694 if (! -f $f2) {
695 $s->echo_msg("WARN: could not find included file - $f2",1);
696 next;
697 } else {
698 $s->echo_msg("INFO: reading sub init file - $f2...",1);
699 }
700 # print "INFO (read_plsql): reading sub init file - $f2...<br>";
701 ($k,$v) = ();
702 open F2, "< $f2" or
703 croak "ERR: could not read file - $f2: $!\n";
704 while (<F2>) {
705 next if $_ =~ /^\s*#/ || $_ =~ /^\s*$/;
706 chomp; # remove line break
707 my ($x, $y) = $s->_parseline2($_);
708 $k = $x if $x; $v = $y ;
709 if ($x) { $h{$k} = $v; } else { $h{$k} .= " $v"; }
710 }
711 close F2;
712 next;
713 }
714 # skip comment and empty lines
715 next if $_ =~ /^\s*#/ || $_ =~ /^\s*$/;
716 chomp; # remove line break
717 my ($x, $y) = $s->_parseline2($_);
718 $k = $x if $x; $v = $y ;
719 if ($x) { $h{$k} = $v; } else { $h{$k} .= " $v"; }
720 }
721 close FILE;
722 foreach my $k (keys %h) {
723 $h{$k} =~ s/;\s*/;\n/g; # add line break back
724 $h{$k} =~ s/(declare|begin|then|else)/$1\n /ig; # add line break
725 $h{$k} =~ s/(\>\>)/$1\n /ig; # add line break
726 $h{$k} =~ s/(\)\s*IS)/\n$1\n /ig; # add line break
727 $h{$k} =~ s/[^']?(from|where|order by|group by)/\n $1/ig; # add line break
728 $h{$k} =~ s/(\s*,\s*\w+\s*=>)/\n $1/ig; # add line break
729 $h{$k} =~ s/(,\s*\w+\s*(varchar|number|integer|date))/\n $1/ig; # add line break
730 }
731 if (ref($pr) =~ /^HASH/) {
732 foreach my $k (keys %h) { $pr->{$k} = $h{$k}; }
733 } else { $pr = \%h; }
734 return wantarray ? %$pr : $pr;
735 }
736  
737 sub _parseline2 {
738 my ($s, $rec) = @_;
739 my ($k, $v) = ();
740 if ($rec =~ /^(\w+)\s*=\s*(.+)/) {
741 $k = $1; $v = $2;
742 } elsif ($rec =~ /\s*(\w+)\s*=>\s*(.+)/) { # k1 => v1
743 $k = ''; $v = $rec;
744 } else {
745 $k = ''; $v = $rec;
746 }
747 $v =~ s/^\s+//; $v =~ s/\s+$//; # remove leading and trailing spaces
748 $v =~ s/\s*[^'"\(]#[^'",\)].*$//; # remove inline comments
749 $v =~ s/\s*[^'"\(]?--.*$//; # remove plsql inline comments
750 return ($k,$v);
751 }
752  
753  
754 1;
755  
756 =head1 HISTORY
757  
758 =over 4
759  
760 =item * Version 0.10
761  
762 This version ported from ora_jobs.pl on 07/17/2010.
763  
764 =item * Version 0.20
765  
766 08/12/2010 (htu):
767 1. added read_plsql, _parseline2
768 2. modified expand_vars to use read_plsql
769 3. modified exec_plsql to preload codes if the preload_code = 1
770  
771 =cut
772  
773 =head1 SEE ALSO (some of docs that I check often)
774  
775 Oracle::Loader, Oracle::Trigger, CGI::AppBuilder, File::Xcopy,
776 CGI::AppBuilder::Message
777  
778 =head1 AUTHOR
779  
780 Copyright (c) 2009 Hanming Tu. All rights reserved.
781  
782 This package is free software and is provided "as is" without express
783 or implied warranty. It may be used, redistributed and/or modified
784 under the terms of the Perl Artistic License (see
785 http://www.perl.com/perl/misc/Artistic.html)
786  
787 =cut
788