blib/lib/DDL.pm untested

filter: Statementstmt 0.0% 0 / 205 Branchbran 0.0% 0 / 96 Conditioncond 0.0% 0 / 54 MC/DCmcdc 0.0% 0 / 32 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 403 CC 49 SCAR 73.3
CC
49
Cov
0%
create_table
2070.0
add_primary_key
20.0
new
6.0
CRAP 1528.9
1 package Oracle::DDL;
2  
3 # Perl standard modules
4 use strict;
5 use warnings;
6 use Carp;
7 use DBI;
8 use Debug::EchoMessage;
9 use Oracle::DML::Common qw(:all);
10 use POSIX qw(strftime);
11  
12 require 5.003;
13 $Oracle::DDL::VERSION = 0.10;
14  
15 require Exporter;
16 our @ISA = qw(Exporter);
17 our @EXPORT = qw();
18 our @EXPORT_OK = qw( add_primary_key
19 create_table
20 );
21 our @IMPORT_OK = qw(
22 get_dbh is_object_exist
23 debug echoMSG disp_param
24 );
25 our %EXPORT_TAGS = (
26 all => [@EXPORT_OK],
27 all_ok=>[@EXPORT_OK,@IMPORT_OK],
28 );
29  
30 =head1 NAME
31  
32 Oracle::DDL - Perl class for Oracle batch DML
33  
34 =head1 SYNOPSIS
35  
36 use Oracle::DDL;
37  
38 my %cfg = ('conn_string'=>'usr/pwd@db', 'table_name'=>'my_ora_tab');
39 my $ot = Oracle::DDL->new;
40 # or combine the two together
41 my $ot = Oracle::DDL->new(%cfg);
42 my $sql= $ot->prepare(%cfg);
43 $ot->execute(); # actually create the audit table and trigger
44  
45  
46 =head1 DESCRIPTION
47  
48 This class contains methods to create audit tables and triggers for
49 Oracle tables.
50  
51 =cut
52  
53 =head2 Object Constructor
54  
55 =head3 new (%arg)
56  
57 Input variables:
58  
59 $cs - Oracle connection string in usr/pwd@db
60 $tn - Oracle table name without schema
61  
62 Variables used or routines called:
63  
64 None
65  
66 How to use:
67  
68 my $obj = new Oracle::DDL; # or
69 my $obj = Oracle::DDL->new; # or
70 my $cs = 'usr/pwd@db';
71 my $tn = 'my_table';
72 my $obj = Oracle::DDL->new(cs=>$cs,tn=>$tn); # or
73 my $obj = Oracle::DDL->new('cs',$cs, 'tn',$tn);
74  
75 Return: new empty or initialized Oracle::DDL object.
76  
77 =cut
78  
79 sub new {
80 my $caller = shift;
81 my $caller_is_obj = ref($caller);
82 my $class = $caller_is_obj || $caller;
83 my $self = bless {}, $class;
84 my %arg = @_; # convert rest of inputs into hash array
85 foreach my $k ( keys %arg ) {
86 if ($caller_is_obj) {
87 $self->{$k} = $caller->{$k};
88 } else {
89 $self->{$k} = $arg{$k};
90 }
91 }
92 return $self;
93 }
94  
95 =head1 METHODS
96  
97 The following are the common methods, routines, and functions
98 defined in this class.
99  
100 =head2 Exported Tag: All
101  
102 The I<:all> tag includes all the methods or sub-rountines
103 defined in this class.
104  
105 use Oracle::DDL qw(:all);
106  
107 =cut
108  
109 =head3 add_primary_key($dbh, $tab, $pk, $exe)
110  
111 Input variables:
112  
113 $dbh - database handler
114 $tab - table name
115 $pk - primary key column name
116 $exe - whether to execute the SQL statement
117 0 - No (default); 1- Yes.
118  
119 Variables used or routines called:
120  
121 echoMSG - display message
122  
123 How to use:
124  
125 $self->add_primary_key(4dbh, 'my_tab', 'id');
126  
127 Return: 0|1 - whether it is successful 0 - OK; 1 - failed
128  
129 =cut
130  
131 sub add_primary_key {
132 my $s = shift;
133 my ($dbh, $tab, $pk, $exe) = @_;
134 my $r = 0;
135 my $f1 = "ALTER TABLE %s \n";
136 $f1 .= " ADD (CONSTRAINT pk_%s_%s PRIMARY KEY (%s) )";
137 my $q1 = sprintf $f1, $tab, $tab, $pk, $pk;
138 my $s1 = $dbh->prepare($q1);
139 if (! $s1) {
140 print "ERR: Stmt - $dbh->errstr";
141 $r = 1;
142 }
143 if ($exe) {
144 if (!$s1->execute()) {
145 print "ERR: Stmt - $s1->errstr";
146 $r = 1;
147 }
148 }
149 return $r;
150 }
151  
152  
153 =head3 create_table($tab,$crf,$opt)
154  
155 Input variables:
156  
157 $tab - table name
158 $crf - array ref containing table definition as $crf->[$i]{$itm},
159 where $i is column number and $itm is col,typ,req,wid,dft,etc.
160 $opt - other table related options:
161 dbh - database handler
162 fn_sql - output file name for SQL codes
163 fn_log - log file name for spool off and default to
164 fn_sql with the extension replaced with .log
165 fh_sql - output file handler for SQL codes
166 action - whether to return SQL codes
167 SQL (default) - return array ref containing SQL codes
168 execute SQL codes if dbh is specified
169 TXT - return SQL codes in text and write SQL codes to
170 output file if fn_sql or fh_sql is specified.
171 ALL - return SQL codes and
172 write to output file if fn_sql or fh_sql is specified
173 execute SQL statements if dbh is specified
174 public_select - 1 or actual grant statement
175 drop_table - 1 - drop before creating it; 0 - not drop
176 relax_constraint - 0 - no; 1 - yes
177  
178 Variables used or routines called:
179  
180 echoMSG - display message
181  
182 How to use:
183  
184 my $cs = 'usr/pwd\@db';
185 my $dbh = get_dbh($cs);
186 my $fh = new IO::File "> myfile.sql";
187 my %opt = (dbh=>$dbh, fh_sql => $fh,action=>'txt');
188 my $crf = $self->read_tab_def('table.def', 'myTab',',');
189 my $sql = $self->create_table('myTab',${$crf}{mytab},\%opt);
190  
191 Return: the result of table creation or the SQL code for creating the
192 table.
193  
194 =cut
195  
196 sub create_table {
197 my $self = shift;
198 my($tab,$crf,$p) = @_;
199 croak "ERR: No table name is specified.\n" if ! $tab;
200 croak "ERR: No column def array.\n" if ! $crf;
201 croak "ERR: No column def is not a array.\n" if $crf !~ /ARRAY/;
202 $self->echoMSG("+++ [Oracle::DDL] Creating Table $tab +++",1);
203 my ($dbh,$drp,$act,$pbs,$fn,$fh,$flg,$rlx,$spo) = ();
204 if ($p && $p =~ /HASH/) {
205 $dbh = (exists $p->{dbh})?$p->{dbh}:'';
206 $drp = (exists $p->{drop_table})?$p->{drop_table}:1;
207 $drp = ($drp && $drp =~ /^(y|1)$/)?1:0;
208 $act = (exists $p->{action})?$p->{action}:'SQL';
209 $pbs = (exists $p->{public_select})?$p->{public_select}:0;
210 $fn = (exists $p->{fn_sql})?$p->{fn_sql}:'';
211 $flg = (exists $p->{fn_log})?$p->{fn_log}:'';
212 $fh = (exists $p->{fh_sql})?$p->{fh_sql}:'';
213 $rlx = (exists $p->{relax_constraint})?
214 $p->{relax_constraint}:0;
215 $spo = (exists $p->{spool_off})?$p->{spool_off}:'';
216 }
217 $self->echoMSG("ACT=$act;DBH=$dbh;DRP=$drp;PBS=$pbs", 3);
218 $self->echoMSG("FN=$fn;LOG=$flg;FH=$fh;RLX=$rlx", 3);
219 my $st = strftime "%Y%m%d.%H%M%S", localtime time;
220  
221 my $txt = ""; # text to be written to a file
222 my $sql = ""; # SQL codes
223 my @stm = (); # SQL statement
224 $txt .= "REM table $tab generated at $st\n";
225 if ($flg) {
226 $txt .= "set serveroutput on echo on\nspool $flg\n";
227 $txt .= "select to_char(sysdate, 'YYYY/MM/DD HH24:MI:SS') ";
228 $txt .= "\"Started at\" from dual;\n";
229 }
230 $txt .= "DROP TABLE $tab;\n" if $drp;
231 if ($drp && $dbh && $self->is_object_exist($dbh,$tab,'table')) {
232 push @stm, "DROP TABLE $tab" if $drp;
233 }
234 $txt .= "-- DROP TABLE $tab;\n" if !$drp;
235  
236 $sql .= "CREATE TABLE $tab (\n";
237  
238 my $fmt = " %-35s %-23s %12s\n";
239 my ($typ,$col,$wid,$dft,$req,$otp,$orq,$dec,$dsp);
240 for my $i (0..$#{$crf}) { # loop thru each column
241 $col = uc(${$crf}[$i]{'col'}); # column name
242 $col = "\"$col\"";
243 $typ = uc(${$crf}[$i]{'typ'}); # column type
244 if ($typ =~ /^N$/) { $typ = 'NUMBER'; }
245 if ($typ =~ /^D$/) { $typ = 'DATE'; }
246 if ($typ =~ /^C$/) { $typ = 'VARCHAR2'; }
247 $wid = "";
248 if (${$crf}[$i]{'wid'}) { # use 'wid' first
249 $wid = uc(${$crf}[$i]{'wid'}); # column width
250 }
251 if (!$wid) { # use 'max'
252 $wid = uc(${$crf}[$i]{'max'}); # column width
253 }
254 $dft = uc(${$crf}[$i]{'dft'}); # column type
255 $req = uc(${$crf}[$i]{'req'}); # requirement/constraint
256 $dec = uc(${$crf}[$i]{'dec'}); # decimal
257 $otp = ""; # Oracle type
258 # print "$col:$typ:$wid:$dec:$req\n";
259 if ($dec ne "" && $wid && $typ =~ /^N/i) {
260 if ($wid > $dec) { $wid .= ",$dec"; }
261 # print "--$col:$wid\n";
262 }
263 if ($wid && $typ !~ /^D/i) { $otp = "$typ($wid)";
264 } else { $otp = $typ; }
265 $orq="";
266 $orq = $req if $req && $typ !~ /^D/i &&
267 (! $rlx || $col =~ /(^ID|ID$)/);
268 if ($i == $#{$crf}) {
269 $sql .= sprintf $fmt, $col, $otp, $orq . ')';
270 # $sql .= $opt if ($opt);
271 } else {
272 $sql .= sprintf $fmt, $col, $otp, $orq . ',';
273 }
274 }
275 $txt .= "$sql;\n";
276 push @stm, $sql;
277 if ($pbs && $pbs == 1) {
278 $txt .= "GRANT SELECT ON $tab TO PUBLIC;\n";
279 push @stm, "GRANT SELECT ON $tab TO PUBLIC";
280 } elsif ($pbs) {
281 $txt .= $pbs;
282 push @stm, $pbs;
283 }
284 if (exists ${$crf}[0]{table_desc}) {
285 $dsp = ${$crf}[0]{table_desc};
286 $dsp =~ s/\'/ /g; # change single quote to blank
287 $dsp =~ s/\&/and/g; # change & sign to 'and'
288 $txt .= "COMMENT ON TABLE ${tab} IS\n '$dsp';\n";
289 push @stm, "COMMENT ON TABLE ${tab} IS\n '$dsp'";
290 }
291 # create comment for columns
292 for my $i (0..$#{$crf}) { # loop thru each column
293 $col = uc(${$crf}[$i]{'col'}); # column name
294 $dsp = ${$crf}[$i]{'dsp'}; # column description
295 $dsp =~ s/\'/ /g; # change single quote to blank
296 $dsp =~ s/\&/and/g; # change & sign to 'and'
297 next if !$dsp;
298 $txt .= "COMMENT ON COLUMN ${tab}.\"$col\" IS\n '$dsp';\n";
299 push @stm, "COMMENT ON COLUMN ${tab}.\"$col\" IS\n '$dsp'";
300 }
301 $txt .= "spool off\nexit\n" if $spo;
302 # action time...
303 return $txt if $act =~ /^TXT/i && !$fn && !$fh;
304 return \@stm if $act =~ /^SQL/i && !$dbh;
305 my $fh1 = "";
306 if ($fn) {
307 use IO::File;
308 $fh1 = new IO::File ">> $fn";
309 }
310 if ($act =~ /^(ALL|TXT)/i) {
311 print $fh $txt if $fh;
312 print $fh1 $txt if $fn;
313 $fh->close if $fh;
314 $fh1->close if $fn;
315 return $txt if $act =~ /^TXT/i;
316 }
317 if ($act =~ /^(ALL|SQL)/i && $dbh) {
318 for my $i (0..$#stm) {
319 my $q = "$stm[$i]\n";
320 my $s=$dbh->prepare($q)|| print "ERR: Stmt - $dbh->errstr";
321 $s->execute() || print "ERR: Stmt - $s->errstr";
322 }
323 }
324 return \@stm;
325 }
326  
327 1;
328  
329 =head1 HISTORY
330  
331 =over 4
332  
333 =item * Version 0.10
334  
335 This version is to test the concept.
336  
337 =item * Version 0.2
338  
339  
340 =cut
341  
342 =head1 SEE ALSO (some of docs that I check often)
343  
344 Oracle::Loader, Oracle::Trigger, Oracle::DML, Oracle::DML::Common,
345 CGI::Getopt, File::Xcopy
346  
347 =head1 AUTHOR
348  
349 Copyright (c) 2005 Hanming Tu. All rights reserved.
350  
351 This package is free software and is provided "as is" without express
352 or implied warranty. It may be used, redistributed and/or modified
353 under the terms of the Perl Artistic License (see
354 http://www.perl.com/perl/misc/Artistic.html)
355  
356 =cut
357