/*
* call-seq:
* conn.escape_string( str ) -> String
*
* Connection instance method for versions of 8.1 and higher of libpq
* uses PQescapeStringConn, which is safer. Avoid calling as a class method,
* the class method uses the deprecated PQescapeString() API function.
*
* Returns a SQL-safe version of the String _str_.
* This is the preferred way to make strings safe for inclusion in
* SQL queries.
*
* Consider using exec_params, which avoids the need for passing values
* inside of SQL commands.
*
* Encoding of escaped string will be equal to client encoding of connection.
*/
static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
char *escaped;
int size,error;
VALUE result;
#ifdef M17N_SUPPORTED
rb_encoding* enc;
#endif
Check_Type(string, T_STRING);
escaped = ALLOC_N(char, RSTRING_LEN(string) * 2 + 1);
if(rb_obj_class(self) == rb_cPGconn) {
size = PQescapeStringConn(get_pgconn(self), escaped,
RSTRING_PTR(string), RSTRING_LEN(string), &error);
if(error) {
xfree(escaped);
rb_raise(rb_ePGError, "%s", PQerrorMessage(get_pgconn(self)));
}
} else {
size = PQescapeString(escaped, RSTRING_PTR(string),
RSTRING_LEN(string));
}
result = rb_str_new(escaped, size);
xfree(escaped);
OBJ_INFECT(result, string);
#ifdef M17N_SUPPORTED
if(rb_obj_class(self) == rb_cPGconn) {
enc = pgconn_get_client_encoding_as_rb_encoding(get_pgconn(self));
} else {
enc = rb_enc_get(string);
}
rb_enc_associate(result, enc);
#endif
return result;
}