[HttpFoundation] use different approach for duplicate keys in postgres, fix merge for sqlsrv and oracle

This commit is contained in:
Tobias Schultze 2014-05-28 13:11:33 +02:00
parent cff410507f
commit 00d707f76c
2 changed files with 42 additions and 34 deletions

View File

@ -12,7 +12,13 @@
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
/** /**
* PdoSessionHandler. * Session handler using a PDO connection to read and write data.
*
* Session data is a binary string that can contain non-printable characters like the null byte.
* For this reason this handler base64 encodes the data to be able to save it in a character column.
*
* This version of the PdoSessionHandler does NOT implement locking. So concurrent requests to the
* same session can result in data loss due to race conditions.
* *
* @author Fabien Potencier <fabien@symfony.com> * @author Fabien Potencier <fabien@symfony.com>
* @author Michael Williams <michael.williams@funsational.com> * @author Michael Williams <michael.williams@funsational.com>
@ -164,13 +170,10 @@ class PdoSessionHandler implements \SessionHandlerInterface
*/ */
public function write($sessionId, $data) public function write($sessionId, $data)
{ {
// Session data can contain non binary safe characters so we need to encode it.
$encoded = base64_encode($data); $encoded = base64_encode($data);
// We use a MERGE SQL query when supported by the database.
// Otherwise we have to use a transactional DELETE followed by INSERT to prevent duplicate entries under high concurrency.
try { try {
// We use a MERGE SQL query when supported by the database.
$mergeSql = $this->getMergeSql(); $mergeSql = $this->getMergeSql();
if (null !== $mergeSql) { if (null !== $mergeSql) {
@ -183,28 +186,33 @@ class PdoSessionHandler implements \SessionHandlerInterface
return true; return true;
} }
$this->pdo->beginTransaction(); $updateStmt = $this->pdo->prepare(
"UPDATE $this->table SET $this->dataCol = :data, $this->timeCol = :time WHERE $this->idCol = :id"
);
$updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$updateStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
$updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
$updateStmt->execute();
try { // Since Postgres does not support MERGE (without custom stored procedure), we have to use this approach
$deleteStmt = $this->pdo->prepare( // that can result in duplicate key errors when the same session is written simultaneously. We can just
"DELETE FROM $this->table WHERE $this->idCol = :id" // ignore such an error because either the data did not change anyway or which data is written does not
); // matter as proper locking to serialize access to a session is not implemented.
$deleteStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); if (!$updateStmt->rowCount()) {
$deleteStmt->execute(); try {
$insertStmt = $this->pdo->prepare(
$insertStmt = $this->pdo->prepare( "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)"
"INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)" );
); $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
$insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); $insertStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
$insertStmt->bindParam(':data', $encoded, \PDO::PARAM_STR); $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
$insertStmt->bindValue(':time', time(), \PDO::PARAM_INT); $insertStmt->execute();
$insertStmt->execute(); } catch (\PDOException $e) {
// ignore unique violation SQLSTATE
$this->pdo->commit(); if ('23505' !== $e->getCode()) {
} catch (\PDOException $e) { throw $e;
$this->pdo->rollback(); }
}
throw $e;
} }
} catch (\PDOException $e) { } catch (\PDOException $e) {
throw new \RuntimeException(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e); throw new \RuntimeException(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
@ -230,12 +238,12 @@ class PdoSessionHandler implements \SessionHandlerInterface
// DUAL is Oracle specific dummy table // DUAL is Oracle specific dummy table
return "MERGE INTO $this->table USING DUAL ON ($this->idCol = :id) " . return "MERGE INTO $this->table USING DUAL ON ($this->idCol = :id) " .
"WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) " . "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) " .
"WHEN MATCHED THEN UPDATE SET $this->dataCol = :data"; "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->timeCol = :time";
case 'sqlsrv': case 'sqlsrv' && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
// MS SQL Server requires MERGE be terminated by semicolon // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
return "MERGE INTO $this->table USING (SELECT 'x' AS dummy) AS src ON ($this->idCol = :id) " . return "MERGE INTO $this->table USING (SELECT 'x' AS dummy) AS src ON ($this->idCol = :id) " .
"WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) " . "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) " .
"WHEN MATCHED THEN UPDATE SET $this->dataCol = :data;"; "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->timeCol = :time;";
case 'sqlite': case 'sqlite':
return "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)"; return "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)";
} }

View File

@ -23,9 +23,9 @@ class PdoSessionHandlerTest extends \PHPUnit_Framework_TestCase
$this->markTestSkipped('This test requires SQLite support in your environment'); $this->markTestSkipped('This test requires SQLite support in your environment');
} }
$this->pdo = new \PDO("sqlite::memory:"); $this->pdo = new \PDO('sqlite::memory:');
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sql = "CREATE TABLE sessions (sess_id VARCHAR(255) PRIMARY KEY, sess_data TEXT, sess_time INTEGER)"; $sql = 'CREATE TABLE sessions (sess_id VARCHAR(128) PRIMARY KEY, sess_data TEXT, sess_time INTEGER)';
$this->pdo->exec($sql); $this->pdo->exec($sql);
} }
@ -37,9 +37,9 @@ class PdoSessionHandlerTest extends \PHPUnit_Framework_TestCase
public function testWrongPdoErrMode() public function testWrongPdoErrMode()
{ {
$pdo = new \PDO("sqlite::memory:"); $pdo = new \PDO('sqlite::memory:');
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
$pdo->exec("CREATE TABLE sessions (sess_id VARCHAR(255) PRIMARY KEY, sess_data TEXT, sess_time INTEGER)"); $pdo->exec('CREATE TABLE sessions (sess_id VARCHAR(128) PRIMARY KEY, sess_data TEXT, sess_time INTEGER)');
$this->setExpectedException('InvalidArgumentException'); $this->setExpectedException('InvalidArgumentException');
$storage = new PdoSessionHandler($pdo, array('db_table' => 'sessions')); $storage = new PdoSessionHandler($pdo, array('db_table' => 'sessions'));