MQdb/Database.pm untested

filter: Statementstmt 0.0% 0 / 244 Branchbran 0.0% 0 / 86 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 395 CC 44 SCAR 44.6
CC
44
Cov
0%
new_from_url
306.0
get_connection
42.0
init
30.0
CRAP 86.3
1 # $Id: Database.pm,v 1.34 2009/05/30 01:57:14 severin Exp $
2 =pod
3
4 =head1 NAME - MQdb::Database
5
6 =head1 DESCRIPTION
7
8 Generalized handle on an DBI database handle. Used to provide
9 an instance which holds connection information and allows
10 a higher level get_connection/ disconnect logic that persists
11 above the specific DBI connections. Also provides a real object
12 for use with the rest of the toolkit.
13
14 =head1 SUMMARY
15  
16 MQdb::Database provides the foundation of the MappedQuery system.
17 Databases are primarily specified with a URL format.
18 The URL format includes specification of a driver so this single
19 method can select among the supported DBD drivers. Currently the
20 system supports MYSQL, Oracle, and SQLite.
21 The URL also allows the system to provide the foundation for doing
22 federation of persisted objects. Each DBObject contains a pointer
23 to the Database instance where it is stored. With the database URL
24 and internal database ID, each object is defined in a global space.
25  
26 Attributes of MQdb::Database
27 driver : mysql, oracle, sqlite (default mysql)
28 user : username if the database requires
29 password : password if the database requires
30 host : hostname of the database server machine
31 port : IP port of the database if required
32 (mysql default is 3306)
33 dbname : database/schema name on the database server
34 for sqlite, this is the database file
35  
36 Example URLS
37 mysql://<user>:<pass>@<host>:<port>/<database_name>
38 mysql://<host>:<port>/<database_name>
39 mysql://<user>@<host>:<port>/<database_name>
40 mysql://<host>/<database_name>
41 oracle://<user>:<pass>@/<database_name>
42 oracle://<user>:<pass>@<host>:<port>/<database_name>
43 sqlite:///<database_file>
44  
45  
46 =head1 CONTACT
47  
48 Jessica Severin <jessica.severin@gmail.com>
49  
50 =head1 LICENSE
51  
52 * Software License Agreement (BSD License)
53 * MappedQueryDB [MQdb] toolkit
54 * copyright (c) 2006-2009 Jessica Severin
55 * All rights reserved.
56 * Redistribution and use in source and binary forms, with or without
57 * modification, are permitted provided that the following conditions are met:
58 * * Redistributions of source code must retain the above copyright
59 * notice, this list of conditions and the following disclaimer.
60 * * Redistributions in binary form must reproduce the above copyright
61 * notice, this list of conditions and the following disclaimer in the
62 * documentation and/or other materials provided with the distribution.
63 * * Neither the name of Jessica Severin nor the
64 * names of its contributors may be used to endorse or promote products
65 * derived from this software without specific prior written permission.
66 *
67 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
68 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
69 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
70 * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS BE LIABLE FOR ANY
71 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
72 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
73 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
74 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
75 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
76 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
77  
78 =head1 APPENDIX
79  
80 The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _
81  
82 =cut
83  
84 $VERSION=0.954;
85  
86 package MQdb::Database;
87 use strict;
88 use DBI;
89
90 =head2 new
91  
92 Description: instance creation method
93 Parameter : a hash reference of options same as attribute methods
94 Returntype : instance of this Class (subclass)
95 Exceptions : none
96  
97 =cut
98  
99 =head2 new
100  
101 Description: instance creation method
102 Returntype : instance of this Class (subclass)
103 Exceptions : none
104  
105 =cut
106  
107 sub new {
108 my ($class, @args) = @_;
109 my $self = {};
110 bless $self,$class;
111 $self->init(@args);
112 return $self;
113 }
114  
115 =head2 init
116  
117 Description: initialization method which subclasses can extend
118 Returntype : $self
119 Exceptions : subclass dependent
120  
121 =cut
122  
123 sub init {
124 my ($self, %params) = @_;
125
126 $self->{'_uuid'} = ''; #initially not set
127 $self->{'_driver'} = 'mysql';
128 $self->{'_host'} = $params{'-host'};
129 $self->{'_port'} = $params{'-port'};
130 $self->{'_user'} = $params{'-user'};
131
132 $self->{'_database'} = $params{'-database'} if(defined($params{'-database'}));
133 $self->{'_database'} = $params{'-dbname'} if(defined($params{'-dbname'}));
134
135 $self->{'_password'} = $params{'-pass'} if(defined($params{'-pass'}));
136 $self->{'_password'} = $params{'-password'} if(defined($params{'-password'}));
137  
138 $self->{'_disconnect_count'} = 0;
139
140 $self->_load_aliases;
141
142 return $self;
143 }
144  
145  
146 =head2 new_from_url
147  
148 Description: primary instance creation method
149 Parameter : a string in URL format
150 Returntype : instance of MQdb::Database
151 Examples : my $db = MQdb::Database->new_from_url("mysql://<user>:<pass>@<host>:<port>/<database_name>");
152 e.g. mysql://<host>:<port>/<database_name>
153 e.g. mysql://<user>@<host>:<port>/<database_name>
154 e.g. mysql://<host>/<database_name>
155 e.g. sqlite:///<database_file>
156 my $class = shift;
157 Exceptions : none
158  
159 =cut
160  
161 sub new_from_url {
162 #e.g. mysql://<user>:<pass>@<host>:<port>/<database_name>
163 #e.g. mysql://<host>:<port>/<database_name>
164 #e.g. mysql://<user>@<host>:<port>/<database_name>
165 #e.g. mysql://<host>/<database_name>
166 #e.g. sqlite:///<database_file>
167 my $class = shift;
168 my $url = shift;
169 my $pass = shift;
170  
171 my $self = {};
172 bless $self, $class;
173  
174 return undef unless($url);
175
176 $self->_load_aliases;
177
178 my $driver = 'mysql';
179 my $user = '';
180 my $host = '';
181 my $port = 3306;
182 my $dbname = undef;
183 my $path = '';
184 my $discon = 0;
185 my $species;
186 my $type;
187 my ($p, $p2, $p3);
188  
189 #print("FETCH $url\n");
190  
191 $p = index($url, "://");
192 return undef if($p == -1);
193 $driver = substr($url, 0, $p);
194 $url = substr($url, $p+3, length($url));
195  
196 #print ("db_url=$url\n");
197 $p = index($url, "/");
198 return undef if($p == -1);
199  
200 my $conn = substr($url, 0, $p);
201 $dbname = substr($url, $p+1, length($url));
202 my $params = undef;
203 if(($p2=index($dbname, ";")) != -1) {
204 $params = substr($dbname, $p2+1, length($dbname));
205 $dbname = substr($dbname, 0, $p2);
206 }
207 if((($driver eq 'mysql') or ($driver eq 'oracle')) and ($p2=index($dbname, "/")) != -1) {
208 $path = substr($dbname, $p2+1, length($dbname));
209 $dbname = substr($dbname, 0, $p2);
210 }
211 while($params) {
212 my $token = $params;
213 if(($p2=rindex($params, ";")) != -1) {
214 $token = substr($params, 0, $p2);
215 $params = substr($params, $p2+1, length($params));
216 } else { $params= undef; }
217 if($token =~ /type=(.*)/) {
218 $type = $1;
219 }
220 if($token =~ /discon=(.*)/) {
221 $discon = $1;
222 }
223 if($token =~ /species=(.*)/) {
224 $species = $1;
225 }
226 }
227 $species=$host . "_" . $dbname unless(defined($species));
228  
229 #print(" conn=$conn\n dbname=$dbname\n path=$path\n");
230  
231 my($hostPort, $userPass);
232 if(($p=index($conn, "@")) != -1) {
233 $userPass = substr($conn,0, $p);
234 $hostPort = substr($conn,$p+1,length($conn));
235  
236 if(($p2 = index($userPass, ':')) != -1) {
237 $user = substr($userPass, 0, $p2);
238 unless(defined($pass)) {
239 $pass = substr($userPass, $p2+1, length($userPass));
240 }
241 } elsif(defined($userPass)) { $user = $userPass; }
242 }
243 else {
244 $hostPort = $conn;
245 }
246 if(($p3 = index($hostPort, ':')) != -1) {
247 $port = substr($hostPort, $p3+1, length($hostPort)) ;
248 $host = substr($hostPort, 0, $p3);
249 } else { $host=$hostPort; }
250  
251 #return undef unless($host and $dbname);
252
253 unless(defined($pass)) { $pass = ''; }
254  
255 ($host,$port) = $self->_check_alias($host,$port);
256  
257 $self->{'_uuid'} = '';
258 $self->{'_driver'} = $driver;
259 $self->{'_host'} = $host;
260 $self->{'_port'} = $port;
261 $self->{'_database'} = $dbname;
262 $self->{'_user'} = $user;
263 $self->{'_password'} = $pass;
264  
265 my $full_url = $self->full_url;
266
267 return $self;
268 }
269  
270 =head2 copy
271  
272 Description: makes a copy of the database configuration.
273 New instance will have its own database connection
274 Returntype : instance of MQdb::Database
275  
276 =cut
277  
278 sub copy {
279 my $self = shift;
280 my $class = ref($self);
281 my $copy = $class->new;
282
283 $self->{'_uuid'} = $self->uuid;
284 $self->{'_driver'} = $self->driver;
285 $self->{'_host'} = $self->host;
286 $self->{'_port'} = $self->port;
287 $self->{'_user'} = $self->user;
288 $self->{'_password'} = $self->password;
289 $self->{'_database'} = $self->dbname;
290  
291 return $copy;
292 }
293  
294  
295 =head2 dbc
296  
297 Description: connects to database and returns a DBI connection
298 Returntype : DBI database handle
299 Exceptions : none
300  
301 =cut
302  
303 sub dbc {
304 my $self = shift;
305 return $self->get_connection;
306 }
307  
308 sub get_connection {
309 my($self) = @_;
310  
311 my $dbc = $self->{"DB_CONNECTION"};
312  
313 if(defined($dbc)) {
314 if($dbc->ping()) {
315 return $dbc;
316 } else {
317 print STDERR "Failed Ping....\n";
318 $dbc->disconnect();
319 }
320 }
321  
322 my $driver = $self->{'_driver'};
323 my $host = $self->{'_host'};
324 my $port = $self->{'_port'};
325 my $database = $self->{'_database'};
326 my $user = $self->{'_user'};
327 my $password = $self->{'_password'};
328
329 if($driver eq 'mysql') {
330 my $dsn = "DBI:mysql:database=$database;host=$host;port=$port";
331 $dbc = DBI->connect($dsn, $user, $password, {RaiseError=>1, AutoCommit=>1});
332 }
333 if($driver eq 'oracle') {
334 my $dsn = "DBI:Oracle:" . $self->{'_database'};
335 $dbc = DBI->connect($dsn, $user, $password, {RaiseError=>1, AutoCommit=>1});
336 }
337 if($driver eq 'sqlite') {
338 my $dsn = "DBI:SQLite:dbname=/$database";
339 $dbc = DBI->connect($dsn, $user, $password);
340 }
341
342 $self->{"DB_CONNECTION"} = $dbc;
343  
344 return $dbc
345 }
346  
347  
348 =head2 disconnect
349  
350 Description: disconnects handle from database, but retains object and
351 all information so that it can be reconnected again
352 at a later time.
353 Returntype : none
354 Exceptions : none
355  
356 =cut
357  
358 sub disconnect {
359 my $self = shift;
360 return unless($self->{'DB_CONNECTION'});
361
362 my $dbc = $self->{'DB_CONNECTION'};
363 if($dbc->{ActiveKids} != 0) {
364 warn("Problem disconnect : kids=",$dbc->{Kids},
365 " activekids=",$dbc->{ActiveKids},"\n");
366 return 1;
367 }
368 $dbc->disconnect();
369 $self->{'_disconnect_count'}++;
370 $self->{'DB_CONNECTION'} = undef;
371 #print("DISCONNECT\n");
372
373 return $self;
374 }
375  
376  
377 sub DESTROY {
378 my $self = shift;
379 #$self->disconnect();
380 }
381  
382 #############################################
383 # attribute access methods (no setting)
384 #############################################
385  
386 sub uuid {
387 my $self = shift;
388 return $self->{'_uuid'} = shift if(@_);
389 return $self->{'_uuid'};
390 }
391  
392 sub driver { return shift->{'_driver'}; }
393 sub host { return shift->{'_host'}; }
394 sub port { my $self=shift; return $self->{'_port'}; }
395 sub user { my $self=shift; return $self->{'_user'}; }
396 sub password { my $self=shift; return $self->{'_password'}; }
397 sub dbname { my $self=shift; return $self->{'_database'}; }
398 sub disconnect_count { my $self=shift; return $self->{'_disconnect_count'}; }
399  
400 =head2 full_url
401  
402 Description: returns the URL of this database with user and password
403 Returntype : string
404 Exceptions : none
405  
406 =cut
407  
408 sub full_url {
409 my $self = shift;
410 my $full_url = sprintf("%s://%s:%s@%s:%s/%s",
411 $self->driver,
412 $self->user,
413 $self->password,
414 $self->host,
415 $self->port,
416 $self->dbname);
417 #printf(" full_url : %s\n", $full_url);
418 return $full_url;
419 }
420  
421 =head2 url
422  
423 Description: returns URL of this database but without user:password
424 used for global referencing and federation systems
425 Returntype : string
426 Exceptions : none
427  
428 =cut
429  
430 sub url {
431 #no username or password in URL
432 my $self = shift;
433 return $self->{'_short_url'} if(defined($self->{'_short_url'}));
434 my $url = $self->driver . "://";
435 if($self->host) {
436 if($self->port) { $url .= $self->host .":". $self->port; }
437 else { $url .= $self->host; }
438 }
439 $url .= "/". $self->dbname;
440 $self->{'_short_url'} = $url;
441 return $self->{'_short_url'};
442 }
443  
444 =head2 xml
445  
446 Description: returns XML of this database but without user:password
447 used for global referencing and federation systems
448 Returntype : string
449 Exceptions : none
450  
451 =cut
452  
453 sub xml {
454 #no username or password in URL
455 my $self = shift;
456 my $xml = sprintf("<database name=\"%s\" url=\"%s\" ",
457 $self->alias,
458 $self->url);
459 if($self->uuid) { $xml .= sprintf("uuid=\"%s\" ", $self->uuid); }
460 $xml .= "/>";
461 return $xml;
462 }
463  
464 sub alias {
465 my $self = shift;
466 $self->{'alias'} = shift if(@_);
467 $self->{'alias'} = $self->dbname unless(defined($self->{'alias'}));
468 return $self->{'alias'};
469 }
470  
471 ####################################################
472 #
473 # URL related methods
474 #
475 ####################################################
476  
477 sub _load_aliases {
478 my $self = shift;
479  
480 $self->{'_aliases'} = {};
481 return unless(defined($ENV{'HOME'}));
482
483 my $alias_file = $ENV{'HOME'} . "/.mqdb_url_aliases";
484 return unless(-e $alias_file);
485 #print("found ALIAS file $alias_file\n");
486
487 open (ALIASFP,$alias_file) || return;
488 while(<ALIASFP>) {
489 chomp;
490 my($from, $to) = split(/\s+/);
491 $self->{'_aliases'}->{$from} = $to;
492 }
493 close(ALIASFP);
494 }
495  
496  
497 sub _check_alias {
498 my $self = shift;
499 my $host = shift;
500 my $port = shift;
501  
502 my $key = "$host:$port";
503 my $alias = $self->{'_aliases'}->{$key};
504 return ($host,$port) unless($alias);
505
506 ($host,$port) = split(/:/, $alias);
507 #print("translate alias $key into $host : $port\n");
508 return ($host,$port);
509 }
510  
511 #################################################
512 # high level wrappers for direct queries
513 #################################################
514  
515 =head2 execute_sql
516  
517 Description : executes SQL statement with external parameters and placeholders
518 Example : $db->execute_sql("insert into table1(id, value) values(?,?)", $id, $value);
519 Parameter[1] : sql statement string
520 Parameter[2..] : optional parameters for the SQL statement
521 Returntype : none
522 Exceptions : none
523  
524 =cut
525  
526 sub execute_sql {
527 my $self = shift;
528 my $sql = shift;
529 my @params = @_;
530
531 if($self->driver eq 'sqlite') {
532 $sql =~ s/INSERT ignore/INSERT or ignore/g;
533 }
534 my $dbc = $self->get_connection;
535 my $sth = $dbc->prepare($sql);
536 eval { $sth->execute(@params); };
537 if($@) {
538 printf(STDERR "ERROR with query: %s\n", $sql);
539 printf(STDERR " params: ");
540 foreach my $param (@params) { print(STDERR "'%s' ", $param); }
541 print(STDERR "\n");
542 }
543 $sth->finish;
544 }
545  
546  
547 =head2 do_sql
548  
549 Description : executes SQL statement with "do" and no external parameters
550 Example : $db->do_sql("insert into table1(id, value) values(null,'hello world');");
551 Parameter : sql statement string with no external parameters
552 Returntype : none
553 Exceptions : none
554  
555 =cut
556  
557 sub do_sql {
558 my $self = shift;
559 my $sql = shift;
560
561 if($self->driver eq 'sqlite') {
562 $sql =~ s/INSERT ignore/INSERT or ignore/g;
563 if(uc($sql) =~ /^UNLOCK TABLES/) { $sql = "END TRANSACTION;"; }
564 if(uc($sql) =~ /^LOCK TABLE/) { $sql = "BEGIN TRANSACTION;"; }
565
566 }
567 my $dbc = $self->get_connection;
568 if(!($dbc->do($sql))) {
569 printf(STDERR "WARNING with query: %s\n", $sql);
570 #die;
571 }
572 }
573  
574 =head2 fetch_col_value
575  
576 Arg (1) : $sql (string of SQL statement with place holders)
577 Arg (2...) : optional parameters to map to the placehodlers within the SQL
578 Example : $value = $self->fetch_col_value($db, "select some_column from my_table where id=?", $id);
579 Description: General purpose function to allow fetching of a single column from a single row.
580 Returntype : scalar value
581 Exceptions : none
582 Caller : within subclasses to easy development
583  
584 =cut
585  
586 sub fetch_col_value {
587 my $self = shift;
588 my $sql = shift;
589 my @params = @_;
590  
591 my $dbc = $self->get_connection;
592 my $sth = $dbc->prepare($sql);
593 $sth->execute(@params);
594 my ($value) = $sth->fetchrow_array();
595 $sth->finish;
596 return $value;
597 }
598  
599
600 1;