Permalink
Browse files

Add driver registration so the DriverManager can handle multiple driv…

…ers.
  • Loading branch information...
1 parent 47679d3 commit 174d529005000eaabdf2d6329bdb3dffd525165d @timbunce committed Jul 24, 2010
Showing with 36 additions and 12 deletions.
  1. +24 −5 DBDI.pm6
  2. +9 −5 DBDI_pg.pm6
  3. +3 −2 dbdi.pl6
View
@@ -1,20 +1,39 @@
use v6;
+class java::sql::Driver { ... };
+class java::sql::Connection { ... };
+
use java::sql::DriverManager;
-use DBDI_pg;
+class DBDI::DriverManager does java::sql::DriverManager {
+
+ my %drivers;
-class DBDI does java::sql::DriverManager {
+ method registerDriver ( java::sql::Driver $driver ) {
+ say "registerDriver($driver)";
+ %drivers{$driver} = $driver;
+ } # throws java.sql.SQLException
multi method getConnection (
Str $url,
Str $user,
Str $pass,
--> java::sql::Connection
) {
- my $conninfo = "host=localhost $url user=$user password=$pass";
- my %opt;
- my $con = DBDI_pg::Driver.connect($conninfo, %opt);
+ say "> getConnection($url, $user, $pass)";
+
+ my Hash $opt .= new;
+ $opt.<user> = $user;
+ $opt.<password> = $pass;
+
+ my $con;
+ for %drivers.values -> $driver {
+ $con = $driver.connect($url, $opt);
+ last if $con;
+ }
+ die "Unable to find a driver to handle $url" if not $con;
+
+ say "< getConnection $con";
return $con;
}
View
@@ -108,16 +108,20 @@ class DBDI_pg::Connection does java::sql::Connection {
class DBDI_pg::Driver does java::sql::Driver {
+ DBDI::DriverManager.registerDriver( DBDI_pg::Driver.new );
+
+
multi method connect (
- Str $v1,
- Hash $v2,
+ Str $url,
+ Hash $prop,
--> java::sql::Connection
) {
- say "> connect '$v1'";
- my $db_conn = PQconnectdb($v1);
+ say "> connect '$url'";
+ my $conninfo = "host=localhost $url user=$prop.<user> password=$prop.<password>";
+ my $db_conn = PQconnectdb($conninfo);
if (PQstatus($db_conn) != CONNECTION_OK) {
my $msg = PQerrorMessage($db_conn);
- die sprintf( "Connection to database ($v1) failed: %s %s", $msg, PQstatus($db_conn));
+ die sprintf( "Connection to database ($conninfo) failed: %s %s", $msg, PQstatus($db_conn));
}
my DBDI_pg::Connection $conn .= new( :$db_conn );
View
@@ -1,10 +1,11 @@
use v6;
use DBDI;
+use DBDI_pg;
-my $dbname = prompt 'Database: ';
+my $dbname = @*ARGS.shift || prompt 'Database: ';
-my $con = DBDI.getConnection("dbname=$dbname", 'testuser', 'testpass');
+my $con = DBDI::DriverManager.getConnection("dbname=$dbname", 'testuser', 'testpass');
while prompt 'SQL: ' -> $sql {

0 comments on commit 174d529

Please sign in to comment.