-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdbSession.pm
More file actions
executable file
·1997 lines (1678 loc) · 56.3 KB
/
dbSession.pm
File metadata and controls
executable file
·1997 lines (1678 loc) · 56.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dbSession;
# -*- perl -*-
use strict;
use MIME::Base64;
use POSIX;
=head1 NAME
dbSession - a DBI wrapper with various db helpers and utils
=cut
=head1 SYNOPSIS
use dbSession;
#constructors:
my $ds = dbSession->new($db_locator [, $authfile]);
my $ds = dbSession->new([$server[:$port], $user, $pass, $server_type]);
#direct connection:
my $ds = dbSession->postgres($server, $user, $password, $db);
my $ds = dbSession->oracle($server, $user, $password, $db);
my $ds = dbSession->sybase($server, $user, $password, $db);
my $ds = dbSession->mysql($serverhost, $user, $password, $db);
# methods:
my $dbh = $ds->dbh(); # get DBI's database handle
my $res = $ds->do($sql); #non-query SQL execution
my $sth = $ds->prep($sql); #prepare SQL for execution
my $sth = $ds->prepare($sql); # ditto
my $sth = $ds->exec($sql, ...); #prepare and execute an SQL
my $sth = $ds->exec($sth, ...); #execute a previously prepared $sth
my $aref = $ds->fetch($sth); #fetches next row as an array ref
my $aref = $ds->fetch(); # fetches next row for the most recent $sth
# (generated by the last prep() or exec())
my @rowvalues = $db->getval($sql); #returns a single row (the first)
my $fieldvalue = $db->getval($sql); #in scalar context returns the first field
=head1 DESCRIPTION
A wrapper module for DBI, with various helper subroutines
=cut
use Exporter;
use DBI;
our ($VERSION, @ISA, @EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw( initLog restoreSTD resumeLog flog
db_perm scrypt sdecrypt db_srvtype db_login db_logout db_lastlogin
onErrExit trim cur_status ask_pass ask_cpass getDate
sql_do sql_exec sql_prepare sth_exec sth_fetch sth_afetch
sql_get_value sql_get_values sql_get_all syb_dboalias
confirm nice_int nice_intm sql_quote sql_dquote
print_sql print_sql_fetch sql_to_file ErrExit
fmt_fasta print_fasta sql2fasta sql2fasta_CLR fetch2fasta
sub sql_cmdfile sql_execlist batchsql_to_file
syb_getIndexes syb_putIndexes);
#-- package variables (static):
#-- these will be overriden by the [Default] section of ~/.db_pass
# or the authentication file, or whatever extra info the user
# provides in the locator string
# if no .db_pass or other authentication file/data is given,
# these defaults MUST BE edited apropriately for local compliance
# before installing the module
# Example, for sybase:
# our $DBDEF_SRV_TYPE='sybase';
# our $DBDEF_SERVER = $ENV{'DSQUERY'} || 'SYBEST';
# our $DBDEF_USER='access';
# our $DBDEF_PASS='access';
our $DBDEF_SRV_TYPE='mysql';
our $DBDEF_SERVER = 'localhost';
# this is the host name, and it may include ":<port#>"
our $DBDEF_USER='access';
our $DBDEF_PASS='access';
our $dbExitSub=\&dbErrExit;
our $dbLastError='';
our $DEF_FASTA_LINELEN=60;
#--procedural interface helpers:
our %dbhs; # dbh -> [valid, server[:port], user, pass, initdb, servertype]
our $db_last_dbh;
our ($file_log, $stdout_log, $stderr_log);
local *__OLDERR;
local *__OLDSTD;
#-- we could test for CGI environment e.g.:
# unless ($ENV{HTTP_ACCEPT} || $ENV{HTTP_HOST}) { ... }
#-- to avoid ~/.db_pass parsing and instead just use the DBDEF_* values above
return 1;
=head1 GLOBAL (non-OO) SUBROUTINES
----------------------------------------------------------------
=cut
=head2 initLog(<logfilename> [, <STDOUT_redirect_file>, <STDERR_redirect_file>])
Initializes the logging system. Subsequent flog() calls will write
into <logfilename> Beware that <logfilename>, if exists, is deleted
and then created again at each initLog() call.
May optionally redirect STDOUT and/or STDERR to the provided log
file(s)
=cut
sub initLog {
($file_log, $stdout_log, $stderr_log) = @_;
return unless ($file_log);
unlink($file_log);
#also saves STDOUT, STDERR;
open(__OLDOUT, ">&STDOUT") if $stdout_log;
open(__OLDERR, ">&STDERR") if $stderr_log;
if ($stdout_log) {
open(STDOUT, ">$stdout_log")
|| &$dbExitSub("Cannot redirect STDOUT to file $stdout_log");
}
if ($stderr_log) {
if ($stderr_log eq $stdout_log) {
open(STDERR, ">&STDOUT");
}
else {
open(STDERR, ">$stderr_log")
|| &$dbExitSub("Cannot redirect STDERR to file $stderr_log");
}
}
}
=head2 restoreSTD( )
Restores the STDERR and STDOUT if they were previously redirected by initLog()
=cut
sub restoreSTD {
return unless ($file_log);
close STDERR if ($stderr_log);
close STDOUT if ($stdout_log);
open(STDOUT, ">&__OLDOUT");
open(STDERR, ">&__OLDERR");
}
sub resumeLog {
if ($stdout_log) {
open(STDOUT, ">>$stdout_log")
|| &$dbExitSub("Cannot redirect STDOUT to file $stdout_log");
}
if ($stderr_log) {
if ($stderr_log eq $stdout_log) {
open(STDERR, ">&STDOUT");
}
else {
open(STDERR, ">>$stderr_log")
|| &$dbExitSub("Cannot redirect STDERR to file $stderr_log");
}
}
}
=head2 flog(<text>..)
The given text lines are written to STDERR and to the log file if such
was established by initLog()
=cut
sub flog {
if ($file_log) {
local *LOG_FILE;
open(LOG_FILE, ">>$file_log");
print LOG_FILE join("\n",@_)."\n";
print __OLDERR join("\n",@_)."\n";
#print STDERR join("\n",@_)."\n";
close LOG_FILE;
}
else {
print STDERR join("\n",@_)."\n";
}
}
sub db_askpass {
my ($server, $srvtype, $user, $db)=@_;
$user=$ENV{'USER'} unless $user;
$user=$ENV{'USERNAME'} unless $user;
$server=$DBDEF_SERVER unless $server;
$srvtype=$DBDEF_SRV_TYPE unless $srvtype;
# script instructed to ask for password always
my $pass=&ask_pass("Enter password for user '$user' on server '$server',\n database $db");
return ($server, $user, $pass, $db, $srvtype);
}
=head2 db_perm(<db> [,<auth_file>] [, 'ASK'])
returns: (server_name, user, pass, db, server_type, server_port)
(if server_port is returned non-zero, then server_name is actually a hostname and
server_port is optional)
if no <auth_file> is specified, ~/.db_pass is read.
Parses <auth_file> looking for server and user authentication data
necessary for initiating a connection to the database $db, (using
the current Unix user as the username, unless :<user> is included in
$db)
$db parameter can also have a more complex locator format:
<dbschema>[@<server>[/<server_type>]][:<user>]
..where <server_type> can be 'postgres', 'oracle', 'sybase' or 'mysql'.
None of <server>,<user>,<server_type> are necessary except to avoid
ambiguity when multiple servers with the same name (but different DBMS)
exist in <auth_file>
If a server name is not found for the current <dbname>, the [Default]
section is looked-up in <auth_file>; if that section is missing,
hardcoded defaults are used instead.
If the 3rd parameter of this function is the string 'ASK', db_perm will
stop and ask for the specified user's password interactively.
The <auth_file> contains the encrypted passwords just for very basic
visual protection (use dbpass utility to update the passwords; see
the subroutines scrypt and sdecrypt in this module)
----------------------------------------
[Default]
server_type=oracle
server=BIOCOMPD
[BIOCOMPD]
db1, db2, db3, ...
[MYSERVER/oracle@orclhost.dfci.harvard.edu:3139]
db1_1, db1_2, db1_3, ...
[MYSERVER/mysql@tools.dfci.harvard.edu]
db1_1, db1_2, db1_3, ...
[MYSQLSRV/mysql@mysqlhost:port]
db2_1, db2_2, db2_3, ...
[Authentication]
BIOCOMPD:username/encpassword
MYSERVER/oracle:username/encpassword
MYSERVER/mysql:username/encpassword
MYSQLSRV:username/encpassword
-----------------------------------------
The server name can be optionally followed by '/<srv_type>'
and/or '@<host>' (optionally ':<port>'), otherwise Default values
are assumed.
If server names are uniquely assigned and the DBD driver has a mechanism
of resolving the host name based on the server name (e.g. like Oracle does by
using environment variables like TNS_ADMIN, TWO_TASK, etc.), a ~/db_pass file
can be as simple as this:
---------------------------------
[Default]
server_type=oracle
[BIOCOMPD]
db1, db2, db3...
[Authentication]
BIOCOMPD:username:encpassword
------------------------------------
IMPORTANT: the [Authentication] section MUST be the last section in the
file, while [Default] section MUST be the first (to speed up parsing).
=cut
sub db_perm {
my ($dblocator, $authfile, $flag)=@_;
$authfile='' unless defined($authfile);
$flag=$authfile if $authfile =~ '/\bASK\b/i' && !defined($flag);
my $db_err="Error at db_perm('$dblocator', '$authfile'):";
my $db_advice="(You should probably use dbpass to update $authfile)\n";
if ($authfile) {
open(TESTF, $authfile) ||
die("$db_err Cannot open $authfile!\n");
close(TESTF);
}
else { $authfile= $ENV{HOME}.'/.db_pass' }
#--------- to return:
my ($db, $server, $user, $pass, $srvtype, $srvport);
#only mysql returns $server as a hostname and also a $srvport
my $srvhost; #only needed for mysql, to be returned instead of $server
# $dblocator format can be <dbname>[@<server>[/<server_type>]][:<user>]
($db, my $rest) = ($dblocator=~m/^([#\"\-\.\w]+)(.*)/);
die "$db_err Cannot parse locator '$dblocator'!\n"
unless $db;
if ($rest) { # in here we can have server, server_type and/or user
$rest=~tr/ //d;
my @d=($rest=~m/([\:\@\/])(\w+)/g);
my ($sep, $word);
foreach (@d) {
if ($sep) { $word=$_;
#--do stuff with $sep, $word
if ($sep eq ':') { $user=$word }
elsif ($sep eq '@') { $server=$word }
elsif ($sep eq '/') { $srvtype=$word }
#--
undef($sep); #re-init next pair
}
else { $sep=$_; }
} #foreach
} # additional locator info provided
if ($server && $user && ($user eq $DBDEF_USER)) {
$srvtype=$DBDEF_SRV_TYPE unless $srvtype;
my ($shost,$port)=split(/:/,$server);
if (defined($port) && $port>0) { $srvport=$port; $server=$shost; }
return ($server, $user, $DBDEF_PASS, $db, $srvtype, $srvport);
}
if (defined($flag) && $flag =~/ALWAYS/i) {
return (db_askpass($server, $srvtype, $user, $db));
}
my $askflag=($flag=~/\bASK\b/i) if defined($flag);
local *AUTHFILE;
unless (open(AUTHFILE, $authfile)) {
if ($askflag) {
return (&db_askpass($server, $srvtype, $user, $db));
}
$srvtype=$DBDEF_SRV_TYPE unless $srvtype;
$srvtype=lc($srvtype);
$server=$DBDEF_SERVER unless ($server);
my ($shost,$port)=split(/:/,$server);
if ($port>0) { $srvport=$port; $server=$shost; }
$user=$DBDEF_USER;
$pass=$DBDEF_PASS;
return ($server, $user, $pass, $db, $srvtype, $srvport);
}
#locate the server for this database
local $/="\n";
my $auth_section='Authentication';
my $def_section='Default';
my $def_srvtype=$DBDEF_SRV_TYPE;
my $def_server=$DBDEF_SERVER;
my ($section, $section_srvtype, $section_srvhost, $section_srvport); #current section
my %srvauth; # serverID:user => encpass
local $_;
while (<AUTHFILE>) {
s/\s+$//;s/^\s+//;
next unless $_;
next if m/^\s*#/;
if (m/^\s*\[\s*(\w+)(.*?)\]/) { #[section] line
($section, my $section_attr)=($1,$2);
if ($section_attr) {
my @d=($section_attr=~m/([\:\@\/])([\.\w]+)/g);
my ($sep, $word);
foreach (@d) {
if ($sep) { $word=$_;
#--do stuff with $sep, $word
if ($sep eq '@') { $section_srvhost=$word }
elsif ($sep eq '/') { $section_srvtype=$word }
elsif ($sep eq ':') { $section_srvport=$word }
#--
undef($sep); #re-init next pair
}
else { $sep=$_; }
} #foreach
if ($server eq $section) {
$srvtype=$section_srvtype unless $srvtype;
$srvport=$section_srvport unless $srvport;
$srvhost=$section_srvhost unless $srvhost;
}
}
next;
}
#not a "[section]" line
s/[\n\r]+$//s;
if ($section ne $auth_section) {
tr/ //d;
next if ($server && $srvtype);
if ($section eq $def_section) { # [Default] section?
my ($var, $value)=split(/=/);
$var=lc($var);
if ($value) {
if ($var eq 'server') { $def_server = uc($value) }
elsif ($var eq 'server_type') { $def_srvtype = lc($value);
}
}#if value
next;
} #[Default] section parsing
#--
next if $server; #we have the server, no need to search for it
#[server] section line -- parse the databases
my @dbs=split(/[\s\,\;]+/);
foreach my $sdb (@dbs) {
if ($sdb eq $db) {
$server=$section;
$srvhost=$section_srvhost;
$srvtype=$section_srvtype;
$srvport=$section_srvport;
}
}
} #not an auth line
else { #line in authentication section
my ($asrv, $auserpass)=split(/:/,$_,2);
next unless $auserpass;
my ($auser, $apass)=split(/\//, $auserpass, 2);
next unless $apass;
my ($srv, $stype)=split(/\//,$asrv);
$asrv = $stype ? uc($srv).'/'.lc($stype) : uc($asrv);
my $skey=$asrv.':'.$auser;
$srvauth{$skey}=[$apass] unless exists($srvauth{$skey});
# alternate (fall-back) authentication:
$srvauth{$asrv}=[$auser, $apass];
if ($stype) { #server type was provided
$skey=$srv.':'.$auser;
$srvauth{$skey}=[$apass, $stype] unless exists($srvauth{$skey});
#alternate (fall-back) authentication:
$srvauth{$srv}=[$auser, $apass, $stype];
}
}
} # --- while <AUTHFILE>
close(AUTHFILE);
#--
unless ($server) {
$server=$def_server;
my ($shost,$port)=split(/:/,$server);
if ($port>0) { $srvport=$port; $srvhost=$shost; }
}
#$srvtype=$def_srvtype unless $srvtype;
$server=uc($server);
$srvtype=lc($srvtype);
#========> now retrieve the password for this db@server [ / srv_type ]
#======== and if the $user was given, try to retrieve the password
# for that $user and that $server..
# otherwise fall back to $DBDEF_USER/PASS
#VVVVVVVVVVVVVVVVVVVVVVVVVVVV
#$user=$ENV{'USER'} unless $user;
my $srvkey = $server;
#my $srvname= $server;
$server=$srvhost if $srvhost;
my ($encpass, $auth_srvtype);
if ($user) {
my $authd=$srvauth{$srvkey.':'.$user};
$authd=$srvauth{$srvkey.'/'.$srvtype.':'.$user} unless $authd;
$authd=$srvauth{$server.':'.$user} unless $authd;
($encpass, $auth_srvtype)=@$authd if $authd;
}
$srvtype=$auth_srvtype if $auth_srvtype;
unless ($encpass) {
if ($askflag && $user) {
return (&db_askpass($server, $srvtype, $user, $db));
}
#look for any other authentication for this server:
my $alternate=$srvauth{$srvkey};
$alternate=$srvauth{$server} unless $alternate;
if ($alternate) {
($user, $pass)=($$alternate[0], &sdecrypt($$alternate[1],$srvkey));
$srvtype=$$alternate[2] unless $srvtype;
#warn("..Found and returned user '$user' authentication instead.\n");
}
else {
warn("..Returning default user ($DBDEF_USER) authentication instead.\n");
($user, $pass)=($DBDEF_USER, $DBDEF_PASS);
}
$srvtype=$def_srvtype unless $srvtype;
return ($server, $user, $pass, $db, $srvtype, $srvport);
}
#else return the authentication data found
$srvtype=$def_srvtype unless $srvtype;
print STDERR "found server $server of type $srvtype, user $user, pass $encpass\n";
return ($server, $user, &sdecrypt($encpass, $srvkey), $db, $srvtype, $srvport);
}
#=======================================================================
# simple encryption/decryption routine, only offering a very basic
# "protection" against quick naked eye inspection..
#=======================================================================
sub xor_encode {
my ($str, $key) = @_;
$key=lc($key);
$str=reverse($str);
my $enc_str = '';
for my $char (split //, $str){
my $decode = chop $key;
$enc_str .= chr(ord($char) ^ ord($decode));
$key = $decode . $key;
}
return $enc_str;
}
sub __xor_encode {
my ($str, $key) = @_;
$key=lc($key);
$str=reverse($str);
my $enc_str = '';
for my $char (split //, $str){
my $decode = chop $key;
$enc_str .= chr(ord($char) ^ ord($decode));
$key = $decode . $key;
}
return $enc_str;
}
sub scrypt {
my ($pass, $key)=@_;
return encode_base64(xor_encode($pass, $key));
#$seed=lc($seed);
#$pass=reverse($pass).reverse(substr($seed,0,4));
#my $mask = substr($seed x (length($pass)/length($_[0]) + 1), 0, length($pass));
#$mask &= (chr(15) x length($mask));
#return ($pass ^ $mask);
}
sub sdecrypt {
my ($crpass, $key)=@_;
my $s=decode_base64($crpass);
my $decoded=xor_encode(scalar(reverse($s)), $key);
return scalar(reverse($decoded));
#$seed=lc($seed);
#my $mask = substr($seed x (length($crpass)/length($_[0]) + 1), 0, length($crpass));
#$mask &= (chr(15) x length($mask));
#my $pass = ($crpass ^ $mask);
#$pass=substr($pass, 0,length($pass)-length(substr($seed,0,4)));
#return scalar(reverse($pass));
}
sub syb_MsgHandler {
my($err, $sev, $state, $line, $server,
$proc, $msg, $sql, $err_type) = @_;
my @msg = ();
if($err_type eq 'server') {
return 0 if !$err; #this will obliterate useless warning messages
push @msg,
(sprintf('Server Message# %ld, Severity %ld, State %ld, Line %ld',
$err,$sev,$state,$line),
(defined($server) ? "Server '$server' " : '') .
(defined($proc) ? "Procedure '$proc'" : ''),
"Message text: '$msg'");
} else {
push @msg,
(sprintf('Open Client SEVERITY = (%ld) NUMBER = (%ld)',
$sev, $err),
"Message text: $msg");
}
print STDERR join("\n",@msg)."\n";
return 1;
}
#just a fancier exit to be used for fatal errors
#the first string is printed at STDOUT
#the second, if provided, is sent to STDERR
sub dbErrExit {
$dbLastError="@_\n";
print STDERR $_[0]."\n";
exit(1) unless defined($_[1]);
die "$_[1]\n";
}
sub onErrExit {
$dbExitSub=$_[0];
}
=head2 trim(<strings>...)
"in place" trimming of all spaces around each string given as a parameter
The trimmed strings are also returned as a list.
=cut
#--remove spaces at both ends of strings;
sub trim {
foreach (@_) {
s/^\s+//; s/\s+$//;
}
return @_;
}
=head2 cur_status(<text_lines>..)
Simply creates a file called 'current_status' in the current directory
with the <text_lines> written in it.
=cut
sub cur_status {
local *S_FILE;
open(S_FILE, '>current_status');
print S_FILE join("\n",@_);
close S_FILE;
}
#===============================================
#ask_pass([user_prompt]) : string
#-----------------------------------
# Ask for a password at the current STDIN terminal, without displaying
# the keyboard entries
#
sub ask_pass {
my $prompt=shift || "Password:";
my $term = POSIX::Termios->new();
my $stdin=fileno(STDIN);
$term->getattr($stdin);
my $oterm = $term->getlflag();
my $echo = ECHO | ECHOK | ICANON;
# ----- i don't want echo:
$term->setlflag(($oterm & ~$echo));
$term->setattr($stdin, TCSANOW);
# ----- i don't want echo:
print $prompt;
local $_='';
$_=<STDIN>;
chomp;
print "\n";
$term->setlflag($oterm);
$term->setattr($stdin, TCSANOW);
return $_;
}
#=============================================================
#ask_cpass([user_prompt], [pass_char]) : string
#-----------------------------------------------
# Same as above, but every time the user presses a key,
# a mask character (pass_char or '#' by default) is displayed.
# the ERASE key is supported! (backspace/delete)
sub ask_cpass {
my $prompt=shift || "Password:";
my $pc=shift || '#';
my $term = POSIX::Termios->new();
my $stdin=fileno(STDIN);
$term->getattr($stdin);
my $erase = $term->getcc(VERASE);
#this should be 8; if not, enforce it (on axp it's 127 not ?!?);
$erase=8 if ($erase!=8);
my $oterm = $term->getlflag();
my $echo = ECHO | ECHOK | ICANON;
print $prompt;
local $_='';
local $|=1;
my $key='';
for (;;) {
$term->setlflag(($oterm & ~$echo));
$term->setcc(VTIME, 1);
$term->setattr($stdin, TCSANOW);
sysread(STDIN, $key, 1);
$term->setlflag(($oterm & ~$echo));
$term->setcc(VTIME, 0);
$term->setattr($stdin, TCSANOW);
last if $key eq "\n";
if (ord($key)==$erase) {
if (length($_)>0) { #show erase
chop;
print $key,' ',$key; #deal with the terminal display
}
}
elsif (ord($key)>=32) {
#printf $key;
printf $pc;
$_.=$key;
}
}
$term->setlflag($oterm);
$term->setattr($stdin, TCSANOW);
print "\n";
return $_;
}
#returns the server type (postgres/oracle/sybase/mysql) for
#a given dbh
sub db_srvtype {
my $dbhdata=$dbhs{$_[0]};
return $dbhdata ? $$dbhdata[1] : '';
}
=head2 db_login(<server>, <user>, <password>, [<database>[, <srvtype>]])
RETURNS: a database handle (dbh)
if a database name is provided, it is selected as the current database context
If <user> and <password> are undefined or empty, the default read-only
login 'access' account is assumed.
E.g.
db_login('SYBASESRV', undef, undef, 'mydb')
.. will use the common 'access' account to login into SYBASESRV and
use the database 'mydb'
=cut
sub db_login {
my ($server, $user, $pass, $db, $srvtype, $srvport)=@_;
$server=$server.':'.$srvport if ($srvport);
$user=$DBDEF_USER unless $user;
$pass=$DBDEF_PASS unless $pass;
$srvtype=$DBDEF_SRV_TYPE unless $srvtype;
my $dbh;
if ($srvtype eq 'postgres') {
$dbh=postgres('.', $server, $user, $pass, $db); }
elsif ($srvtype eq 'oracle') {
$dbh=oracle('.', $server, $user, $pass, $db); }
elsif ($srvtype eq 'sybase') {
$dbh=sybase('.', $server, $user, $pass, $db); }
elsif ($srvtype eq 'mysql') {
$dbh=mysql('.', $server, $user, $pass, $db); }
else {
die("Error at db_login: invalid server type ('$srvtype')!\n");
}
$db_last_dbh=$dbh;
return $dbh;
}
=head2 db_logout(<dbh>)
Disconnects from the server (if <dbh> is defined)
=cut
sub db_logout {
my $dbh=shift;
if ($dbh) {
$dbh->disconnect();
}
my $dbhdata=$dbhs{$dbh};
if ($dbhdata) {
$$dbhdata[0]=0; #not active
}
}
sub db_lastlogin {
my ($dbh, $dbhdata);
if ($db_last_dbh) {
$dbhdata=$dbhs{$db_last_dbh};
if ($dbhdata) {
my ($server, $user, $pass, $db, $srvtype)=@$dbhdata[1..4];
$dbh=&db_login($server, $user, $pass, $db, $srvtype);
if ($dbh ne $db_last_dbh) {
delete $dbhs{$db_last_dbh};
$db_last_dbh=$dbh;
}
}
}
unless ($dbhdata) {
&$dbExitSub("Error at db_lastlogin: no previous login data found!\n");
}
return $dbh;
}
sub getDate {
my $date=localtime();
#get rid of the day name so Sybase will accept it
(my $wday,$date)=split(/\s+/,$date,2);
return $date;
}
=head2 sql_do(<dbh>, <sql_statement> [, <ignore_failure>])
Simply execute the given sql statement(s) (typically non-select ones
or not returning any result sets back)
The script is terminated if any error code is returned by the server,
unless the <ignore_failure> parameter is defined and non-zero.
=cut
#Expects: <dbh>, <command>, [<error message>]
#Returns: number of rows affected by the command.
sub sql_do {
my $r;
if ($_[2]) { #special case: just print the warning message, don't exit
if ($_[2]) {#quiet!
$r=$_[0]->do($_[1]);
}
else {
$r=$_[0]->do($_[1]) || &flog("sql_do failed at:\n$_[1]\n".$_[0]->errstr.$_[2]);
}
}
else { # blow up if there was an error
$r=$_[0]->do($_[1]) || &$dbExitSub("sql_do failed at:\n$_[1]\n".
$_[0]->errstr);
}
return $r;
}
=head2 sql_exec(<dbhandle>, <sql_query> [, <binding_values>])
RETURNS: a statement handle <sth> for the given query <sql_query>
Prepares and executes the <sql_query> (presumably a select statement -
or even more than one in Sybase). Optional parameter binding values can
be given for every respective parameter or ? character in the <sql_query>.
The returned <sth> can be used later for fetching the query
results in a loop - see sth_fetch()
=cut
#========================================================================
# sql_exec (<db_handle>, <query>, [<binding_params>]): <sth>
# returns a statement handle (sth) for the query;
# this sth can be used for fetching the query results in a loop
#========================================================================
sub sql_exec {
my ($dbh, $query, @params) = @_;
my $sth = $dbh->prepare($query)
|| &$dbExitSub("Prepare failed for \n$query\n$DBI::errstr");
my $rc = $sth->execute(@params)
|| &$dbExitSub("Execute failed for \n$query\n$DBI::errstr");
return $sth;
}
=head2 sql_prepare(<dbh>, <sql_statement> [, <error message>])
RETURNS: a statement handle <sth> for the prepared sql statement.
Prepares an sql statement to the server. The statement is NOT executed,
so <sth> cannot be used for fetching the results immediately.
The typical use case for this is to have a dynamic <sql_statement>
(i.e. a statement with binding parameters) prepared only once, and then to
repeatedly call sth_exec() with various parameter values (e.g. scanning a
list of values), with a sth_fetch() session for each sth_exec(), like this:
my $sth = sql_prepare($dbh, 'select name, date from orders where val=? and id=?');
# assume @v is a list of [$val, $id]
foreach my $d (@v) {
sth_exec($sth, @$d);
while (my $rowref = sth_fetch($sth)) {
my ($name, $date)=@$rowref;
#.. do something with the resulting row values
#...
} # result row fetching loop
} # parameter value binding loop
=cut
sub sql_prepare { #expects: <dbh>, <query>, [<error message>]
#returns statement handle
my $sth=$_[0]->prepare($_[1]) ||
&$dbExitSub("Error preparing:\n $_[1]\n".$_[2]."\n".$_[0]->errstr);
return $sth;
}
=head2 sql_get_all(<dbh>, <query>);
#Execute a query and returns ALL the results as reference to an array
# of references to field value lists
=cut
sub sql_get_all {
my ($dbh, $query)=@_;
my $aref=$dbh->selectall_arrayref($query)
|| &$dbExitSub("Select all failed for:\n$query");
return $aref;
}
=head2 sth_exec(<sth>[, <binding_values>..])
Executes a previously prepared statement.
RETURNS: the number of rows affected (according to DBI specs,
but not all DBMSs can live up to it)
=cut
sub sth_exec {
my $sth=shift;
my $rc = $sth->execute(@_)
|| &$dbExitSub("*** sth_exec failed:\n$DBI::errstr");
return $rc ;
# according to DBI specs, this should be the number of rows affected,
# or -1 if unknown
}
=head2 sth_fetch(<sth>)
RETURNS: an array reference to a list of all values in a row of the result set.
<sth> is a statement handle for an already EXECUTED sth statement (not just prepared).
This is meant to be used in a loop.
Typical use:
my $sth=&sql_exec($dbh, $sql_query);
while (my $r=sth_fetch($sth)) { #while rows are returned..
#..
#do something with @$r ,which is the list of values for each field in a result row
#..
}
=cut
sub sth_fetch {
my $sth=shift;
my $r=$sth->fetch();
&sth_checkErr($sth) unless ($r);
return $r;
}
=head2 sth_afetch(<sth>)
RETURNS: an array of field values for a row in the result set
Same as sth_fetch() but returns an array instead of a reference to an array.
=cut
sub sth_afetch {
my $sth=shift;
my $r=$sth->fetch();
&sth_checkErr($sth) unless ($r);
return defined($r)?(@$r):(); #returns a copy of referenced array
}
sub sth_checkErr {
my $err=$_[0]->errstr;
&$dbExitSub("*** fetch() failed :\n$err\n") if $err;
}
=head2 sql_get_value($dbh, $sql_query)
RETURNS:
(in scalar context): the first field of the first row in the result set
(in array context) : the values in the first row in the result set
It is meant for 'select count() ..' queries or other aggregate
queries or any other queries expected to return a result set with
only one row.
=cut
sub sql_get_value { #single row/value return from a simple SELECT
my ($dbh, $sql)=@_;
my $sth=&sql_exec($dbh, $sql);
my $r=&sth_fetch($sth);
$r=[undef] unless $r;
$sth->cancel(); #not all DBDs can actually do this
undef($sth); #hopefully destroying the $sth will cancel it anyway..
if (wantarray()) {
return @$r;
}
else {
return $$r[0];
}
}
=head2 sql_get_values($dbh, $sql_query)
Same as sql_get_value() but enforces a list context
(i.e. returns a LIST of field values for the first returned row)
=cut
sub sql_get_values {
my @r=&sql_get_value(@_);
return @r;
}
sub syb_dboalias {
my $r=&sql_get_value($_[0],
'select suid from sysalternates where suid=suser_id()');
return $r;
}
=head2 confirm(<prompt>)
displays an yes/no prompt waiting for user response
RETURNS: 1 if user chooses 'yes' or 'y', 0 otherwise