| 1 | package Oracle::SQL::Builder; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | |||
| 5 | # require Exporter; | ||
| 6 | # require DynaLoader; | ||
| 7 | # require AutoLoader; | ||
| 8 | use POSIX qw(strftime); | ||
| 9 | use Carp; | ||
| 10 | use warnings; | ||
| 11 | use DBI; | ||
| 12 | use Oracle::DML::Common qw(check_input_drf); | ||
| 13 | |||
| 14 | |||
| 15 | our @ISA = qw(Exporter DynaLoader); | ||
| 16 | # Items to export into callers namespace by default. Note: do not export | ||
| 17 | # names by default without a very good reason. Use EXPORT_OK instead. | ||
| 18 | # Do not simply export all your public functions/methods/constants. | ||
| 19 | our @EXPORT = qw( | ||
| 20 | |||
| 21 | ); | ||
| 22 | our @EXPORT_OK = qw( | ||
| 23 | form_sql genWhere split_cns run_sql | ||
| 24 | build_sql_stmt build_sql_value build_sql_operator build_sql_where | ||
| 25 | ); | ||
| 26 | our %EXPORT_TAGS = ( | ||
| 27 | sql => [qw(form_sql genWhere split_cns run_sql quote_keywords | ||
| 28 | )], | ||
| 29 | all => [@EXPORT_OK], | ||
| 30 | ); | ||
| 31 | our @IMPORT_OK = qw( | ||
| 32 | check_input_drf | ||
| 33 | ); | ||
| 34 | |||
| 35 | our $VERSION = '0.01'; | ||
| 36 | |||
| 37 | # bootstrap Oracle::SQL::Builder $VERSION; | ||
| 38 | |||
| 39 | =head1 NAME | ||
| 40 | |||
| 41 | Oracle::SQL::Builder - Perl extension for building SQL statements. | ||
| 42 | |||
| 43 | =head1 SYNOPSIS | ||
| 44 | |||
| 45 | use Oracle::SQL::Builder; | ||
| 46 | |||
| 47 | No automatically exported routines. You have to specifically to import | ||
| 48 | the methods into your package. | ||
| 49 | |||
| 50 | use Oracle::SQL::Builder qw(:sql); | ||
| 51 | use Oracle::SQL::Builder /:sql/; | ||
| 52 | use Oracle::SQL::Builder ':sql'; | ||
| 53 | |||
| 54 | =head1 DESCRIPTION | ||
| 55 | |||
| 56 | This is a package containing common sub routines that can be used in | ||
| 57 | other programs. | ||
| 58 | |||
| 59 | =cut | ||
| 60 | |||
| 61 | =head3 new (%arg) | ||
| 62 | |||
| 63 | Input variables: | ||
| 64 | |||
| 65 | any input variable and value pairs | ||
| 66 | |||
| 67 | Variables used or routines called: | ||
| 68 | |||
| 69 | None | ||
| 70 | |||
| 71 | How to use: | ||
| 72 | |||
| 73 | my $obj = new Oracle::SQL; # or | ||
| 74 | my $obj = Oracle::SQL->new; # or | ||
| 75 | |||
| 76 | Return: new empty or initialized Oracle::SQL object. | ||
| 77 | |||
| 78 | =cut | ||
| 79 | |||
| 80 | sub new { | ||
| 81 | my $caller = shift; | ||
| 82 | my $caller_is_obj = ref($caller); | ||
| 83 | my $class = $caller_is_obj || $caller; | ||
| 84 | my $self = bless {}, $class; | ||
| 85 | my %arg = @_; # convert rest of inputs into hash array | ||
| 86 | foreach my $k ( keys %arg ) { $self->{$k} = $arg{$k}; } | ||
| 87 | return $self; | ||
| 88 | } | ||
| 89 | |||
| 90 | # ------------------------------------------------------------------- | ||
| 91 | |||
| 92 | =head2 Export Tag: sql | ||
| 93 | |||
| 94 | The I<:table> tag includes sub-rountines for accessing Orable tables. | ||
| 95 | |||
| 96 | use Oracle::SQL::Builder qw(:sql); | ||
| 97 | |||
| 98 | It includes the following sub-routines: | ||
| 99 | |||
| 100 | =cut | ||
| 101 | |||
| 102 | =head3 build_sql_stmt($idn,$idv,$hrf,$dft,$acm) | ||
| 103 | |||
| 104 | Input variables: | ||
| 105 | |||
| 106 | $idn - id/key name | ||
| 107 | $idv - id/key value | ||
| 108 | $hrf - hash ref with column definition. It is from | ||
| 109 | getTableDef method | ||
| 110 | $dft - date format. Default to 'YYYYMMDD.HH24MISS' | ||
| 111 | $acm - add comma. If $acm = 1, then add a comma in | ||
| 112 | the end. | ||
| 113 | |||
| 114 | Variables used or routines called: | ||
| 115 | |||
| 116 | fmtTime - get current time | ||
| 117 | |||
| 118 | How to use: | ||
| 119 | |||
| 120 | my $cs = 'usr/pwd@db'; | ||
| 121 | my $dbh = $self->getDBHandler($cs, "Oracle"); | ||
| 122 | my $tab = "test_table"; | ||
| 123 | my ($cns,$cd1,$hrf) = $self->getTableDef($dbh,$tab,'*','hash'); | ||
| 124 | my $dft = 'YYYYMMDD.HH24MISS'; | ||
| 125 | my $v = $self->build_sql_stmt('dept',10,$hrf,$dft); | ||
| 126 | |||
| 127 | Return: value string to be used in SQL statement. | ||
| 128 | |||
| 129 | Any undef or 'null' value of $idv will be translated to '' for | ||
| 130 | insert_records method and 'null' for update_records so that the | ||
| 131 | DBI can handle correctly. | ||
| 132 | |||
| 133 | =cut | ||
| 134 | |||
| 135 | sub build_sql_stmt { | ||
| 136 | my $self = (ref $_[0]) ? shift : Oracle::SQL->new(@_); | ||
| 137 | my ($idn,$idv,$hrf,$dft,$acm) = @_; | ||
| 138 | # Input variables: | ||
| 139 | # $idn - id/key name | ||
| 140 | # $idv - id/key value | ||
| 141 | # $hrf - hash ref with column definition. It is from | ||
| 142 | # getTableDef method | ||
| 143 | # $dft - date format. Default to 'YYYYMMDD.HH24MISS' | ||
| 144 | # | ||
| 145 | carp "WARN: no input for id/key name in build_sql_stmt.\n" | ||
| 146 | if !$idn; | ||
| 147 | $idn = lc $idn; | ||
| 148 | $acm = 0 if !$acm; | ||
| 149 | my $s = ""; # return string | ||
| 150 | my $v = $idv; # id value | ||
| 151 | my $ddn1 = 'rec_crt_dt'; # small initial date | ||
| 152 | my $ddn2 = 'rec_upd_dt|last_update_dt|start_dt'; # current date | ||
| 153 | my ($pkg,$file,$line,$sub) = caller(1); | ||
| 154 | $sub =~ s/.*:://g; # remove class names | ||
| 155 | if (!defined($v) || $v =~ /^null$/i) { | ||
| 156 | $v = 'null'; # assign empty (= null) | ||
| 157 | if (${$hrf}{$idn}{req} =~ /^not null/i) { | ||
| 158 | $self->echoMSG(" Null in required col $idn", 5); | ||
| 159 | } | ||
| 160 | } | ||
| 161 | my $typ = ${$hrf}{$idn}{typ}; | ||
| 162 | my $req = ${$hrf}{$idn}{req}; | ||
| 163 | if ($typ =~ /^DATE/i) { # date datatype | ||
| 164 | my $dtv = $v; # date value | ||
| 165 | $dtv = '' if $v eq 'null'; | ||
| 166 | if ($v eq 'null' && $req =~ /^not null/i) { | ||
| 167 | # datetime in SQL server: 1/1/1753 ~ 12/31/9999 | ||
| 168 | if ($idn =~ /^($ddn1)/i) { | ||
| 169 | $dtv = '19980101.000000'; | ||
| 170 | } elsif ($idn =~ /^($ddn2)/i) { | ||
| 171 | $dtv = $self->fmtTime; | ||
| 172 | } else { | ||
| 173 | $dtv = '17530101.000000'; | ||
| 174 | } | ||
| 175 | } | ||
| 176 | if ($sub =~ /^(insert_)/i) { # called by insert_records sub | ||
| 177 | $s .= $dtv; # no to_date function | ||
| 178 | } else { # called by update_records sub | ||
| 179 | $s .= "TO_DATE('$dtv','$dft')"; | ||
| 180 | } | ||
| 181 | } elsif ($typ =~ /^(V|C)/i) { | ||
| 182 | $v =~ s/'/''/gm if $v; # escape the quote (') | ||
| 183 | if ($sub =~ /^(insert_)/i) { # called by insert_records sub | ||
| 184 | # if ($v eq 'null') { $s .= ''; } else { $s .= "'$v'"; } | ||
| 185 | if ($v eq 'null') { $s .= ''; } else { $s .= "$v"; } | ||
| 186 | } elsif ($sub =~ /^(update_)/i) { # called by update_records sub | ||
| 187 | if ($v eq 'null') { $s .= $v; } else { $s .= "'$v'"; } | ||
| 188 | } else { | ||
| 189 | # if ($v eq 'null') { $s .= $v; } else { $s .= "'$v'"; } | ||
| 190 | if ($v eq 'null') { $s .= $v; } else { $s .= "$v"; } | ||
| 191 | } | ||
| 192 | } else { # numeric datatype | ||
| 193 | if ($sub =~ /^(insert_)/i) { # called by insert_records sub | ||
| 194 | if ($v eq 'null') { $s .= ''; } else { $s .= $v; } | ||
| 195 | } elsif ($idn =~ /^(rowid)/i) { | ||
| 196 | $s .= "'$v'"; | ||
| 197 | } else { | ||
| 198 | $s .= $v; | ||
| 199 | } | ||
| 200 | } | ||
| 201 | $s = "$s," if $acm; | ||
| 202 | $self->echoMSG("$idn=$v; TYP=$typ; REQ=$req: $s<br>\n", 5); | ||
| 203 | return $s; | ||
| 204 | } | ||
| 205 | |||
| 206 | =head3 build_sql_value($k,$v,$ar,$dft,$act) | ||
| 207 | |||
| 208 | Input variables: | ||
| 209 | |||
| 210 | $k - column name | ||
| 211 | $v - column value | ||
| 212 | $ar - hash ref for column definition: ${$ar}{$k}{$itm}. | ||
| 213 | It is from getTableDef with 'hash' type. | ||
| 214 | $dft - date format. | ||
| 215 | Default to 'YYYYMMDD.HH24MISS'? - not sure that we need | ||
| 216 | to do that. | ||
| 217 | It checks the dft in $ar for $k first; | ||
| 218 | If not, then call id_datetime_format to get a format | ||
| 219 | If not, then return undef. | ||
| 220 | $act - action: update|insert | ||
| 221 | |||
| 222 | Variables used or routines called: | ||
| 223 | |||
| 224 | id_datetime_format - get date and time format based on | ||
| 225 | the date and time value provided. | ||
| 226 | |||
| 227 | How to use: | ||
| 228 | |||
| 229 | my $cs = 'usr/pwd@db'; | ||
| 230 | my $dbh = $self->getDBHandler($cs, "Oracle"); | ||
| 231 | my $tab = "test_table"; | ||
| 232 | my ($cns,$cd1,$ar) = $self->getTableDef($dbh,$tab,'*','hash'); | ||
| 233 | my $dft = 'YYYYMMDD.HH24MISS'; | ||
| 234 | my $v = $self->build_sql_value('dept',10,$ar,$dft); | ||
| 235 | |||
| 236 | Return: undef or value string to be used in SQL statement. | ||
| 237 | |||
| 238 | undef - value string can not be determined if no $k. | ||
| 239 | Do not use the column in your SQL statement. | ||
| 240 | 'NULL' - null if $v is not defined and $v is not required. | ||
| 241 | "''" - empty string if $v is not defined and data type is CHAR | ||
| 242 | or VARCHAR and NOT NULL. | ||
| 243 | str - any value string: number or quoted string | ||
| 244 | |||
| 245 | This method returns the value with proper quotes and format string. | ||
| 246 | For date datatype, it gets date and time format and use it in the | ||
| 247 | TO_DATE function. If the $dft is provided or defined in the $ar for | ||
| 248 | the column, then it convert the $v to the same format as defined in | ||
| 249 | $dft if the $v has different date and time format. | ||
| 250 | |||
| 251 | =cut | ||
| 252 | |||
| 253 | sub build_sql_value { | ||
| 254 | my $s = (ref $_[0]) ? shift : Oracle::SQL->new(@_); | ||
| 255 | my ($k, $v, $ar, $dft, $act) = @_; | ||
| 256 | return undef if !$k; | ||
| 257 | my $typ = ${$ar}{$k}{typ}; | ||
| 258 | my $req = ${$ar}{$k}{req}; | ||
| 259 | $dft = ${$ar}{$k}{dft} if !$dft; | ||
| 260 | $act = "update" if ! $act; | ||
| 261 | $v =~ s/^["']+//; $v =~ s/["']+$//; # remove quotes | ||
| 262 | my $msg = ""; | ||
| 263 | return 'NULL' if (!defined($v) && $req =~ /^null/i); | ||
| 264 | return "''" if (!defined($v) && $req =~ /^not/i && | ||
| 265 | $typ =~ /^(V|C)/i); | ||
| 266 | return undef if (!defined($v) || | ||
| 267 | ($v =~ /^null$/i && $req =~ /^null/i)); | ||
| 268 | if ($typ =~ /^(V|C)/i && $v && index($v,"'") > -1) { | ||
| 269 | # escape the quote (') | ||
| 270 | $v =~ s/'/''/gm; | ||
| 271 | } | ||
| 272 | return "'$v'" if (index($v,'?') > -1 || index($v,'%') > -1); | ||
| 273 | # remove quotes and leading and trailing spaces | ||
| 274 | $v =~ s/^['"\s]+//; $v =~ s/['"\s]+$//; | ||
| 275 | my $rst = undef; | ||
| 276 | if ($typ =~ /^N/i) { # numeric | ||
| 277 | # return 'NULL' if ($v eq ""); | ||
| 278 | if ($v eq "" || !defined($v)) { | ||
| 279 | return undef; | ||
| 280 | } elsif ($v && $v =~ /^(blank|null)/i) { | ||
| 281 | return "NULL"; | ||
| 282 | } else { | ||
| 283 | return $v+0; | ||
| 284 | } | ||
| 285 | } elsif ($typ =~ /^D/i) { # date | ||
| 286 | # return undef if the $v less than the shortest format | ||
| 287 | return $rst if (length($v) < 6); # YYMMDD | ||
| 288 | my $df = $s->id_datetime_format($v); | ||
| 289 | # print "$k|$v|$dft|$df\n"; | ||
| 290 | # return undef if we could not determine a format for $v | ||
| 291 | return $rst if (!$dft && !$df); | ||
| 292 | if ($act =~ /^insert/i) { | ||
| 293 | $rst = "'$v'"; | ||
| 294 | } else { | ||
| 295 | $rst = "TO_DATE('$v', '$df')"; | ||
| 296 | } | ||
| 297 | # if no $dft but we have $df, then use $df | ||
| 298 | return $rst if (!$dft && $df); | ||
| 299 | # if we have $dft which equals $df, we use $df | ||
| 300 | return $rst if ($dft && $dft eq $df); | ||
| 301 | if ($dft && $df && $dft ne $df) { | ||
| 302 | # we need to convert $v from $df to $dft | ||
| 303 | # then use $dft | ||
| 304 | my $itp = $s->TimeFormat("$df", 'ora'); | ||
| 305 | my $otp = $s->TimeFormat("$dft",'ora'); | ||
| 306 | $msg = "$df($itp):$dft($otp):$v:"; | ||
| 307 | $v = $s->cvtTime($v, $itp, $otp); | ||
| 308 | $msg .= "$v\n"; | ||
| 309 | $s->echoMSG(" $msg",9); | ||
| 310 | if ($act =~ /^insert/i) { | ||
| 311 | return "'$v'"; | ||
| 312 | } else { | ||
| 313 | return "TO_DATE('$v','$dft')"; | ||
| 314 | } | ||
| 315 | } | ||
| 316 | return undef; | ||
| 317 | } else { | ||
| 318 | return 'NULL' if ($v =~ /^null$/i); | ||
| 319 | return "''" if ($v =~ /^blank$/i); | ||
| 320 | return "'$v'"; | ||
| 321 | } | ||
| 322 | } | ||
| 323 | |||
| 324 | =head3 build_sql_operator($k,$v,$ar) | ||
| 325 | |||
| 326 | Input variables: | ||
| 327 | |||
| 328 | $k - column name | ||
| 329 | $v - column value | ||
| 330 | $ar - hash ref for column definition: ${$ar}{$k}{$itm}. | ||
| 331 | It is from getTableDef with 'hash' type. | ||
| 332 | |||
| 333 | Variables used or routines called: | ||
| 334 | |||
| 335 | None | ||
| 336 | |||
| 337 | How to use: | ||
| 338 | |||
| 339 | my $cs = 'usr/pwd@db'; | ||
| 340 | my $dbh = $self->getDBHandler($cs, "Oracle"); | ||
| 341 | my $tab = "test_table"; | ||
| 342 | my ($cns,$cd1,$ar) = $self->getTableDef($dbh,$tab,'*','hash'); | ||
| 343 | my $v = $self->build_sql_operator('dept',10,$ar); | ||
| 344 | |||
| 345 | Return: SQL operator to be used in SQL statement. | ||
| 346 | |||
| 347 | undef - could not determine operator based on the inputs | ||
| 348 | Do not use the column in your SQL statement. | ||
| 349 | 'LIKE' - match string with wild characters in $v. | ||
| 350 | 'IN' - $v contains a list of values of string or number | ||
| 351 | separated by comma. | ||
| 352 | '=' - any number or quote strings | ||
| 353 | |||
| 354 | This method returns SQL operator based on column data type and | ||
| 355 | the value in $v. | ||
| 356 | |||
| 357 | =cut | ||
| 358 | |||
| 359 | sub build_sql_operator { | ||
| 360 | my $s = (ref $_[0]) ? shift : Oracle::SQL->new(@_); | ||
| 361 | my ($k, $v, $ar, $dft) = @_; | ||
| 362 | return undef if !$k || ! defined($v); | ||
| 363 | my $typ = ${$ar}{$k}{typ}; | ||
| 364 | return 'LIKE' if (${$ar}{$k}{typ} =~ /^(C|V)/i && | ||
| 365 | $v =~ /(\%|\?)/); | ||
| 366 | return 'IN' if ((${$ar}{$k}{typ} =~ /^(C|V)/i && | ||
| 367 | $v =~ /','/) || (${$ar}{$k}{typ} =~ /^(N)/i && | ||
| 368 | $v =~ /,/)); | ||
| 369 | return '='; | ||
| 370 | } | ||
| 371 | |||
| 372 | =head3 build_sql_where($str,$ar,$dft) | ||
| 373 | |||
| 374 | Input variables: | ||
| 375 | |||
| 376 | $str - a string with k1=v1,k2=v2,... | ||
| 377 | $ar - hash ref for column definition: ${$ar}{$k}{$itm}. | ||
| 378 | It is from get_table_definition with 'hash' type. | ||
| 379 | $dft - date format. | ||
| 380 | Default to 'YYYYMMDD.HH24MISS'? - not sure that we need | ||
| 381 | to do that. | ||
| 382 | It checks the dft in $ar for $k first; | ||
| 383 | If not, then call id_datetime_format to get a format | ||
| 384 | If not, then return undef. | ||
| 385 | |||
| 386 | Variables used or routines called: | ||
| 387 | |||
| 388 | None | ||
| 389 | |||
| 390 | How to use: | ||
| 391 | |||
| 392 | my $cs = 'usr/pwd@db'; | ||
| 393 | my $dbh = $self->getDBHandler($cs, "Oracle"); | ||
| 394 | my $tab = "test_table"; | ||
| 395 | my ($cns,$cd1,$ar) = $self->getTableDef($dbh,$tab,'*','hash'); | ||
| 396 | my $s = "id=1,ln=tu,fn=han"; | ||
| 397 | my $whr = $self->build_sql_where($s,$ar,$dft); | ||
| 398 | |||
| 399 | Return: SQL WHERE clause | ||
| 400 | |||
| 401 | =cut | ||
| 402 | |||
| 403 | sub build_sql_where { | ||
| 404 | my $s = (ref $_[0]) ? shift : Oracle::SQL->new(@_); | ||
| 405 | my ($str,$ar, $dft) = @_; | ||
| 406 | return undef if !$str || !defined($str); | ||
| 407 | my @b = split /,/, $str; | ||
| 408 | my $whr = ""; | ||
| 409 | my $sub_name = "Build_SQL_Where"; | ||
| 410 | my ($k, $v, $op); | ||
| 411 | for my $x (0..$#b) { | ||
| 412 | ($k,$v) = (split /=/, $b[$x]); | ||
| 413 | $k = lc $k; | ||
| 414 | # remove leading and trailing spaces | ||
| 415 | $k =~ s/^\s+//; $k =~ s/\s+$//; | ||
| 416 | if (! exists ${$ar}{$k}) { | ||
| 417 | $s->echoMSG(" $sub_name: Column $k does not exist."); | ||
| 418 | next; | ||
| 419 | } | ||
| 420 | $v = $s->build_sql_value($k,$v,$ar,$dft); | ||
| 421 | $op = $s->build_sql_operator($k,$v,$ar,$dft); | ||
| 422 | next if ! defined($v); | ||
| 423 | if ($whr) { | ||
| 424 | $whr .= " AND $k $op $v\n"; | ||
| 425 | } else { | ||
| 426 | $whr = " WHERE $k $op $v\n"; | ||
| 427 | } | ||
| 428 | } | ||
| 429 | return $whr; | ||
| 430 | } | ||
| 431 | |||
| 432 | =head3 form_sql($dbh,$arf,$rtp) | ||
| 433 | |||
| 434 | Input variables: | ||
| 435 | |||
| 436 | $dbh - database handler | ||
| 437 | $arf - input array ref. It has the following elements: | ||
| 438 | act - SQL action such as SELECT, UPDATE, DELETE, etc. | ||
| 439 | tab - target table or view name | ||
| 440 | cns - column names separated by comma | ||
| 441 | where - condition array reference: ${$ar}[$i]{$itm} | ||
| 442 | $i is condition index number | ||
| 443 | $itm are: | ||
| 444 | cn - column name | ||
| 445 | op - operator such as =, <, >, in, lk, etc | ||
| 446 | cv - value, or values separated by comma | ||
| 447 | so - set operator such as AND or OR | ||
| 448 | group_by - a list of columns separated by comma | ||
| 449 | order_by - a list of columns separated by comma | ||
| 450 | data - data array reference ${$ar}{$cn} | ||
| 451 | dft - date format | ||
| 452 | rwd - right column width for formating sql statement | ||
| 453 | $rtp - return type: default - SQL statement string | ||
| 454 | where - just where clause | ||
| 455 | hash - hash array. It has | ||
| 456 | table - table name | ||
| 457 | cns - column specification such as '*' or column names | ||
| 458 | columns - column names. If '*', then all the column names. | ||
| 459 | select/update/delete - actions | ||
| 460 | from - from a table | ||
| 461 | where - where clause | ||
| 462 | group_by - group by clause | ||
| 463 | order_by - order by clause | ||
| 464 | sql - full SQL statement | ||
| 465 | hash_ref - hash array reference pointing to the above hash | ||
| 466 | sql - the whole SQL statement | ||
| 467 | |||
| 468 | Variables used or routines called: | ||
| 469 | |||
| 470 | echoMSG - echo message | ||
| 471 | isObjExist - check object existence | ||
| 472 | getTableDef - get table definitions | ||
| 473 | getTableData - get table data | ||
| 474 | |||
| 475 | How to use: | ||
| 476 | |||
| 477 | my $cs = 'usr/pwd@db'; | ||
| 478 | my $dbh = $self->getDBHandler($cs, "Oracle"); | ||
| 479 | my $drf = $self->getTableData($dbh,$srctab,'*','','hash'); | ||
| 480 | my $arf = bless {}, ref($self)||$self; | ||
| 481 | ${$arf}{act} = 'SELECT'; | ||
| 482 | ${$arf}{tab} = 'test_tab'; | ||
| 483 | ${$arf}{cns} = 'id,name'; | ||
| 484 | ${$arf}{data} = $drf; | ||
| 485 | my $tab = "test_table"; | ||
| 486 | $self->form_sql($dbh,$arf); | ||
| 487 | |||
| 488 | Return: string, hash, hash ref based on return type. | ||
| 489 | |||
| 490 | =cut | ||
| 491 | |||
| 492 | sub form_sql { | ||
| 493 | my $self = (ref $_[0]) ? shift : Oracle::SQL->new(@_); | ||
| 494 | my ($dbh,$arf,$rtp) = @_; | ||
| 495 | croak "ERR: no DB handler is specified.\n" if !$dbh; | ||
| 496 | croak "ERR: action or table is specified.\n" if !$arf; | ||
| 497 | my ($act,$tab,$cns,$mrc,$dft,$rwd) = ("","","","","",""); | ||
| 498 | $act = ${$arf}{act} if exists ${$arf}{act}; | ||
| 499 | $act = 'SELECT' if !$act; | ||
| 500 | $act = uc $act; # DML | ||
| 501 | $tab = ${$arf}{tab} if exists ${$arf}{tab}; # table name | ||
| 502 | $dft = ${$arf}{dft} if exists ${$arf}{dft}; # date format | ||
| 503 | $dft = 'YYYYMMDD.HH24MISS' if !$dft; | ||
| 504 | $rwd = ${$arf}{rwd} if exists ${$arf}{rwd}; # right col wid | ||
| 505 | $rwd = 65 if !$rwd; | ||
| 506 | croak "ERR: no table name is specified.\n" if !$tab; | ||
| 507 | $self->echoMSG(" - generating $act statement for $tab..."); | ||
| 508 | if (!$self->isObjExist($dbh,$tab,'table') && | ||
| 509 | !$self->isObjExist($dbh,$tab,'view') ) { | ||
| 510 | $self->echoMSG("WARN: table or view - $tab does not exist!"); | ||
| 511 | return 0; | ||
| 512 | } | ||
| 513 | $cns = ${$arf}{cns} if exists ${$arf}{cns}; # column name | ||
| 514 | $cns = '*' if !$cns; | ||
| 515 | $mrc = 500; # max # records to be retrieved | ||
| 516 | my ($wrf,$gpb,$odb) = ("","",""); | ||
| 517 | $wrf = ${$arf}{where} if exists ${$arf}{where}; | ||
| 518 | $gpb = ${$arf}{group_by} if exists ${$arf}{group_by}; | ||
| 519 | $odb = ${$arf}{order_by} if exists ${$arf}{order_by}; | ||
| 520 | # get column definition: | ||
| 521 | # $cn1 - columns separated by comma | ||
| 522 | # $dfa - array ref: ${$df1}[$i][$j] | ||
| 523 | # $dfb - hash ref : ${$df2}{$cn}{$itm} | ||
| 524 | my ($cn1,$dfa, $dfb) = $self->getTableDef($dbh,$tab,'','hash'); | ||
| 525 | my $n1 = 10; # left column width | ||
| 526 | my $n2 = $rwd; # right column width | ||
| 527 | my $fmt = "%${n1}s %-${n2}s\n"; | ||
| 528 | $cns = lc $cns; | ||
| 529 | my @cln = $self->split_cns($cns, $n2); | ||
| 530 | my ($sql,$t,$whr,$grp,$ord) = ("","","","",""); | ||
| 531 | my ($so,$cn,$op,$cv,@a,@b,$k); | ||
| 532 | my %rst = (table=>$tab, columns=>$cn1, cns=>$cns); | ||
| 533 | if ($act =~ /^SEL/i) { | ||
| 534 | if ($#cln==0) { | ||
| 535 | $sql = sprintf $fmt, $act, $cln[0]; | ||
| 536 | } else { | ||
| 537 | $sql = sprintf $fmt, $act, "$cln[0],"; | ||
| 538 | foreach my $i (1..$#cln) { | ||
| 539 | if ($i==$#cln) { | ||
| 540 | $sql .= sprintf $fmt, "", "$cln[$i]"; | ||
| 541 | } else { | ||
| 542 | $sql .= sprintf $fmt, "", "$cln[$i],"; | ||
| 543 | } | ||
| 544 | } | ||
| 545 | } | ||
| 546 | $rst{select} = $sql; | ||
| 547 | $sql .= sprintf $fmt, 'FROM', $tab; | ||
| 548 | $rst{from} = sprintf $fmt, 'FROM', $tab; | ||
| 549 | } elsif ($act =~ /^(UPD|INS)/i) { | ||
| 550 | my $drf = ${$arf}{data}; | ||
| 551 | $sql = sprintf $fmt, 'INSERT INTO', "$tab"; | ||
| 552 | my $ito = sprintf $fmt, 'INSERT INTO', "$tab"; | ||
| 553 | $cns = lc $cn1 if (!$cns || $cns =~ /^\*/); | ||
| 554 | @a = $self->split_cns($cns, $n2); | ||
| 555 | foreach my $i (0..$#a) { | ||
| 556 | if ($i==0) { | ||
| 557 | if ($i==$#a) { | ||
| 558 | $sql .= sprintf $fmt, '', "($a[$i])"; | ||
| 559 | $ito .= sprintf $fmt, '', "($a[$i])"; | ||
| 560 | next; | ||
| 561 | } else { | ||
| 562 | $sql .= sprintf $fmt, '', "($a[$i],"; | ||
| 563 | $ito .= sprintf $fmt, '', "($a[$i],"; | ||
| 564 | } | ||
| 565 | } elsif ($i==$#a) { | ||
| 566 | $sql .= sprintf $fmt, "", "$a[$i])"; | ||
| 567 | $ito .= sprintf $fmt, "", "$a[$i])"; | ||
| 568 | } else { | ||
| 569 | $sql .= sprintf $fmt, "", "$a[$i],"; | ||
| 570 | $ito .= sprintf $fmt, "", "$a[$i],"; | ||
| 571 | } | ||
| 572 | } | ||
| 573 | $rst{insert_into} = $ito; | ||
| 574 | my ($v, $p, $vnp) = ("","",""); | ||
| 575 | @a = split /,/, $cns; | ||
| 576 | @b = (); | ||
| 577 | for my $i (0..$#a) { | ||
| 578 | $k = $a[$i]; | ||
| 579 | $v = ${$drf}{$k}; | ||
| 580 | if (!$v || $v =~ /^null/i) { | ||
| 581 | $p = "null"; | ||
| 582 | } elsif (${$dfb}{$k}{typ} =~ /^DATE/i) { | ||
| 583 | $p = "to_date('$v','$dft')"; | ||
| 584 | } elsif (${$dfb}{$k}{typ} =~ /^(V|C)/i) { | ||
| 585 | $v =~ s/'/''/gm; # escape quotes | ||
| 586 | $p = "'$v'"; | ||
| 587 | } else { $p = "$v"; } | ||
| 588 | if ($vnp && length("$vnp,$p") > $n2) { | ||
| 589 | push @b, $vnp; $vnp = ""; | ||
| 590 | } | ||
| 591 | if ($vnp) { $vnp .= ",$p"; } else { $vnp = "$p"; }; | ||
| 592 | } | ||
| 593 | if ($vnp) { push @b, $vnp; $vnp = ""; } | ||
| 594 | my $vls = ""; | ||
| 595 | if ($#b==0) { | ||
| 596 | $sql .= sprintf $fmt, 'VALUES', "($b[0])"; | ||
| 597 | $vls .= sprintf $fmt, 'VALUES', "($b[0])"; | ||
| 598 | } else { | ||
| 599 | $sql .= sprintf $fmt, 'VALUES', "($b[0],"; | ||
| 600 | $vls .= sprintf $fmt, 'VALUES', "($b[0],"; | ||
| 601 | foreach my $j (1..$#b) { | ||
| 602 | if ($j==$#b) { | ||
| 603 | $sql .= sprintf $fmt, "", "$b[$j])"; | ||
| 604 | $vls .= sprintf $fmt, "", "$b[$j])"; | ||
| 605 | } else { | ||
| 606 | $sql .= sprintf $fmt, "", "$b[$j],"; | ||
| 607 | $vls .= sprintf $fmt, "", "$b[$j],"; | ||
| 608 | } | ||
| 609 | } | ||
| 610 | } | ||
| 611 | $rst{values} = $vls; | ||
| 612 | } elsif ($act =~ /^DEL/i) { | ||
| 613 | } else { # Insert | ||
| 614 | } | ||
| 615 | if ($wrf) { # where clause | ||
| 616 | for my $i (0..$#{$wrf}) { # each condition | ||
| 617 | $so = ${$wrf}[$i]{so}; # set operator | ||
| 618 | $cn = ${$wrf}[$i]{cn}; # column name | ||
| 619 | $op = ${$wrf}[$i]{op}; # operator | ||
| 620 | $cv = ${$wrf}[$i]{cv}; # column value | ||
| 621 | $t = $self->genWhere($so,$cn,$op,$cv,$dfb,$dft); | ||
| 622 | # print "SO:$so CN:$cn OP:$op CV:$cv\n"; # XXX | ||
| 623 | # print "T: $t\n"; | ||
| 624 | @a = $self->split_cns($t, $n2, ' '); | ||
| 625 | $k = 0; | ||
| 626 | if ($i == 0) { | ||
| 627 | $whr = sprintf $fmt, "WHERE", $a[0]; | ||
| 628 | $sql .= $whr; | ||
| 629 | $k = 1; | ||
| 630 | } | ||
| 631 | foreach my $j ($k..$#a) { | ||
| 632 | $sql .= sprintf $fmt, "", $a[$j]; | ||
| 633 | $whr .= sprintf $fmt, "", $a[$j]; | ||
| 634 | } | ||
| 635 | } | ||
| 636 | $rst{where} = $whr; | ||
| 637 | } | ||
| 638 | if ($gpb) { # group by | ||
| 639 | @a = $self->split_cns($gpb, $n2); | ||
| 640 | $grp = sprintf $fmt, 'GROUP BY', $a[0]; | ||
| 641 | $sql .= $grp; | ||
| 642 | foreach my $i (1..$#a) { | ||
| 643 | $grp .= sprintf $fmt, "", $a[$i]; | ||
| 644 | $sql .= sprintf $fmt, "", $a[$i]; | ||
| 645 | } | ||
| 646 | $rst{group_by} = $grp; | ||
| 647 | } | ||
| 648 | if ($odb) { # order by | ||
| 649 | @a = $self->split_cns($odb, $n2); | ||
| 650 | $ord = sprintf $fmt, 'ORDER BY', $a[0]; | ||
| 651 | $sql .= $ord; | ||
| 652 | foreach my $i (1..$#a) { | ||
| 653 | $ord .= sprintf $fmt, "", $a[$i]; | ||
| 654 | $sql .= sprintf $fmt, "", $a[$i]; | ||
| 655 | } | ||
| 656 | $rst{order_by} = $ord; | ||
| 657 | } | ||
| 658 | $sql =~ s/\s*$//gm; | ||
| 659 | return $whr if (!$rtp || $rtp =~ /^where/i); | ||
| 660 | return $sql if (!$rtp || $rtp =~ /^sql/i); | ||
| 661 | $rst{sql} = $sql; | ||
| 662 | return \%rst if ($rtp && $rtp =~ /^hash_ref/i); | ||
| 663 | return %rst if ($rtp && $rtp =~ /^hash/i); | ||
| 664 | } | ||
| 665 | |||
| 666 | =head3 split_cns($str,$len,$chr,$nbk) | ||
| 667 | |||
| 668 | Input variables: | ||
| 669 | |||
| 670 | $str - string with words or column names separated by comma | ||
| 671 | or by spliting character | ||
| 672 | $len - length allow in a line, default to 65 | ||
| 673 | $chr - spliting character, default to comma | ||
| 674 | $nbk - number of blank space in from of each line. | ||
| 675 | If this is set, it will return a string with line breaks. | ||
| 676 | |||
| 677 | Variables used or routines called: | ||
| 678 | |||
| 679 | None | ||
| 680 | |||
| 681 | How to use: | ||
| 682 | |||
| 683 | my $cs = 'col1, col2, col3, this, is, a multiple,line'; | ||
| 684 | my @a = $self->split_cns($cs,10); | ||
| 685 | |||
| 686 | Return: array with lines within length limit or a string. | ||
| 687 | |||
| 688 | =cut | ||
| 689 | |||
| 690 | sub split_cns { | ||
| 691 | my $self = (ref $_[0]) ? shift : Oracle::SQL->new(@_); | ||
| 692 | my ($str, $len, $sep, $nbk) = @_; | ||
| 693 | $sep = ',' if !$sep; | ||
| 694 | $nbk = 0 if !$nbk; | ||
| 695 | # $str =~ s/^["']+//; $str =~ s/["']+$//; | ||
| 696 | my @r = (); | ||
| 697 | if (length($str) <= $len) { push @r, $str; | ||
| 698 | return @r if !$nbk; | ||
| 699 | return (' ' x $nbk) . "$str\n"; | ||
| 700 | } | ||
| 701 | # we have multiple lines | ||
| 702 | my $line = ""; | ||
| 703 | foreach my $i (split /$sep/, $str) { # split it into words | ||
| 704 | $i = uc "\"$i\""; | ||
| 705 | if (length("$line$sep$i") > $len) { | ||
| 706 | push @r, $line; $line = ""; | ||
| 707 | } | ||
| 708 | if ($line) { $line .= "$sep$i"; } else { $line = $i; } | ||
| 709 | } | ||
| 710 | push @r, $line if $line; | ||
| 711 | return @r if !$nbk; | ||
| 712 | my $s = ""; | ||
| 713 | for my $i (0..$#r) { | ||
| 714 | next if !$r[$i]; | ||
| 715 | if ($i==$#r) { | ||
| 716 | $s .= (' ' x $nbk) . "$r[$i]\n"; | ||
| 717 | } else { | ||
| 718 | $s .= (' ' x $nbk) . "$r[$i],\n"; | ||
| 719 | } | ||
| 720 | } | ||
| 721 | return $s; | ||
| 722 | } | ||
| 723 | |||
| 724 | |||
| 725 | =head3 genWhere($so,$cn,$op,$cv,$ar,$dft) | ||
| 726 | |||
| 727 | Input variables: | ||
| 728 | |||
| 729 | $so - set operator: AND, OR | ||
| 730 | $cn - column name | ||
| 731 | $op - operator: =, <=, >=, <>, lk, btw, in, nn, nl, etc. | ||
| 732 | $cv - column value | ||
| 733 | $ar - hash array ref: ${$ar}{$cn}{$itm}. | ||
| 734 | $itm: col, typ, wid, max. dec, req, min, dft, and dsp | ||
| 735 | $dft - date format | ||
| 736 | Variables used or routines called: | ||
| 737 | |||
| 738 | None | ||
| 739 | |||
| 740 | How to use: | ||
| 741 | |||
| 742 | my $whr = $self->build_where('','id','=',1); | ||
| 743 | $whr .= $self->build_where('Or','name','lk','A'); | ||
| 744 | |||
| 745 | Return: string - where clause. | ||
| 746 | |||
| 747 | =cut | ||
| 748 | |||
| 749 | sub genWhere { | ||
| 750 | my $self = (ref $_[0]) ? shift : Oracle::SQL->new(@_); | ||
| 751 | my ($so,$cn,$op,$cv,$ar,$dft) = @_; | ||
| 752 | # Input variables: | ||
| 753 | # $so - set operator: AND, OR | ||
| 754 | # $cn - column name | ||
| 755 | # $op - operator: =, <=, >=, <>, lk, btw, in, nn, nl, etc. | ||
| 756 | # $cv - column value | ||
| 757 | # $ar - hash array ref: ${$ar}{$cn}{$itm}. | ||
| 758 | # $itm: col, typ, wid, max. dec, req, min, dft, and dsp | ||
| 759 | # | ||
| 760 | my $r = ""; | ||
| 761 | return $r if ($cn =~ /^_/); | ||
| 762 | return $r if (!$cn && !$op); | ||
| 763 | return $r if ($cv =~ /^\s*$/); | ||
| 764 | $cn = lc($cn); | ||
| 765 | my (@a); | ||
| 766 | my %opt=('eq'=>'=', 'le'=>'<=', 'ge'=>'>=', | ||
| 767 | 'ne'=>'<>', 'gt'=>'>', 'lt'=>'<', | ||
| 768 | 'in'=>'in', 'lk'=>'like', 'btw'=>'between', | ||
| 769 | 'nn'=>'not null', 'nl'=>'is null' | ||
| 770 | ); | ||
| 771 | my $ct = ""; # column type | ||
| 772 | $ct = ${$ar}{$cn}{typ} if exists ${$ar}{$cn}{typ}; | ||
| 773 | $ct = 'Number' if $cn =~ /^(rownum)/i; | ||
| 774 | $dft = "YYYYMMDD.H24MISS" if !$dft; | ||
| 775 | $dft = "'$dft'"; # add quotes | ||
| 776 | if ($op && $op eq 'lk') { | ||
| 777 | # if user uses '*' as wildcard | ||
| 778 | $cv =~ s/\*/\%/; # change '*' to '%' | ||
| 779 | # if user did not provide any wildcard, we add one | ||
| 780 | if (index($cv, '%') < 0) { $cv .= '%'; } | ||
| 781 | } | ||
| 782 | # $so = 'AND' if ! $so; | ||
| 783 | my $msg = "SO:$so CN:$cn OP:$op CV:$cv DF:$dft\n"; | ||
| 784 | $self->echoMSG($msg, 5); | ||
| 785 | my ($t); | ||
| 786 | if ($so) { $r .= uc($so) . " "; } | ||
| 787 | $r .= "$cn " . uc($opt{$op}) . " "; # column op | ||
| 788 | if (uc($op) eq 'BTW') { | ||
| 789 | @a = split /,\s*/, $cv; | ||
| 790 | if ($ct =~ /^N/i) { # Number | ||
| 791 | $r .= "$a[0] AND $a[1]"; | ||
| 792 | } elsif ($ct =~ /^D/i) { # Date | ||
| 793 | $r .= "to_date('$a[0]',$dft) AND"; | ||
| 794 | $r .= "to_date('$a[1]',$dft) "; | ||
| 795 | } else { # CHAR or VARCHAR | ||
| 796 | $r .= "'$a[0]' AND '$a[1]' "; | ||
| 797 | } | ||
| 798 | } elsif (uc($op) eq 'IN') { | ||
| 799 | if ($ct =~ /^N/i) { # Number | ||
| 800 | $r .= "($cv) "; | ||
| 801 | } elsif ($ct =~ /^D/i) { # Date | ||
| 802 | @a = split /,\s*/, $cv; | ||
| 803 | $t = ""; | ||
| 804 | foreach my $i (@a) { | ||
| 805 | if ($t) { $t .= ",to_date('$i',$dft)"; | ||
| 806 | } else { $t = "to_date('$i',$dft)"; } | ||
| 807 | } | ||
| 808 | $r .= "($t) "; | ||
| 809 | } else { # CHAR or VARCHAR | ||
| 810 | $cv =~ s/,\s*/','/g; | ||
| 811 | $r .= "('$cv') "; | ||
| 812 | } | ||
| 813 | } else { | ||
| 814 | if ($ct =~ /^N/i) { # Number | ||
| 815 | $r .= "$cv "; | ||
| 816 | } elsif ($ct =~ /^D/i) { # Date | ||
| 817 | $r .= "to_date('$cv',$dft) "; | ||
| 818 | } else { # CHAR or VARCHAR | ||
| 819 | $r .= "'$cv' "; | ||
| 820 | } | ||
| 821 | } | ||
| 822 | # print "$r\n"; | ||
| 823 | return $r; | ||
| 824 | } | ||
| 825 | |||
| 826 | =head3 run_sql($dbh,$sfn) | ||
| 827 | |||
| 828 | Input variables: | ||
| 829 | |||
| 830 | $dbh - datebase handler or connection string | ||
| 831 | usr/pwd@db: for Oracle | ||
| 832 | $sfn - sql file name with full path | ||
| 833 | $hmd - home directory | ||
| 834 | |||
| 835 | Variables used or routines called: | ||
| 836 | |||
| 837 | None | ||
| 838 | |||
| 839 | How to use: | ||
| 840 | |||
| 841 | my $dbh = $self-?getDBHandler('usr/pwd@db'); | ||
| 842 | my $sfn = '/my/dir/sqls/crt1.sql'; | ||
| 843 | $self->run_sql($dbh, $sfn); | ||
| 844 | |||
| 845 | Return: the following status codes: | ||
| 846 | |||
| 847 | 0 - ok; | ||
| 848 | 1 - no DB handler | ||
| 849 | 2 - inproper inputs | ||
| 850 | 3 - sql not found | ||
| 851 | |||
| 852 | =cut | ||
| 853 | |||
| 854 | sub run_sql { | ||
| 855 | my $s = shift; | ||
| 856 | my ($dbh,$sfn,$hmd) = @_; | ||
| 857 | # check input variables | ||
| 858 | return 1 if ! $dbh; | ||
| 859 | return 2 if ! $sfn; | ||
| 860 | return 3 if ! -f $sfn; | ||
| 861 | my ($q,$e,@a,$m,$cmd,$cns,$dbt); | ||
| 862 | my $ds = '/'; | ||
| 863 | if ($dbh =~ /([-\w_]+)\/(\w+)\@(\w+)/) { | ||
| 864 | $dbt = 'Oracle'; | ||
| 865 | $cns = $dbh; | ||
| 866 | } elsif ($dbh =~ /^(DBI::db)/i) { # DBI::db=HASH(0x649178) | ||
| 867 | $cns = $1; | ||
| 868 | $dbt = $dbh->{Driver}->{Name}; | ||
| 869 | } elsif ($dbh =~ /^(Win32::ODBC)/i) { # Win32::ODBC=HASH(0x17cadc8) | ||
| 870 | $cns = $1; | ||
| 871 | $dbt = 'ODBC'; | ||
| 872 | } else { | ||
| 873 | $dbt = 'CSV'; | ||
| 874 | $cns = ''; | ||
| 875 | } | ||
| 876 | if ($dbt =~ /^oracle/i) { | ||
| 877 | $hmd = $ENV{ORACLE_HOME} if ! $hmd && exists $ENV{ORACLE_HOME}; | ||
| 878 | # $q = "BEGIN\n@a\nEND;\n"; | ||
| 879 | # $e = $dbh->prepare($q); | ||
| 880 | # $e->execute() or croak "ERR: could not execute: $e->errstr"; | ||
| 881 | # print $q; | ||
| 882 | $cmd = join $ds, $hmd, "bin", "sqlplus"; | ||
| 883 | # $cmd .= " -s $cns \@$sfn "; | ||
| 884 | $cmd .= " $cns \@$sfn "; | ||
| 885 | $m=$cmd; | ||
| 886 | $m =~ s{(\w+)/(\w+)\@}{$1/\*\*\*\@}; | ||
| 887 | $m =~ s{( \@)}{\n $1}g; | ||
| 888 | $s->echoMSG(" CMD: $m\n",2); | ||
| 889 | open CMD, "$cmd |" or croak "Could not run sqlplus: $!\n"; | ||
| 890 | @a = <CMD>; | ||
| 891 | close CMD; | ||
| 892 | $s->echoMSG("@a", 5); | ||
| 893 | } else { | ||
| 894 | # open FH, "<$sfn" or croak "ERR: open - $sfn: $!\n"; | ||
| 895 | # my @a = <FH>; | ||
| 896 | # close FH; | ||
| 897 | } | ||
| 898 | return 0; | ||
| 899 | } | ||
| 900 | |||
| 901 | =head1 AUTHOR | ||
| 902 | |||
| 903 | Hanming Tu, hanming_tu@yahoo.com | ||
| 904 | |||
| 905 | =head1 SEE ALSO (some of docs that I check often) | ||
| 906 | |||
| 907 | Oracle::Trigger, Oracle:DDL, Oracle::DML, Oracle::DML::Common, | ||
| 908 | Oracle::Loader, etc. | ||
| 909 | |||
| 910 | |||
| 911 | =cut | ||
| 912 |