问题
We are trying to find out if our Rails 3.1.12 app opens the SQLite3 database (version 3.6 or above) with gem sequel. Here is what we did:
rails console
In the Rails console session, typed the following command:
sequel = Sequel.connect('sqlite://development')
It returns:
=> #<Sequel::SQLite::Database: "sqlite://development">
Also sequel.class returns:
=> Sequel::SQLite::Database
However when trying to select from the database with sequel.execute
or check a table with sequel.schema
, the returned text says that the table does not exist.
We are not quite sure if the database (development here) has been opened or not. How do we check that?
回答1:
Offhand I'd say you can try:
DB.test_connection
=> true
The documentation for test_connection says:
Attempts to acquire a database connection. Returns true if successful. Will probably raise an Error if unsuccessful. If a server argument is given, attempts to acquire a database connection to the given server/shard.
Years ago we'd use a benign query to tell if the connection is alive. You can try:
DB["select datetime('now');"].first
Which returns:
{
:"datetime('now')" => "2013-06-25 06:23:44"
}
You'll probably want to catch any exceptions that might be raised if the query fails, but that would indicate that the connection was down too.
回答2:
Michael Berkowski's comment deserves to be an answer.
The Sequel.connect method accepts a test: true
option. According to the docs:
Whether to test that a valid database connection can be made (false by default)
Under the hood it causes Sequel to call #test_connection
on the new db object.
来源:https://stackoverflow.com/questions/17287623/how-do-we-verify-if-sequel-connect-opened-our-sqlite3-database-in-rails