bug #11009 [HttpFoundation] smaller fixes for PdoSessionHandler (Tobion)
This PR was merged into the 2.3 branch. Discussion ---------- [HttpFoundation] smaller fixes for PdoSessionHandler | Q | A | ------------- | --- | Bug fix? | yes | New feature? | no | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | #10652 | License | MIT For both the PdoSessionHandler and DbalSessionHandler - https://github.com/symfony/symfony/pull/10652#issuecomment-42370425: Transactional DELETE + INSERT does not work as expected - https://github.com/symfony/symfony/pull/10652#issuecomment-44359784: sqlsrv 2005 does not support the MERGE SQL, and if used it requires an HOLDLOCK - missing time update for sqlsrv and oracle Commits -------a0e1d4d
[Doctrine Bridge] fix DBAL session handler according to PdoSessionHandler00d707f
[HttpFoundation] use different approach for duplicate keys in postgres, fix merge for sqlsrv and oracle
This commit is contained in:
commit
fe01d10735
@ -12,6 +12,8 @@
|
|||||||
namespace Symfony\Bridge\Doctrine\HttpFoundation;
|
namespace Symfony\Bridge\Doctrine\HttpFoundation;
|
||||||
|
|
||||||
use Doctrine\DBAL\Connection;
|
use Doctrine\DBAL\Connection;
|
||||||
|
use Doctrine\DBAL\Driver\DriverException;
|
||||||
|
use Doctrine\DBAL\Platforms\SQLServer2008Platform;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DBAL based session storage.
|
* DBAL based session storage.
|
||||||
@ -146,13 +148,10 @@ class DbalSessionHandler 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 single MERGE SQL query when supported by the database.
|
||||||
$mergeSql = $this->getMergeSql();
|
$mergeSql = $this->getMergeSql();
|
||||||
|
|
||||||
if (null !== $mergeSql) {
|
if (null !== $mergeSql) {
|
||||||
@ -165,28 +164,41 @@ class DbalSessionHandler implements \SessionHandlerInterface
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->con->beginTransaction();
|
$updateStmt = $this->con->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 {
|
// When MERGE is not supported, like in Postgres, we have to use this approach that can result in
|
||||||
$deleteStmt = $this->con->prepare(
|
// duplicate key errors when the same session is written simultaneously. We can just catch such an
|
||||||
"DELETE FROM $this->table WHERE $this->idCol = :id"
|
// error and re-execute the update. This is similar to a serializable transaction with retry logic
|
||||||
);
|
// on serialization failures but without the overhead and without possible false positives due to
|
||||||
$deleteStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
// longer gap locking.
|
||||||
$deleteStmt->execute();
|
if (!$updateStmt->rowCount()) {
|
||||||
|
try {
|
||||||
$insertStmt = $this->con->prepare(
|
$insertStmt = $this->con->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 (\Exception $e) {
|
||||||
$this->con->commit();
|
$driverException = $e->getPrevious();
|
||||||
} catch (\Exception $e) {
|
// Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
|
||||||
$this->con->rollback();
|
// DriverException only available since DBAL 2.5
|
||||||
|
if (
|
||||||
throw $e;
|
($driverException instanceof DriverException && 0 === strpos($driverException->getSQLState(), '23')) ||
|
||||||
|
($driverException instanceof \PDOException && 0 === strpos($driverException->getCode(), '23'))
|
||||||
|
) {
|
||||||
|
$updateStmt->execute();
|
||||||
|
} else {
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
throw new \RuntimeException(sprintf('Exception was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
|
throw new \RuntimeException(sprintf('Exception was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
|
||||||
@ -212,12 +224,13 @@ class DbalSessionHandler 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 'mssql':
|
case $this->con->getDatabasePlatform() instanceof SQLServer2008Platform:
|
||||||
// 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) " .
|
// It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
|
||||||
|
return "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 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)";
|
||||||
}
|
}
|
||||||
|
@ -20,14 +20,11 @@ use Doctrine\DBAL\Schema\Schema;
|
|||||||
*/
|
*/
|
||||||
final class DbalSessionHandlerSchema extends Schema
|
final class DbalSessionHandlerSchema extends Schema
|
||||||
{
|
{
|
||||||
private $tableName;
|
|
||||||
|
|
||||||
public function __construct($tableName = 'sessions')
|
public function __construct($tableName = 'sessions')
|
||||||
{
|
{
|
||||||
parent::__construct();
|
parent::__construct();
|
||||||
|
|
||||||
$this->tableName = $tableName;
|
$this->addSessionTable($tableName);
|
||||||
$this->addSessionTable();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function addToSchema(Schema $schema)
|
public function addToSchema(Schema $schema)
|
||||||
@ -37,9 +34,9 @@ final class DbalSessionHandlerSchema extends Schema
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function addSessionTable()
|
private function addSessionTable($tableName)
|
||||||
{
|
{
|
||||||
$table = $this->createTable($this->tableName);
|
$table = $this->createTable($tableName);
|
||||||
$table->addColumn('sess_id', 'string');
|
$table->addColumn('sess_id', 'string');
|
||||||
$table->addColumn('sess_data', 'text')->setNotNull(true);
|
$table->addColumn('sess_data', 'text')->setNotNull(true);
|
||||||
$table->addColumn('sess_time', 'integer')->setNotNull(true)->setUnsigned(true);
|
$table->addColumn('sess_time', 'integer')->setNotNull(true)->setUnsigned(true);
|
||||||
|
@ -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 single MERGE SQL query when supported by the database.
|
||||||
$mergeSql = $this->getMergeSql();
|
$mergeSql = $this->getMergeSql();
|
||||||
|
|
||||||
if (null !== $mergeSql) {
|
if (null !== $mergeSql) {
|
||||||
@ -183,28 +186,36 @@ 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 {
|
// When MERGE is not supported, like in Postgres, we have to use this approach that can result in
|
||||||
$deleteStmt = $this->pdo->prepare(
|
// duplicate key errors when the same session is written simultaneously. We can just catch such an
|
||||||
"DELETE FROM $this->table WHERE $this->idCol = :id"
|
// error and re-execute the update. This is similar to a serializable transaction with retry logic
|
||||||
);
|
// on serialization failures but without the overhead and without possible false positives due to
|
||||||
$deleteStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
// longer gap locking.
|
||||||
$deleteStmt->execute();
|
if (!$updateStmt->rowCount()) {
|
||||||
|
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) {
|
||||||
$this->pdo->commit();
|
// Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
|
||||||
} catch (\PDOException $e) {
|
if (0 === strpos($e->getCode(), '23')) {
|
||||||
$this->pdo->rollback();
|
$updateStmt->execute();
|
||||||
|
} else {
|
||||||
throw $e;
|
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 +241,13 @@ 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) " .
|
// It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
|
||||||
|
return "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 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)";
|
||||||
}
|
}
|
||||||
|
@ -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'));
|
||||||
|
Reference in New Issue
Block a user