Skip to content

Commit 40e3b86

Browse files
committed
Do not require an open connection for MySQL string escaping
1 parent b355917 commit 40e3b86

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

ext/mysql2/client.c

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,12 @@ static ID intern_brackets, intern_merge, intern_merge_bang, intern_new_with_args
3838
#define CONNECTED(wrapper) (wrapper->client->net.pvio != NULL && wrapper->client->net.fd != -1 && VIO_IS_CONNECTED(wrapper))
3939
#endif
4040

41+
#define MYSQL_CLIENT_NOT_CONNECTED_STR "MySQL client is not connected"
42+
4143
#define REQUIRE_CONNECTED(wrapper) \
4244
REQUIRE_INITIALIZED(wrapper) \
4345
if (!CONNECTED(wrapper) && !wrapper->reconnect_enabled) { \
44-
rb_raise(cMysql2Error, "MySQL client is not connected"); \
46+
rb_raise(cMysql2Error, MYSQL_CLIENT_NOT_CONNECTED_STR); \
4547
}
4648

4749
#define REQUIRE_NOT_CONNECTED(wrapper) \
@@ -50,6 +52,12 @@ static ID intern_brackets, intern_merge, intern_merge_bang, intern_new_with_args
5052
rb_raise(cMysql2Error, "MySQL connection is already open"); \
5153
}
5254

55+
#define REQUIRE_CONNECTED_ONCE(wrapper) \
56+
REQUIRE_INITIALIZED(wrapper) \
57+
if (!wrapper->client->server_version) { \
58+
rb_raise(cMysql2Error, MYSQL_CLIENT_NOT_CONNECTED_STR); \
59+
}
60+
5361
/*
5462
* compatability with mysql-connector-c, where LIBMYSQL_VERSION is the correct
5563
* variable to use, but MYSQL_SERVER_VERSION gives the correct numbers when
@@ -819,7 +827,7 @@ static VALUE rb_mysql_client_real_escape(VALUE self, VALUE str) {
819827
rb_encoding *conn_enc;
820828
GET_CLIENT(self);
821829

822-
REQUIRE_CONNECTED(wrapper);
830+
REQUIRE_CONNECTED_ONCE(wrapper);
823831
Check_Type(str, T_STRING);
824832
default_internal_enc = rb_default_internal_encoding();
825833
conn_enc = rb_to_encoding(wrapper->encoding);

spec/mysql2/client_spec.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -887,11 +887,11 @@ def run_gc
887887
end.not_to raise_error
888888
end
889889

890-
it "should require an open connection" do
890+
it "should not require an open connection" do
891891
@client.close
892892
expect do
893893
@client.escape ""
894-
end.to raise_error(Mysql2::Error)
894+
end.not_to raise_error
895895
end
896896

897897
context 'when mysql encoding is not utf8' do

0 commit comments

Comments
 (0)