swoole / ext-postgresql

🐘 Coroutine-based client for PostgreSQL
65 stars 21 forks source link

More escaping methods #39

Closed codercms closed 4 years ago

codercms commented 4 years ago

Changes:

Why do I add these methods?

Because the "escape" method doesn't escape values completely for their usage in SQL queries. Ref from the libpq doc: PQescapeStringConn escapes string literals, much like PQescapeLiteral. Unlike PQescapeLiteral, the caller is responsible for providing an appropriately sized buffer. Furthermore, PQescapeStringConn does not generate the single quotes that must surround PostgreSQL string literals; they should be provided in the SQL command that the result is inserted into.

PHP code example

$sourceString1 = "some'hacking\\string";

$escape = $connection->escape($sourceString1);
$literal = $connection->escapeLiteral($sourceString1);
$identifier = $connection->escapeIdentifier($sourceString1);

printf("source_string=%s\n", $sourceString1);
printf("escape=%s\n", $escape);
printf("literal=%s\n", $literal);
printf("identifier=%s\n\n", $identifier);

// ------------------------------------------------------------

$sourceString2 = 'simple"';

$escape = $connection->escape($sourceString2);
$literal = $connection->escapeLiteral($sourceString2);
$identifier = $connection->escapeIdentifier($sourceString2);

printf("source_string=%s\n", $sourceString2);
printf("escape=%s\n", $escape);
printf("literal=%s\n", $literal);
printf("identifier=%s\n\n", $identifier);

Output:

source_string=some'hacking\string
escape=some''hacking\string
literal= E'some''hacking\\string'
identifier="some'hacking\string"

source_string=simple"
escape=simple"
literal='simple"'
identifier="simple"""