-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryBroker.pl
More file actions
executable file
·1999 lines (1603 loc) · 61.2 KB
/
QueryBroker.pl
File metadata and controls
executable file
·1999 lines (1603 loc) · 61.2 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
#!/usr/bin/env perl
#
# Author: Floyd Moore (floyd.moore\@hp.com)
# $HeadURL: file:///var/lib/svn/repository/projects/metrics/trunk/QueryBroker/QueryBroker.pl $
# $Revision: 198 $
# $Date: 2009-10-09 14:00:29 -0700 (Fri, 09 Oct 2009) $
# Description:
# Submit a generic SQL query to a specified database server and
# save the results to a file. Implement queries to be placed
# into an aux file and not have to edit the script to change
# the query parameters.
#
#
package QueryBroker;
use strict;
use warnings;
use 5.010;
# General Modules
use Carp qw( croak carp );
use English qw( -no_match_vars );
use File::Basename qw( basename );
use Pod::Usage qw( pod2usage );
use Readonly;
use Getopt::Long;
use File::Spec::Functions;
use Module::Load;
use Digest::MD5 qw(md5 md5_hex);
use Date::Manip;
use Date::Manip::Date;
# Program Specific Modules
use Config::General;
use DBI qw(:sql_types);
use POSIX qw(strftime);
use Text::ASCIITable;
use Text::CSV;
use YAML::Dumper;
use YAML;
use JSON;
use Email::Sender::Simple qw(sendmail);
use Email::Simple;
use Email::Simple::Creator;
# Define output mode types:
use constant {
CSV => 0,
TABLE => 1,
PERL => 2,
YAML => 3,
JSON => 4,
};
# I seem to use this a million times when I am diagnosing the failures
# in my data structures and to make it easier to see what actual data
# the internal routines are seeing. The indent thing is a personal
# preference
use Data::Dumper;
local $Data::Dumper::Indent = 1;
# setup general information
our $RUNDATE = strftime '%Y/%m/%d %H:%M:%S', localtime;
our $VERSION = 198;
Readonly my $PROGNAME => basename $PROGRAM_NAME;
# create a local timestamp so that it doesn't change within each
# query. The 'space' character ' ' causes problems to the joining
# of the fields.
my $report_start_time = strftime '%Y-%m-%d_%H:%M:%S', localtime;
#-----
# Global variables:
# I know defining these globals and not setting them here causes Perl::Critic
# to have fits, but I prefer (especially when I have strict mode on) to
# predefine my global varaibles early in my code. It lets me see which
# variables *should* be global and try to minimize them. Also it isn't
# easy to create an initializor for an empty hash like %config.
#-----
our ( $append_mode, $VERBOSE, $DEBUG, %config, $input_query_file );
our ( $input_outfile, $input_sql, $input_sqlfile );
our ( $input_query_name, $check_mode, $list_queries, $shorten_long_fields );
our ( $input_mode, @input_replace_vars, $input_dbsel, %replace_vars );
our ( %Database, %Queries, $Rows, $no_report_headers );
my $OUTFH;
#
# Parse the command line:
# I prefer to DRY out the command line stuff to the Getopt module instead
# of writing my own. I also like the way I can write a nicely formatted
# specification for the command line variables.
#
sub parse_cmdline {
Getopt::Long::Configure('bundling');
my %options_list = (
'out|outfile|output=s' => \$input_outfile, # file to write output
'append|append_mode' =>
\$append_mode, # append to a file instead of opening a new one
'query_file|qf=s' =>
\$input_query_file, # file containing the query information
'mode=s' => \$input_mode, # alternate method to set output mode
'query|queryname|qn=s' =>
\$input_query_name, # specifiy which query in the file to run
'list_queries|list' =>
\$list_queries, # dump a list of all defined databases and queries
'check' =>
\$check_mode, # check the database and options, don't run the query
'shorten:i' => \$shorten_long_fields
, # shorted long message strings sent to the console
'var|vars=s@' => \@input_replace_vars
, # string to be used for variable substitution in SQL
'no_header' => \$no_report_headers
, # flag to indicate that the user does not want headers in the report
# Ad-Hoc query definition
'db=s' => \$input_dbsel, # which database (from the queryfile) to access
'sql=s' => \$input_sql, # the raw SQL to use for the query
'sqlfile=s' => \$input_sqlfile, # file containing SQL commands not in defs.
# Standard gnu like meta-options
'help|?' => sub { pod2usage(1); },
'man' => sub { pod2usage( -exitstatus => 0, -verbose => 2 ); },
'version' => sub { command_version(); },
'usage' => sub { pod2usage( -verbose => 0 ); },
'verbose|v' => \$VERBOSE,
'debug|x' => \$DEBUG,
);
my $options_okay = GetOptions(%options_list);
# Fail if unknown arguemnts encountered...
pod2usage(2) if !$options_okay;
# you need to either use a direct 'sql' query or specify one from
# the query file
if ( !defined $input_query_name
&& !defined $input_sql
&& !defined $input_sqlfile
&& !defined $list_queries )
{
die
"Either a query name from the query file, or a direct SQL query must be specified\n";
}
# preprocess the variable substitution list
# allow both multiple --var(s) options and a comma separated list
if (@input_replace_vars) {
@input_replace_vars = split /,/sxm, join q{,}, @input_replace_vars;
if ( !defined $input_query_name ) {
die
"You need to use a predefined query from the query file to use variable substitution\n";
}
for my $var (@input_replace_vars) {
my ( $name, $value ) = split /=/sxm, $var, 2;
$VERBOSE && print " ... var: $name = $value\n";
$replace_vars{$name} = $value;
}
}
# check the output file to make sure we can write to it.
if ( defined $input_outfile ) {
if ( $input_outfile ne q{-} ) {
if ( defined $append_mode ) {
open $OUTFH, '>>', $input_outfile
or die
"Cannot append to the output file $input_outfile for writing\n";
}
else {
open $OUTFH, '>', $input_outfile
or die
"Cannot open the output file $input_outfile for writing\n";
}
close $OUTFH
or die "Bad close to starting check of output file: $ERRNO\n";
}
}
# tell people who we are...
$VERBOSE && print "# $PROGNAME $VERSION\t\t$RUNDATE\n\n";
return;
}
#
# print the program version and return. Only called by the command line parser
#
sub command_version {
# simply print the version number of the script
print "$PROGNAME Revision $VERSION\n";
exit 0;
}
#
# load_and_parse_config_file():
# This is a general loader that uses the Config::General module to grab a bunch of
# definitions from a file and load it into a structure. I use this method alot in
# my scripts to make config files easier to read and safer to load (I don't
# have to use any 'eval's to load the file into a structure.
#
sub _load_and_parse_config_file {
my $filename = shift;
my $cfgfile;
my $buffer;
open $cfgfile, '<', $filename
or die "Cannot open config file $filename for reading: $ERRNO\n";
while (<$cfgfile>) {
if (/^ [#] /sxm) {
next;
}
$buffer .= $_;
}
close $cfgfile
or die "Bad close of config file.\n";
#print "Buffer: \n$buffer\n";
if ( !defined $buffer ) {
die "Error: empty config file: $filename\n";
}
$buffer =~ s/;\n/\n/gsxm;
my $parsebuffer = Config::General->new( -String => $buffer, );
my %hash = $parsebuffer->getall;
return %hash;
}
# _set_output_handle {
# helper routine to se an output filehandle based on if the use has requested
# a seperate output file or just wants stuff sent to the screen.
sub _set_output_handle {
my $_outfile = shift;
if ( defined $_outfile ) {
my $file_mode;
if ( defined $append_mode ) {
$file_mode = '>>';
}
else {
$file_mode = '>';
}
open $OUTFH, $file_mode, $_outfile
or die "Cannot open the output file $_outfile for writing\n";
}
else {
$OUTFH = \*STDOUT;
}
return $OUTFH;
}
#
# shorten an ascii message to a shorter length more suitable for printing in long
# column contents (like descriptions) directed to a screen instead of to a file.
sub shorten_message {
my $msg = shift;
my $MAXLEN = shift;
Readonly my $DEFAULT_MAXIMUM_LENGTH => 20;
if ( !defined $msg ) {
return 1;
}
if ( !defined $MAXLEN ) {
$MAXLEN = $DEFAULT_MAXIMUM_LENGTH;
}
if ( ( my $idx = index $msg, "\n" ) > 0 ) {
$msg = substr $msg, 0, $idx - 1;
}
if ( length($msg) > $MAXLEN ) {
$msg = substr $msg, 0, $MAXLEN;
$msg .= '...';
}
return $msg;
}
#
# ---------------------------------------------------
# Handle special alert messages or other triggers
# ---------------------------------------------------
#
# email a message to a user if a metric runs out of process. This will be used to
# trip a warning by email if for instance the query time for a given request goes
# beyond a given limit. These alerts will have to be configured in the control file
#
sub check_alerts {
my $query_name = shift;
my @table_array = @{$Rows};
my @headers;
#@headers = setup_table_headers( $query_name, \@headers );
if ( !exists $Queries{$query_name}->{alert} ) {
return 1;
}
my $alert_column = $Queries{$query_name}->{alert}->{column};
my $alert_limit = $Queries{$query_name}->{alert}->{limit};
my $alert_email = $Queries{$query_name}->{alert}->{email};
my $alert_date = `date`;
$VERBOSE
&& print Data::Dumper->Dump( [ \@table_array ], ['*table_array'] );
if ( !exists $table_array[-1]->{$alert_column} ) {
die "Can't find alert column in data rows\n";
}
my $value = 0;
$value = $table_array[-1]->{$alert_column};
$VERBOSE
&& print "$alert_column: Value = "
. $table_array[-1]->{$alert_column} . "\n";
my $email;
if ( $value == 0 ) {
$email = Email::Simple->create(
header => [
To => "Alert Email <$alert_email>",
From => '"Floyd Moore Workstation" <floyd.moore@hp.com>',
Subject => "Query returnning Zero! $alert_column",
],
body =>
"Date: $alert_date\nQuery Time is Zero!!! We have found a zero time for the test query $query_name: $alert_column = $value\n",
);
sendmail($email);
print
"Query Time is Zero!!! We have found a zero time for the test query $query_name: $alert_column = $value\n",
}
elsif ( $value > $alert_limit ) {
$email = Email::Simple->create(
header => [
To => "Alert Email <$alert_email>",
From => '"Floyd Moore Workstation" <floyd.moore@hp.com>',
Subject => "Query Limit Reached $alert_column",
],
body =>
"Date: $alert_date\nLIMIT!!! We have exceeded the alert limit for $query_name: $alert_column = $value, limit = $alert_limit\nhttps://tableau-dev.corp.hpicorp.net/#/site/HPI/views/ProductionVerticaMonitor/PrdVerticaMonitor?:iid=1\n",
);
sendmail($email);
print
"LIMIT!!! We have exceeded the alert limit for $query_name: $alert_column = $value, limit = $alert_limit\n";
}
return 1;
}
sub connect_alert {
my $query_name = shift;
print " ... connect_alert : $query_name\n";
if ( !exists $Queries{$query_name}->{alert} ) {
return 1;
}
my $alert_column = $Queries{$query_name}->{alert}->{column};
my $alert_limit = $Queries{$query_name}->{alert}->{limit};
my $alert_email = $Queries{$query_name}->{alert}->{email};
my $alert_date = `date`;
my $email;
$email = Email::Simple->create(
header => [
To => "Alert Email <$alert_email>",
From => '"Floyd Moore Workstation" <floyd.moore@hp.com>',
Subject => "Query returnning Zero! $alert_column",
],
body =>
"Date: $alert_date\nQuery Time is Zero!!! We have found a zero time for the test query $query_name: $alert_column\n",
);
sendmail($email);
print
"Query Time is Zero!!! We have found a zero time for the test query $query_name: $alert_column\n",
return 1;
}
# ------------------------------------------------------------------
# Script Section: Load the query information from a file.
# ------------------------------------------------------------------
#
# Load the query information from a file.
# This file is the power of the script and so I wanted to keep the format as flexible as
# possible. I used the Config::General module before and it should would well here.
# There are currently two separate section in the file: the database definitions, and the
# actual query definitions. There will be a sepeate POD section to describe the file format.
# In the end there will be 2 hashes defined: Databases{} with database information, and
# Queries{} that hold the query infomation.
sub _check_db_defs {
# check the database definitions
for my $dblist ( keys %Database ) {
$VERBOSE && print " checking database entry... $dblist\n";
if ( !exists $Database{$dblist}->{connect_string} ) {
die
"Database definition \'$dblist\' does not have a connect string\n";
}
$Database{$dblist}->{connect_string} =~ s/\'//sxmg;
if ( $Database{$dblist}->{connect_string} !~ /^\'?dbi:\S+:/ismx ) {
die
"Database defintion $dblist has a badly formatted connect string: $Database{$dblist}->{connect_string}\n";
}
my $db_adapter = $Database{$dblist}->{connect_string};
$db_adapter =~ s/^\'?dbi://isxm;
$db_adapter =~ s/:.*$//isxm;
#eval "use DBD::$db_adapter";
#croak "ERROR: Database adapter module DBD::$db_adapter not found in path"
# if $EVAL_ERROR;
my $module = "DBD::$db_adapter";
load $module;
}
return 1;
}
sub _check_all_query_mode {
my $ret = TABLE;
for my $qname ( keys %Queries ) {
my $_mode = $Queries{$qname}->{mode};
$ret = _check_query_mode($_mode);
$Queries{$qname}->{mode} = $ret;
}
return 1;
}
sub _check_query_mode {
my $_mode = shift;
my $ret = TABLE;
if ($_mode =~ /perl/isxm) {
$ret = PERL;
} elsif ($_mode =~ /csv/isxm) {
$ret = CSV;
} elsif ($_mode =~ /json/isxm) {
$ret = JSON;
} elsif ($_mode =~ /yaml/isxm) {
$ret = YAML;
} else {
# default mode is table
$ret = TABLE;
}
return $ret;
}
#
# set the file output mode by looking at the 'mode' setting in the query definition
#
sub set_output_mode_by_defn {
my $query_name = shift;
if (defined $input_mode){
my $ret = _check_query_mode($input_mode);
$input_mode = $ret;
}
# set output mode in the query based on the command line if it isn't set already
# in the definition
# Command Line takes precidence over Definition and that over the default table
# mode
if ( exists $Queries{$query_name}->{mode} ) {
if ( defined $input_mode )
{
# mode defined in query definition but command line mode set ->
# use command line
$Queries{ $query_name }->{mode} = $input_mode;
}
} else {
# mode not defined in query definition use command line or default
if ( defined $input_mode ) {
$Queries{ $query_name }->{mode} = $input_mode;
} else {
# default output mode is a table
$Queries{ $query_name }->{mode} = TABLE;
}
}
return 1;
}
#
# special case function to verify that for a report querty (a query that contains multiple
# simple queries that get joined together by a given field) all the required information is
# present and looks sane. This way I don't have to do it later.
#
sub _check_report_queries {
my $qname = shift;
#
# strictly speaking this isn't a 'check' type of thing. However, it is the most
# convientient place to take care of defining these variables.
# We need to add an index column to the report dimensions if this is set up as
# an 'autoindex' type of report.
#
if ( exists $Queries{$qname}->{index}
&& !exists $Queries{$qname}->{dimensions} )
{
$Queries{$qname}->{dimensions} = 'index';
if ( exists( $Queries{$qname}->{facts} ) ) {
$Queries{$qname}->{facts} .= ' index';
}
else {
$Queries{$qname}->{facts} = ' index';
}
}
#
# check if the report definition contains the required dimensions and fact entries.
# All reports need at a minumum a single fact column (how the query results are joined)
# and some report dimensions (what fields are to be carried forward to the report output)
#
if ( !exists $Queries{$qname}->{dimensions} ) {
die
"A report must define the 'dimensions' (table headings used in the report) for the report\n";
}
if ( !exists $Queries{$qname}->{facts} ) {
die
"A report must define the 'facts' (heading that join the various queries) for the report\n";
}
#my @sql_list = @{$Queries{$qname}->{sql}};
#for my $sql (@sql_list){
# print "report sql = $sql\n";
#}
}
#
# Verify that the query definitions are sane.
#
sub _check_query_defs {
my $query_index;
for my $qname ( keys %Queries ) {
$VERBOSE && print " checking query... $qname\n";
if ( !exists $Queries{$qname}->{sql} &&
!exists $Queries{$qname}->{sqlfile} ) {
die
"The query $qname definition must contain at least one sql query!\n";
}
if ( !exists $Queries{$qname}->{database} ) {
die "The query $qname needs a database definition!\n";
}
if ( !exists $Database{ $Queries{$qname}->{database} } ) {
die
"The database $Queries{$qname}->{database} used in query $qname not defined in database list\n";
}
if ( ref( $Queries{$qname}->{sql} ) eq 'ARRAY' ) {
_check_report_queries($qname);
}
if ( !exists $Queries{$qname}->{mode} ) {
set_output_mode_by_defn($qname);
}
}
# need to see if the queries list is empty!
if ( !%Queries ) {
croak
"ERROR: Query 'No Query could not be found in definitions file.\n";
}
return 1;
}
#
# Load the query information from a file.
# This file is the power of the script and so I wanted to keep the format as flexible as
# possible. I used the Config::General module before and it should would well here.
# There are currently two separate section in the file: the database definitions, and the
# actual query definitions. There will be a sepeate POD section to describe the file format.
# In the end there will be 2 hashes defined: Databases{} with database information, and
# Queries{} that hold the query infomation.
#
sub load_query_definitions {
my $buffer;
my $query_file;
if ( defined $input_query_file ) {
$query_file = $input_query_file;
}
else {
die "No query definitions specified\n";
}
my %hash = _load_and_parse_config_file($query_file);
%Database = %{ $hash{database} };
%Queries = %{ $hash{queries} };
_check_db_defs();
_check_query_defs();
_check_all_query_mode();
if ( defined $list_queries ) {
list_queries();
exit 0;
}
#print Data::Dumper->Dump( [ \%Queries ], ['*Queries'] );
return 1;
}
#
# simple routine to just list out the queries defined in the query
# file.
#
sub list_queries {
print "Databases Defined:\n";
for my $dblist ( keys %Database ) {
print " $dblist\n";
}
print "Queries Defined:\n";
for my $qname ( keys %Queries ) {
print " \'$qname\'\n";
}
return 1;
}
#
# routine to do a variable substitution on the query to replace variables
# that might need to change from run to run (like a date)
#
sub process_replace_vars {
my $query_name = shift;
# check the variable substitution names versus the names in the query file
if ( !exists $Queries{$query_name}->{var} ) {
return 1;
}
if (%replace_vars) {
$VERBOSE && print "Check substitution variables...\n";
my %varlist = %{ $Queries{$query_name}->{var} };
for my $check_var ( keys %replace_vars ) {
$VERBOSE
&& print "check var $check_var against Queries list...\n";
if ( !exists $varlist{$check_var} ) {
die
"The variable $check_var does not exist in the $query_name query\n";
}
# add a special rule to allow the replacement of a variable called 'today' with
# a formatted date/time string suitable for inclusion in a database.
if ( $replace_vars{$check_var} =~ /\'today\'/ismx ) {
# find out the type of database we are connecting to...
my $dba =
$Database{ $Queries{$query_name}->{database} }->{adapter};
# print "process a 'today' replacements for database $dba\n";
if ( $dba =~ /Oracle/ismx ) {
my $ora_today = strftime '%d-%b-%Y', localtime;
$replace_vars{$check_var} = q{'} . $ora_today . q{'};
}
}
$Queries{$query_name}->{var}{$check_var} =
$replace_vars{$check_var};
}
}
return 1;
}
#
# set an array of headings used for outputs
#
sub setup_table_headers {
my $query_name = shift;
my $header_ref = shift;
my %header_map;
my @headers = @{$header_ref};
my @table_array = @{$Rows};
#print "setup_table_headers...\n";
#print Data::Dumper->Dump( [ \@table_array ], ['*table_array'] );
foreach my $col ( keys %{ $table_array[0] } ) {
push @headers, $col;
$header_map{$col} = 1;
$VERBOSE && print "Header map: '$col'\n";
}
if ( defined $query_name ) {
#print "... query_name defined: $query_name\n";
if ( exists $Queries{$query_name}->{order} ) {
undef @headers;
my @order = split /\s+/sxm, $Queries{$query_name}->{order};
#print "in order clause of setup_headers: ", join(" ", @order), "\n";
for my $hdr (@order) {
$VERBOSE && print "Header Order: '$hdr'\n";
if ( $hdr =~ /\%SKIP=(\d+)\%/sxm ) {
my $skip = $1;
if ( $Queries{$query_name}->{mode} = CSV ) {
next;
}
# in prep of handling skipped/blank fields in reports
#print " ... process skip $skip in setup_table_headers\n";
for my $skip_count ( 1 .. $skip ) {
push @headers, q{};
}
next;
}
if ( !exists $header_map{$hdr} ) {
die "No row header that matches order heading $hdr\n";
}
else {
delete $header_map{$hdr};
}
push @headers, $hdr;
}
$VERBOSE
&& print
"Left over items in the fact list not in the order list\n";
for my $nm ( keys %header_map ) {
$VERBOSE && print " ... $nm\n";
push @headers, $nm;
}
}
}
return @headers;
}
#
# Dump an ascii formatted table from the database output.
# ascii formatted tables from the database information.
#
sub write_formatted_table {
my $query_name = shift;
my $_outfile = shift;
my $table = Text::ASCIITable->new();
my @headers;
my @table_array = @{$Rows};
@headers = setup_table_headers( $query_name, \@headers );
$table->setCols(@headers);
for my $row (@table_array) {
my @varray;
for my $j (@headers) {
my $value = $row->{$j};
if ( !defined $_outfile
&& $j =~ /description|request_reason|_comment/isxm )
{
$value = shorten_message( $value, $shorten_long_fields );
}
if ( defined $value ) {
# testing a fix to remove extra Win32 newlines from the output
$value =~ s/\015\n*//gsxm;
}
push @varray, $value;
}
$table->addRow(@varray);
undef @varray;
}
$OUTFH = _set_output_handle($_outfile);
print {$OUTFH} $table;
undef $table;
close $OUTFH
|| die "Cannot close output file $_outfile\n";
undef $OUTFH;
return 1;
}
#
# All parts of the method to output a CSV formatted table. It includes a couple
# of helper methods as well.
#
# combine array fields into a csv string
sub _csv_combine {
my $csv = shift;
my $array_ref = shift;
my @array = @{$array_ref};
my $hdrstatus = $csv->combine(@array);
my $hdrline = $csv->string();
if ( !defined $hdrline ) {
die 'Bad CSV combine: ' . $csv->error_diag() . "\n";
}
return $hdrline;
}
# combine array of arrays fields into a csv string
sub _csv_aofa_combine {
my $csv = shift;
my $array_ref = shift;
my @array = @{$array_ref};
#print Data::Dumper->Dump( [ \@array ], ['*array'] );
my $long_line = q{};
for my $i (@array) {
my @line = @{$i};
my $output_line = _csv_combine( $csv, \@line );
$long_line .= $output_line . "\n";
}
return $long_line;
}
# write the csv file
sub write_csv_file {
my $query_name = shift;
my $_outfile = shift;
my @headers;
my @lines_array;
my @table_array = @{$Rows};
@headers = setup_table_headers( $query_name, \@headers );
my $csv = Text::CSV->new( { binary => 1 } );
# print headers
my $hdrstatus = $csv->combine(@headers);
my $hdrline = $csv->string();
if ( !defined $hdrline ) {
die 'bad CSV combine: ' . $csv->error_input() . "\n";
}
# print each row in the table
for my $row (@table_array) {
my @varray;
for my $j (@headers) {
my $value = $row->{$j};
if ( defined $value ) {
$value =~ s/\015\n*//gsxm;
}
push @varray, $value;
}
push @lines_array, [@varray];
undef @varray;
}
my $outlines = _csv_aofa_combine( $csv, \@lines_array );
$OUTFH = _set_output_handle($_outfile);
print {$OUTFH} "$hdrline\n" if ( !$no_report_headers && !$append_mode );
print {$OUTFH} "$outlines";
close $OUTFH
|| die "Cannot close output file $_outfile\n";
undef $OUTFH;
return 1;
}
#
# perl Data::Dumper output mode
#
sub write_struct_file {
my $query_name = shift;
my $_outfile = shift;
$OUTFH = _set_output_handle($_outfile);
print {$OUTFH} Data::Dumper->Dump( [ \$Rows ], ['*Rows'] );
close $OUTFH
|| die "Cannot close output file $_outfile\n";
undef $OUTFH;
return 1;
}
#
# yml output mode
#
sub write_yaml_file {
my $query_name = shift;
my $_outfile = shift;
my @table_array = @{$Rows};
my $dumper = YAML::Dumper->new;
$dumper->indent_width(4);
$OUTFH = _set_output_handle($_outfile);
print {$OUTFH} $dumper->dump(@table_array);
close $OUTFH
|| die "Cannot close output file $_outfile\n";
undef $OUTFH;
return 1;
}
#
# json output mode
#
sub write_json_file {
my $query_name = shift;
my $_outfile = shift;
my @table_array = @{$Rows};
$OUTFH = _set_output_handle($_outfile);
my $json_text = to_json( $Rows, { ascii => 1} );
print {$OUTFH} "$json_text\n";
close $OUTFH
|| die "Cannot close output file $_outfile\n";
undef $OUTFH;
return 1;
}
#
# create a connection to the database
#
sub connect_to_db {
my $query_name = shift;
my $db_string = $Queries{$query_name}->{database};
if ( !$db_string ) {
die "DB string not defined in configuration\n";
}
if ( !exists $Database{$db_string} ) {
die "Cannot find database $db_string in configuration\n";
}
if ( !exists $Database{$db_string}->{connect_string} ) {
die "No connect string defined in database: $db_string\n";
}
my $connect_string = $Database{$db_string}->{connect_string};
$connect_string =~ s/\'//sxmg;
# allow for no user or password setting for database.
my $user;
if ( exists $Database{$db_string}->{user} ) {
$user = $Database{$db_string}->{user};
$user =~ s/\'//sxmg;
}
else {
$user = undef;
#$user = q{};
}
my $password;
if ( exists $Database{$db_string}->{password} ) {
$password = $Database{$db_string}->{password};
$password =~ s/\'//sxmg;
}
else {
$password = undef;
#$password = q{};
}
# review the sql query specified and replace interpolated variables
# and the date/time query information for an Oracle database.
# the return will be a string or and error.
my %db_options = ( RaiseError => 1, AutoCommit => 0 );
if ( exists $Database{$db_string}->{mode} ) {
if ( $Database{$db_string}->{mode} =~ /read-?only/ismx ) {
$db_options{ReadOnly} = 1;
}
else {
warn