diff --git a/ext/mysql2/client.c b/ext/mysql2/client.c index 25a35029..628f91d5 100644 --- a/ext/mysql2/client.c +++ b/ext/mysql2/client.c @@ -1331,6 +1331,26 @@ static VALUE rb_mysql_client_encoding(VALUE self) { return wrapper->encoding; } +/* call-seq: + * client.database + * + * Returns the currently selected database. + * + * The result may be stale if `session_track_schema` is disabled. Read + * https://dev.mysql.com/doc/refman/5.7/en/session-state-tracking.html for more + * information. + */ +static VALUE rb_mysql_client_database(VALUE self) { + GET_CLIENT(self); + + char *db = wrapper->client->db; + if (!db) { + return Qnil; + } + + return rb_str_new_cstr(wrapper->client->db); +} + /* call-seq: * client.automatic_close? * @@ -1603,6 +1623,7 @@ void init_mysql2_client() { rb_define_method(cMysql2Client, "ssl_cipher", rb_mysql_get_ssl_cipher, 0); rb_define_method(cMysql2Client, "encoding", rb_mysql_client_encoding, 0); rb_define_method(cMysql2Client, "session_track", rb_mysql_client_session_track, 1); + rb_define_method(cMysql2Client, "database", rb_mysql_client_database, 0); rb_define_private_method(cMysql2Client, "connect_timeout=", set_connect_timeout, 1); rb_define_private_method(cMysql2Client, "read_timeout=", set_read_timeout, 1); diff --git a/spec/mysql2/client_spec.rb b/spec/mysql2/client_spec.rb index 257b56c9..460fd132 100644 --- a/spec/mysql2/client_spec.rb +++ b/spec/mysql2/client_spec.rb @@ -1181,6 +1181,49 @@ def run_gc end end + context 'database' do + before(:example) do + 2.times do |i| + @client.query("CREATE DATABASE test_db#{i}") + end + end + + after(:example) do + 2.times do |i| + @client.query("DROP DATABASE test_db#{i}") + end + end + + it "should be `nil` when no database is selected" do + client = new_client(database: nil) + expect(client.database).to eq(nil) + end + + it "should reflect the initially connected database" do + client = new_client(database: 'test_db0') + expect(client.database).to eq('test_db0') + end + + context "when session tracking is on" do + it "should change to reflect currently selected database" do + client = new_client(database: 'test_db0') + client.query('SET session_track_schema=on') + expect { client.query('USE test_db1') }.to change { + client.database + }.from('test_db0').to('test_db1') + end + end + + context "when session tracking is off" do + it "does not change when a new database is selected" do + client = new_client(database: 'test_db0') + client.query('SET session_track_schema=off') + expect(client.database).to eq('test_db0') + expect { client.query('USE test_db1') }.not_to(change { client.database }) + end + end + end + it "#thread_id should return a boolean" do expect(@client.ping).to eql(true) @client.close