exec() returns the number of SELECTed rows on postgresql >= 9.

Bug #61267 pdo_pgsql's PDO::exec() returns the number of SELECTed rows on postgresql >= 9.
Submitted: 2012-03-03 13:54 UTC Modified: 2012-03-08 08:52 UTC
From: ben dot pineau at gmail dot com Assigned: cataphract (profile)
Status: Closed Package: PDO related
PHP Version: Irrelevant OS: all
Private report: No CVE-ID: None

 [2012-03-03 13:54 UTC] ben dot pineau at gmail dot com

Description:
------------
After executing a SELECT statement, PDO::exec() -using the pdo_pgsql driver and 
running against a PostgreSQL server older than 9.0- will always returns 0, as 
does the pdo_mysql and pdo_sqlite drivers. ie. this is the exepected behaviour 
(though to be precise, the PDO::exec() documentation stipulate : "PDO::exec() 
does not return results from a SELECT statement.").

But when executed against a PostgreSQL >= 9.0 server, this very same php client 
and select statement will return the number of selected rows. This is due to a 
server side change in how PostgreSQL servers answers to libpqs's PQcmdTuples() 
commands (PQcmdTuples() being used as the PDO::exec() return value, via 
pdo_pgsql pgsql_handle_doer() function).

This server-side change is visible by comparing this command's documentation for 
different PostgreSQL versions :
http://www.postgresql.org/docs/8.4/interactive/libpq-exec.html#LIBPQ-EXEC-
SELECT-INFO
http://www.postgresql.org/docs/9.1/interactive/libpq-exec.html#LIBPQ-EXEC-
SELECT-INFO
See also the bug in pg_affected_rows https://bugs.php.net/bug.php?id=61266 I 
just reported.

The attached patch does check whether the PDO::exec() param was a (successful) 
DML statement before using PQcmdTuples() to return the number of affected rows. 
Also attached, a test script for PHP's unit test infrastructure.


Test script:
---------------
// Bugs on PostgreSQL >= 9.0 server (but ok on previous versions)
$dbh = new PDO("pgsql:dbname=postgres ;host=localhost", 'postgres'); 
var_dump($dbh->exec("SELECT * from generate_series(1, 42);"));

Expected result:
----------------
int(0)

Actual result:
--------------
int(42)

Patches

unittest_pdo_exec_return_value_after_pdo_pgsql_select.phpt (last revision 2012-03-03 13:56 UTC by ben dot pineau at gmail dot com)
pdo_exec_return_zero_after_pdo_pgsql_select.patch (last revision 2012-03-03 13:54 UTC by ben dot pineau at gmail dot com)

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports

 [2012-03-08 08:52 UTC] cataphract@php.net

-Status: Open +Status: Closed -Assigned To: +Assigned To: cataphract