DbalSessionHandler.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Doctrine\HttpFoundation;
  11. use Doctrine\DBAL\Connection;
  12. use Doctrine\DBAL\Driver\DriverException;
  13. use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
  14. use Doctrine\DBAL\Platforms\SQLServer2008Platform;
  15. /**
  16. * DBAL based session storage.
  17. *
  18. * This implementation is very similar to Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler
  19. * but uses a Doctrine connection and thus also works with non-PDO-based drivers like mysqli and OCI8.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  23. * @author Tobias Schultze <http://tobion.de>
  24. */
  25. class DbalSessionHandler implements \SessionHandlerInterface
  26. {
  27. /**
  28. * @var Connection
  29. */
  30. private $con;
  31. /**
  32. * @var string
  33. */
  34. private $table;
  35. /**
  36. * @var string Column for session id
  37. */
  38. private $idCol = 'sess_id';
  39. /**
  40. * @var string Column for session data
  41. */
  42. private $dataCol = 'sess_data';
  43. /**
  44. * @var string Column for timestamp
  45. */
  46. private $timeCol = 'sess_time';
  47. /**
  48. * @param Connection $con A connection
  49. * @param string $tableName Table name
  50. */
  51. public function __construct(Connection $con, $tableName = 'sessions')
  52. {
  53. $this->con = $con;
  54. $this->table = $tableName;
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function open($savePath, $sessionName)
  60. {
  61. return true;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function close()
  67. {
  68. return true;
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function destroy($sessionId)
  74. {
  75. // delete the record associated with this id
  76. $sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
  77. try {
  78. $stmt = $this->con->prepare($sql);
  79. $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  80. $stmt->execute();
  81. } catch (\Exception $e) {
  82. throw new \RuntimeException(sprintf('Exception was thrown when trying to delete a session: %s', $e->getMessage()), 0, $e);
  83. }
  84. return true;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. */
  89. public function gc($maxlifetime)
  90. {
  91. // delete the session records that have expired
  92. $sql = "DELETE FROM $this->table WHERE $this->timeCol < :time";
  93. try {
  94. $stmt = $this->con->prepare($sql);
  95. $stmt->bindValue(':time', time() - $maxlifetime, \PDO::PARAM_INT);
  96. $stmt->execute();
  97. } catch (\Exception $e) {
  98. throw new \RuntimeException(sprintf('Exception was thrown when trying to delete expired sessions: %s', $e->getMessage()), 0, $e);
  99. }
  100. return true;
  101. }
  102. /**
  103. * {@inheritdoc}
  104. */
  105. public function read($sessionId)
  106. {
  107. $sql = "SELECT $this->dataCol FROM $this->table WHERE $this->idCol = :id";
  108. try {
  109. $stmt = $this->con->prepare($sql);
  110. $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  111. $stmt->execute();
  112. // We use fetchAll instead of fetchColumn to make sure the DB cursor gets closed
  113. $sessionRows = $stmt->fetchAll(\PDO::FETCH_NUM);
  114. if ($sessionRows) {
  115. return base64_decode($sessionRows[0][0]);
  116. }
  117. return '';
  118. } catch (\Exception $e) {
  119. throw new \RuntimeException(sprintf('Exception was thrown when trying to read the session data: %s', $e->getMessage()), 0, $e);
  120. }
  121. }
  122. /**
  123. * {@inheritdoc}
  124. */
  125. public function write($sessionId, $data)
  126. {
  127. $encoded = base64_encode($data);
  128. try {
  129. // We use a single MERGE SQL query when supported by the database.
  130. $mergeSql = $this->getMergeSql();
  131. if (null !== $mergeSql) {
  132. $mergeStmt = $this->con->prepare($mergeSql);
  133. $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  134. $mergeStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
  135. $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  136. // Oracle has a bug that will intermittently happen if you
  137. // have only 1 bind on a CLOB field for 2 different statements
  138. // (INSERT and UPDATE in this case)
  139. if ('oracle' == $this->con->getDatabasePlatform()->getName()) {
  140. $mergeStmt->bindParam(':data2', $encoded, \PDO::PARAM_STR);
  141. }
  142. $mergeStmt->execute();
  143. return true;
  144. }
  145. $updateStmt = $this->con->prepare(
  146. "UPDATE $this->table SET $this->dataCol = :data, $this->timeCol = :time WHERE $this->idCol = :id"
  147. );
  148. $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  149. $updateStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
  150. $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  151. $updateStmt->execute();
  152. // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in
  153. // duplicate key errors when the same session is written simultaneously. We can just catch such an
  154. // error and re-execute the update. This is similar to a serializable transaction with retry logic
  155. // on serialization failures but without the overhead and without possible false positives due to
  156. // longer gap locking.
  157. if (!$updateStmt->rowCount()) {
  158. try {
  159. $insertStmt = $this->con->prepare(
  160. "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)"
  161. );
  162. $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  163. $insertStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
  164. $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  165. $insertStmt->execute();
  166. } catch (\Exception $e) {
  167. $driverException = $e->getPrevious();
  168. // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
  169. // DriverException only available since DBAL 2.5
  170. if (
  171. ($driverException instanceof DriverException && 0 === strpos($driverException->getSQLState(), '23')) ||
  172. ($driverException instanceof \PDOException && 0 === strpos($driverException->getCode(), '23'))
  173. ) {
  174. $updateStmt->execute();
  175. } else {
  176. throw $e;
  177. }
  178. }
  179. }
  180. } catch (\Exception $e) {
  181. throw new \RuntimeException(sprintf('Exception was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
  182. }
  183. return true;
  184. }
  185. /**
  186. * Returns a merge/upsert (i.e. insert or update) SQL query when supported by the database.
  187. *
  188. * @return string|null The SQL string or null when not supported
  189. */
  190. private function getMergeSql()
  191. {
  192. $platform = $this->con->getDatabasePlatform()->getName();
  193. switch (true) {
  194. case 'mysql' === $platform:
  195. return "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) ".
  196. "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->timeCol = VALUES($this->timeCol)";
  197. case 'oracle' === $platform:
  198. // DUAL is Oracle specific dummy table
  199. return "MERGE INTO $this->table USING DUAL ON ($this->idCol = :id) ".
  200. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) ".
  201. "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data2, $this->timeCol = :time";
  202. case $this->con->getDatabasePlatform() instanceof SQLServer2008Platform:
  203. // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
  204. // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
  205. return "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = :id) ".
  206. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) ".
  207. "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->timeCol = :time;";
  208. case 'sqlite' === $platform:
  209. return "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)";
  210. case 'postgresql' === $platform && version_compare($this->getServerVersion(), '9.5', '>='):
  211. return "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) ".
  212. "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->timeCol)";
  213. }
  214. }
  215. private function getServerVersion()
  216. {
  217. $params = $this->con->getParams();
  218. // Explicit platform version requested (supersedes auto-detection), so we respect it.
  219. if (isset($params['serverVersion'])) {
  220. return $params['serverVersion'];
  221. }
  222. $wrappedConnection = $this->con->getWrappedConnection();
  223. if ($wrappedConnection instanceof ServerInfoAwareConnection) {
  224. return $wrappedConnection->getServerVersion();
  225. }
  226. // Support DBAL 2.4 by accessing it directly when using PDO PgSQL
  227. if ($wrappedConnection instanceof \PDO) {
  228. return $wrappedConnection->getAttribute(\PDO::ATTR_SERVER_VERSION);
  229. }
  230. // If we cannot guess the version, the empty string will mean we won't use the code for newer versions when doing version checks.
  231. return '';
  232. }
  233. }