Permalink
Browse files

Add Database#valid_connection? for checking whether a given connectio…

…n is valid

This is not currently used by other parts of Sequel, but I plan
to use it in a future extension.
  • Loading branch information...
1 parent a01fdf8 commit 40e7a68323138d0c6359b158c6e135ab3b600253 @jeremyevans committed Oct 23, 2012
Showing with 35 additions and 1 deletion.
  1. +2 −0 CHANGELOG
  2. +5 −0 lib/sequel/adapters/jdbc/derby.rb
  3. +21 −1 lib/sequel/database/connecting.rb
  4. +7 −0 spec/integration/database_test.rb
View
@@ -1,5 +1,7 @@
=== HEAD
+* Add Database#valid_connection? for checking whether a given connection is valid (jeremyevans)
+
* Make dataset.limit(nil, nil) reset offset as well as limit (jeremyevans) (#571)
* Support IMMEDIATE/EXCLUSIVE/DEFERRED transaction modes on SQLite (Eric Wong)
@@ -148,6 +148,11 @@ def type_literal(column)
def uses_clob_for_text?
true
end
+
+ # The SQL query to issue to check if a connection is valid.
+ def valid_connection_sql
+ @valid_connection_sql ||= select(1).sql
+ end
end
# Dataset class for Derby datasets accessed via JDBC.
@@ -140,7 +140,7 @@ def add_servers(servers)
@pool.add_servers(servers.keys)
end
end
-
+
# Connects to the database. This method should be overridden by descendants.
def connect(server)
raise NotImplemented, "#connect should be overridden by adapters"
@@ -250,6 +250,21 @@ def test_connection(server=nil)
true
end
+ # Check whether the given connection is currently valid, by
+ # running a query against it. If the query fails, the
+ # connection should probably be removed from the connection
+ # pool.
+ def valid_connection?(conn)
+ sql = valid_connection_sql
+ begin
+ log_connection_execute(conn, sql)
+ rescue Sequel::DatabaseError, *database_error_classes
+ false
+ else
+ true
+ end
+ end
+
private
# The default options for the connection pool.
@@ -278,5 +293,10 @@ def server_opts(server)
opts.delete(:servers)
opts
end
+
+ # The SQL query to issue to check if a connection is valid.
+ def valid_connection_sql
+ @valid_connection_sql ||= select(nil).sql
+ end
end
end
@@ -35,4 +35,11 @@
specify "should not have the connection pool swallow non-StandardError based exceptions" do
proc{INTEGRATION_DB.pool.hold{raise Interrupt, "test"}}.should raise_error(Interrupt)
end
+
+ specify "should provide ability to check connections for validity" do
+ conn = INTEGRATION_DB.synchronize{|c| c}
+ INTEGRATION_DB.valid_connection?(conn).should be_true
+ INTEGRATION_DB.disconnect
+ INTEGRATION_DB.valid_connection?(conn).should be_false
+ end
end

0 comments on commit 40e7a68

Please sign in to comment.