Method: PG::Connection#escape_string
- Defined in:
- ext/pg_connection.c
#escape_string(str) ⇒ String Also known as: escape
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.
Character encoding of escaped string will be equal to client encoding of connection.
NOTE: This class version of this method can only be used safely in client programs that use a single PostgreSQL connection at a time (in this case it can find out what it needs to know “behind the scenes”). It might give the wrong results if used in programs that use multiple database connections; use the same method on the connection object in such cases.
See also convenience functions #escape_literal and #escape_identifier which also add proper quotes around the string.
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 |
# File 'ext/pg_connection.c', line 1628
static VALUE
pgconn_s_escape(VALUE self, VALUE string)
{
size_t size;
int error;
VALUE result;
int enc_idx;
int singleton = !rb_obj_is_kind_of(self, rb_cPGconn);
StringValueCStr(string);
enc_idx = singleton ? ENCODING_GET(string) : pg_get_connection(self)->enc_idx;
if( ENCODING_GET(string) != enc_idx ){
string = rb_str_export_to_enc(string, rb_enc_from_index(enc_idx));
}
result = rb_str_new(NULL, RSTRING_LEN(string) * 2 + 1);
PG_ENCODING_SET_NOCHECK(result, enc_idx);
if( !singleton ) {
size = PQescapeStringConn(pg_get_pgconn(self), RSTRING_PTR(result),
RSTRING_PTR(string), RSTRING_LEN(string), &error);
if(error)
pg_raise_conn_error( rb_ePGerror, self, "%s", PQerrorMessage(pg_get_pgconn(self)));
} else {
size = PQescapeString(RSTRING_PTR(result), RSTRING_PTR(string), RSTRING_LEN(string));
}
rb_str_set_len(result, size);
return result;
}
|