SAL/DBI.pm untested

filter: Statementstmt 0.0% 0 / 214 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 72 MC/DCmcdc 0.0% 0 / 41 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 385 CC 8 SCAR 23.3
CC
8
Cov
0%
_get_labels
42.0
destruct
6.0
_extract_table
6.0
CRAP 10.3
1 package SAL::DBI;
2  
3 # This module is licensed under the FDL (Free Document License)
4 # The complete license text can be found at http://www.gnu.org/copyleft/fdl.html
5 # Contains excerpts from various man pages, tutorials and books on perl
6 # DBI ABSTRACTION
7  
8 use strict;
9 use DBI;
10 use Carp;
11  
12 BEGIN {
13 use Exporter ();
14 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
15 $VERSION = '3.03';
16 @ISA = qw(Exporter);
17 @EXPORT = qw();
18 %EXPORT_TAGS = ();
19 @EXPORT_OK = qw();
20 }
21 our @EXPORT_OK;
22  
23 END { }
24  
25 =pod
26  
27 =head1 Name
28  
29 SAL::DBI - Database abstraction for SAL
30  
31 =head1 Synopsis
32  
33 use SAL::DBI;
34  
35 my $dbo_factory = new SAL::DBI;
36 my $dbo_sqlite = $dbo_factory->spawn_sqlite($filename);
37 my $dbo_mysql = $dbo_factory->spawn_mysql($server, $user, $pass, $database);
38 my $dbo_odbc = $dbo_factory->spawn_odbc($dsn, $user, $pass);
39 my $dbo_temp = $dbo_factory->spawn_sqlite(':memory:');
40  
41 # SQL Queries
42 my $rv = $dbo_temp->do(qq|CREATE TABLE SomeTable(some_column varchar(255), some_other_column varchar(255))|);
43 my ($w, $h) = $dbo_temp->execute('SELECT * FROM SomeTable WHERE some_column=?', $somevalue);
44  
45 # Processing Records
46 for (my $i=0; $i<=$h; $i++) {
47 # Accessing the data directly...
48 my $field_0 = $dbo_temp->{data}->[$i][0];
49 my $field_1 = $dbo_temp->{data}->[$i][1];
50  
51 # Grab the fields as a list
52 my @record = $dbo_temp->get_row($i);
53 }
54  
55 # Processing entire columns
56 for (my $i=0; $i<$w; $i++) {
57 my @column = $dbo_temp->get_column($i);
58 # do something with the data...
59 }
60  
61 =head1 Eponymous Hash
62  
63 This section describes some useful items in the SAL::DBI eponymous hash. Arrow syntax is used here for readability,
64 but is not strictly required.
65  
66 Note: Replace $SAL::DBI with the name of your database object... eg. $dbo_temp->{connection}->{dbh}
67  
68 =over 1
69  
70 =item Connection Information
71  
72 $SAL::DBI->{connection}->{dbh} contains the DBI database handle.
73 $SAL::DBI->{connection}->{sth} contains the DBI statement handle.
74  
75 =item Formatting Control
76  
77 $SAL::DBI->{fields}->[$col]{name} contains the name of the field. (an alias for {fields}{label})
78 $SAL::DBI->{fields}->[$col]{label} contains the name of the field. (an alias for {fields}{name})
79 $SAL::DBI->{fields}->[$col]{type} contains the datatype for the field
80 $SAL::DBI->{fields}->[$col]{visible} contains the visibility status flag for this field
81 $SAL::DBI->{fields}->[$col]{writeable} contains a write-access flag. (Use to indicate field is locked in your apps.)
82 $SAL::DBI->{fields}->[$col]{css} contains a CSS string for displaying this field on the web
83 $SAL::DBI->{fields}->[$col]{precision} is used to specify the number of digits to the right of a decimail place.
84 $SAL::DBI->{fields}->[$col]{commify} is used to force commas in numbers > 999
85 $SAL::DBI->{fields}->[$col]{align} is used for aligning the contents of the field (usually for the web). Default is 'left';
86 $SAL::DBI->{fields}->[$col]{prefix} is used to prepend a string to the contents of any data in this column.
87 $SAL::DBI->{fields}->[$col]{postfix} is used to append a string to the contents of any data in this column.
88  
89 =item The Dataset
90  
91 $SAL::DBI->{data}->[$y][$x] is used to access a returned dataset as if it were a two-dimensional array.
92 (Yes, I'm lazy. ;-)
93  
94 =back
95  
96 =cut
97  
98 our %DBI = (
99 ######################################
100 'connection' => {
101 # Shared
102 'type' => '',
103 'dbh' => '',
104 'sth' => '',
105 'user' => '',
106 'passwd' => '',
107 # For MySQL
108 'server' => '',
109 'database' => '',
110 # For ODBC
111 'dsn' => '',
112 # For SQLite
113 'dbfile' => ''
114 },
115 ######################################
116 'fields' => (
117 {
118 'name' => '',
119 'label' => '',
120 'type' => '',
121 'visible' => '',
122 'header' => '',
123 'writeable' => '',
124 'css' => '',
125 'precision' => '',
126 'commify' => '',
127 'align' => '',
128 'prefix' => '',
129 'postfix' => '',
130 }
131 ),
132 ######################################
133 'data' => [],
134 ######################################
135 'internal' => {
136 'width' => '',
137 'height' => '',
138 },
139 ######################################
140 );
141  
142 # Setup accessors via closure (from perltooc manpage)
143 sub _classobj {
144 my $obclass = shift || __PACKAGE__;
145 my $class = ref($obclass) || $obclass;
146 no strict "refs";
147 return \%$class;
148 }
149  
150 for my $datum (keys %{ _classobj() }) {
151 no strict "refs";
152 *$datum = sub {
153 my $self = shift->_classobj();
154 $self->{$datum} = shift if @_;
155 return $self->{$datum};
156 }
157 }
158  
159 ##########################################################################################################################
160 # Constructors (Public)
161  
162 =pod
163  
164 =head1 Constructors
165  
166 =head2 new()
167  
168 Builds a basic factory object. Used for spawning database objects.
169  
170 =cut
171  
172 sub new {
173 my $obclass = shift || __PACKAGE__;
174 my $class = ref($obclass) || $obclass;
175 my $self = {};
176  
177 bless($self, $class);
178  
179 return $self;
180 }
181  
182 =pod
183  
184 =head2 spawn_mysql($server, $user, $passwd, $database)
185  
186 Builds a MySQL-specific database object.
187  
188 =cut
189  
190 sub spawn_mysql {
191 my $obclass = shift || __PACKAGE__;
192 my $class = ref($obclass) || $obclass;
193  
194 my $db_type = 'mysql';
195 my $db_server = shift || '(undefined)';
196 my $db_user = shift || '(undefined)';
197 my $db_passwd = shift || '(undefined)';
198 my $db_database = shift || '(undefined)';
199  
200 my $self = {};
201 $self->{connection}{type} = $db_type;
202 $self->{connection}{server} = $db_server;
203 $self->{connection}{user} = $db_user;
204 $self->{connection}{passwd} = $db_passwd;
205 $self->{connection}{database} = $db_database;
206  
207 bless($self, $class);
208  
209 # make the connection
210 $self->{connection}{dbh} = DBI->connect("DBI:mysql:$db_database:$db_server",$db_user,$db_passwd) || confess($DBI::errstr);
211  
212 return $self;
213 }
214  
215 =pod
216  
217 =head2 spawn_odbc($dsn, $user, $passwd)
218  
219 Builds an ODBC-specific database object.
220  
221 =cut
222  
223 sub spawn_odbc {
224 my $obclass = shift || __PACKAGE__;
225 my $class = ref($obclass) || $obclass;
226  
227 my $db_type = 'odbc';
228 my $db_dsn = shift || '';
229 my $db_user = shift || '';
230 my $db_passwd = shift || '';
231  
232  
233 my $self = {};
234 $self->{connection}{type} = $db_type;
235 $self->{connection}{dsn} = $db_dsn;
236 $self->{connection}{user} = $db_user;
237 $self->{connection}{passwd} = $db_passwd;
238  
239 bless($self, $class);
240  
241 # make the connection
242 $self->{connection}{dbh} = DBI->connect("DBI:ODBC:$db_dsn",$db_user,$db_passwd) || confess($DBI::errstr);
243  
244 return $self;
245 }
246  
247 =pod
248  
249 =head2 spawn_sqlite($dbfile)
250  
251 Builds a SQLite-specific database object.
252  
253 Note that temporary databases can be created by passing the string ':memory:' in place of a filename.
254  
255 =cut
256  
257 sub spawn_sqlite {
258 my $obclass = shift || __PACKAGE__;
259 my $class = ref($obclass) || $obclass;
260  
261 my $db_type = 'sqlite';
262 my $db_server = '';
263 my $db_user = '';
264 my $db_passwd = '';
265 my $db_database = shift || '(undefined)';
266  
267 my $self = {};
268 $self->{connection}{type} = $db_type;
269 $self->{connection}{server} = $db_server;
270 $self->{connection}{user} = $db_user;
271 $self->{connection}{passwd} = $db_passwd;
272 $self->{connection}{database} = $db_database;
273  
274 bless($self, $class);
275  
276 # make the connection
277 $self->{connection}{dbh} = DBI->connect("DBI:SQLite:dbname=$db_database",$db_user,$db_passwd) || confess($DBI::errstr);
278  
279 return $self;
280 }
281  
282 ##########################################################################################################################
283 # Destructor (Public)
284 sub destruct {
285 my $self = shift;
286  
287 if(defined($self->{connection}{dbh})) {
288 $self->{connection}{dbh}->disconnect();
289 }
290 }
291  
292 ##########################################################################################################################
293 # Public Methods
294  
295 =pod
296  
297 =head1 Methods
298  
299 =head2 $rv = do($statement)
300  
301 Executes a SQL command that does not return a dataset. Check $rv (result value) for errors.
302  
303 =cut
304  
305 sub do {
306 my ($self, $statement) = @_;
307 my $rv = $self->{connection}{dbh}->do($statement);
308 return $rv;
309 }
310  
311 =pod
312  
313 =head2 ($w, $h) = execute($statement, @params)
314  
315 Executes a SQL command that returns a dataset. The list ($w, $h) contains the size of the SAL::DBI's internal data
316 array. (Useful in for loops ;)
317  
318 =cut
319  
320 sub execute {
321 my ($self, $statement, @params) = @_;
322  
323 my $table = $self->_extract_table($statement);
324  
325 # From the section "Outline Usage" of the DBI pod (http://search.cpan.org/~timb/DBI-1.43/DBI.pm)
326 # This should probably be it's own function... Note also the way placeholders are used...
327 $self->{connection}{sth} = $self->{connection}{dbh}->prepare($statement) || confess("Can't Prepare SQL Statement: " . $self->{connection}{dbh}->errstr);
328 #
329  
330 $self->{connection}{sth}->execute(@params) || confess("Can't Execute SQL Statement: " . $self->{connection}{sth}->errstr . "\n\nSQL Statement:\n$statement\nParams:\n@params\n\n");
331 $self->{data} = $self->{connection}{sth}->fetchall_arrayref();
332  
333 # get the width and height (aka metrics) of the returned data set...
334 my $width = $#{$self->{data}[0]};
335 my $height = $self->{connection}{sth}->rows();
336 $self->{internal}{width} = $width;
337 $self->{internal}{height} = $height;
338  
339 foreach my $column (0..$width) {
340 $self->{fields}[$column]{visible} = 1;
341 $self->{fields}[$column]{header} = 1;
342 $self->{fields}[$column]{writeable} = 0;
343 }
344  
345 $self->_get_labels($table);
346 return ($width, $height);
347 }
348  
349 =pod
350  
351 =head2 @column = get_column($col)
352  
353 Return a dataset column as a list.
354  
355 =cut
356  
357 sub get_column {
358 my $self = shift;
359 my $column = shift;
360 my @data;
361  
362 for (my $i=0; $i <= $self->{internal}{height}; $i++) {
363 push (@data, $self->{data}->[$i][$column]);
364 }
365  
366 return @data;
367 }
368  
369 =pod
370  
371 =head2 @record = get_row($row)
372  
373 Return a dataset record as a list.
374  
375 =cut
376  
377 sub get_row {
378 my $self = shift;
379 my $row = shift;
380 my @data;
381  
382 for (my $i=0; $i <= $self->{internal}{width}; $i++) {
383 push (@data, $self->{data}->[$row][$i]);
384 }
385  
386 return @data;
387 }
388  
389 =pod
390  
391 =head2 $csv = get_csv()
392  
393 Get the object's dataset as a CSV file
394  
395 =cut
396  
397 sub get_csv {
398 my $self = shift;
399 my @data;
400 my @labels = $self->get_labels();
401 my $labels = join(',', @labels);
402 push (@data, $labels);
403
404
405 for (my $i=0; $i < $self->{internal}{height}; $i++) {
406 my @record = $self->get_row($i);
407 for (my $j=0; $j <= $self->{internal}{width}; $j++) {
408 $record[$j] = qq["$record[$j]"];
409 $record[$j] =~ s/\[.*\]//;
410 }
411 my $record = join(',', @record);
412 push (@data, $record);
413 }
414
415
416 my $data = join("\r\n", @data);
417 return $data;
418 }
419  
420 =pod
421  
422 =head2 @labels = get_labels()
423  
424 Get a list containing the dataset's field names.
425  
426 =cut
427  
428 sub get_labels {
429 my $self = shift;
430 my @data;
431  
432 for (my $i=0; $i <= $self->{internal}{width}; $i++) {
433 push (@data, $self->{fields}->[$i]->{label});
434 }
435  
436 return @data;
437 }
438  
439 =pod
440  
441 =head2 clean_times($col)
442  
443 Strip times from a datetime column.
444  
445 =cut
446  
447 sub clean_times {
448 my $self = shift;
449 my $col = shift || '0';
450  
451 for (my $i=0; $i < $self->{internal}{height}; $i++) {
452 $self->{data}->[$i][$col] =~ s/\s+\d\d:\d\d:\d\d.*$//;
453 }
454 }
455  
456 =pod
457  
458 =head2 short_dates($col)
459  
460 Convert a datetime column to use short dates. (Note, use clean_times() first)
461  
462 =cut
463  
464 sub short_dates {
465 my $self = shift;
466 my $col = shift || '0';
467  
468 for (my $i=0; $i < $self->{internal}{height}; $i++) {
469 $self->{data}->[$i][$col] =~ s/\d\d(\d\d)-(\d\d)-(\d\d)/$2-$3-$1/;
470 }
471 }
472  
473 ##########################################################################################################################
474 # Private Methods
475 sub _get_labels {
476 my $self = shift;
477 my $table = shift;
478 my $tmp;
479 my $query;
480 my @labels = ();
481  
482 if ($self->{connection}{type} eq 'mysql') {
483 $query = "SHOW COLUMNS FROM $table"; # cant use ? placeholder (embeds in single quotes)
484 $self->{connection}{sth} = $self->{connection}{dbh}->prepare($query) || confess($self->{connection}{dbh}->errstr);
485 $self->{connection}{sth}->execute() || confess($self->{connection}{sth}->errstr);
486 } elsif ($self->{connection}{type} eq 'odbc') {
487 $query = 'SELECT column_name, data_type FROM information_schema.columns WHERE table_name=?';
488 $self->{connection}{sth} = $self->{connection}{dbh}->prepare($query) || confess($self->{connection}{dbh}->errstr);
489 $self->{connection}{sth}->execute($table) || confess($self->{connection}{sth}->errstr);
490 } elsif ($self->{connection}{type} eq 'sqlite') {
491 $query = "PRAGMA table_info($table)";
492 $self->{connection}{sth} = $self->{connection}{dbh}->prepare($query) || confess($self->{connection}{dbh}->errstr);
493 $self->{connection}{sth}->execute() || confess($self->{connection}{sth}->errstr);
494 }
495  
496 $tmp = $self->{connection}{sth}->fetchall_arrayref();
497  
498 if (defined($tmp)) {
499 my $num_rows = $#{$tmp};
500 my $column = 0;
501  
502 for my $row (0..$num_rows) {
503 if ($self->{connection}{type} ne 'sqlite') {
504 my $name = $tmp->[$row][0];
505 my $type = $tmp->[$row][1];
506 $self->{fields}[$column]{label} = $name;
507 $self->{fields}[$column]{name} = $name;
508 $self->{fields}[$column]{type} = $type;
509 $column++;
510 } else {
511 my $name = $tmp->[$row][1];
512 my $type = $tmp->[$row][3];
513 $self->{fields}[$column]{label} = $name;
514 $self->{fields}[$column]{name} = $name;
515 $self->{fields}[$column]{type} = $type;
516 $column++;
517 }
518 }
519 }
520 }
521  
522 sub _extract_table {
523 my $self = shift;
524 my $statement = shift;
525 my $table;
526  
527 # Add a space so that the regex below does not fail on statements like:
528 # "SELECT * FROM some_table"
529  
530 $statement .= ' ';
531  
532 if ($statement =~ /^SELECT\s+(.*)\s+FROM\s+(\w+)\s+(.*)/) {
533 $table = $2;
534 } else {
535 $table = 'undefined_tablename';
536 }
537  
538 return $table;
539 }
540  
541 =pod
542  
543 =head1 Author
544  
545 Scott Elcomb <psema4@gmail.com>
546  
547 =head1 See Also
548  
549 SAL, SAL::WebDDR, SAL::Graph, SAL::WebApplication
550  
551 =cut
552  
553 1;