diff --git a/ext/mysql2/client.c b/ext/mysql2/client.c index 04bf2cc8..8ad3cac4 100644 --- a/ext/mysql2/client.c +++ b/ext/mysql2/client.c @@ -1259,6 +1259,26 @@ static VALUE rb_mysql_client_encoding(VALUE self) { return wrapper->encoding; } +/* call-seq: + * client.db + * + * Returns the currently selected db. + * + * 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_db(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? * @@ -1500,6 +1520,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, "db", rb_mysql_client_db, 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 5861882c..d8c44e71 100644 --- a/spec/mysql2/client_spec.rb +++ b/spec/mysql2/client_spec.rb @@ -1144,6 +1144,49 @@ def run_gc end end + context 'db' 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.db).to eq(nil) + end + + it "should reflect the initially connected database" do + client = new_client(database: 'test_db0') + expect(client.db).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.db + }.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.db).to eq('test_db0') + expect { client.query('USE test_db1') }.not_to change { client.db } + end + end + end + it "#thread_id should return a boolean" do expect(@client.ping).to eql(true) @client.close