diff --git a/lib/WebGUI/DatabaseLink.pm b/lib/WebGUI/DatabaseLink.pm index 22e42dfb9..65839f81d 100644 --- a/lib/WebGUI/DatabaseLink.pm +++ b/lib/WebGUI/DatabaseLink.pm @@ -100,6 +100,33 @@ sub delete { #------------------------------------------------------------------- +=head3 databaseName ( ) + +Based on the DSN, figures out what the database name is. + +=cut + +sub databaseName { + my $self = shift; + return $self->{_databaseName} if $self->{_databaseName}; + my @dsnEntries = split(/[:;]/, $self->get->{DSN}); + + my $databaseName; + if ($dsnEntries[2] !~ /=/) { + $databaseName = $dsnEntries[2]; + } else { + foreach (@dsnEntries) { + if ($_ =~ m/^(database|db|dbname)=(.+)$/) { + $databaseName = $2; + last; + } + } + } + return $databaseName; +} + +#------------------------------------------------------------------- + =head2 disconnect ( ) Disconnect cleanly from the current databaseLink. You should always use this method rather than the disconnect method of the actual WebGUI::SQL database handle otherwise you may accidentally close the database handle to the WebGUI database prematurely. diff --git a/t/DatabaseLink.t b/t/DatabaseLink.t new file mode 100644 index 000000000..e8462ede4 --- /dev/null +++ b/t/DatabaseLink.t @@ -0,0 +1,50 @@ +#------------------------------------------------------------------- +# WebGUI is Copyright 2001-2007 Plain Black Corporation. +#------------------------------------------------------------------- +# Please read the legal notices (docs/legal.txt) and the license +# (docs/license.txt) that came with this distribution before using +# this software. +#------------------------------------------------------------------- +# http://www.plainblack.com info@plainblack.com +#------------------------------------------------------------------- + +use FindBin; +use strict; +use lib "$FindBin::Bin/lib"; + +use WebGUI::Test; +use WebGUI::Session; + +use WebGUI::DatabaseLink; + +use Test::More; # increment this value for each test you create + +my $session = WebGUI::Test->session; + +my $DSNs = [ + { + dsn => 'DBI:mysql:colonSeparated:myHost:8008', + dbName => 'colonSeparated', + }, + { + dsn => 'DBI:mysql:database=myDatabase', + dbName => 'myDatabase', + }, + { + dsn => 'DBI:mysql:dbName=myDbName', + dbName => 'myDbName', + }, +]; + +plan tests => 2; + +my $dbLink = WebGUI::DatabaseLink->new($session, 0); +is($dbLink->get->{DSN}, $session->config->get('dsn'), 'DSN set correctly for default database link'); +my ($databaseName) = $session->db->quickArray('SELECT DATABASE()'); +is ($dbLink->databaseName, $databaseName, 'databaseName parsed default DSN from config file'); + +END { + foreach my $link ($dbLink, ) { + $link->delete if (defined $link and ref $link eq 'WebGUI::DatabaseLink'); + } +}