PdoSessionHandler.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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\Component\HttpFoundation\Session\Storage\Handler;
  11. /**
  12. * Session handler using a PDO connection to read and write data.
  13. *
  14. * It works with MySQL, PostgreSQL, Oracle, SQL Server and SQLite and implements
  15. * different locking strategies to handle concurrent access to the same session.
  16. * Locking is necessary to prevent loss of data due to race conditions and to keep
  17. * the session data consistent between read() and write(). With locking, requests
  18. * for the same session will wait until the other one finished writing. For this
  19. * reason it's best practice to close a session as early as possible to improve
  20. * concurrency. PHPs internal files session handler also implements locking.
  21. *
  22. * Attention: Since SQLite does not support row level locks but locks the whole database,
  23. * it means only one session can be accessed at a time. Even different sessions would wait
  24. * for another to finish. So saving session in SQLite should only be considered for
  25. * development or prototypes.
  26. *
  27. * Session data is a binary string that can contain non-printable characters like the null byte.
  28. * For this reason it must be saved in a binary column in the database like BLOB in MySQL.
  29. * Saving it in a character column could corrupt the data. You can use createTable()
  30. * to initialize a correctly defined table.
  31. *
  32. * @see http://php.net/sessionhandlerinterface
  33. *
  34. * @author Fabien Potencier <fabien@symfony.com>
  35. * @author Michael Williams <michael.williams@funsational.com>
  36. * @author Tobias Schultze <http://tobion.de>
  37. */
  38. class PdoSessionHandler implements \SessionHandlerInterface
  39. {
  40. /**
  41. * No locking is done. This means sessions are prone to loss of data due to
  42. * race conditions of concurrent requests to the same session. The last session
  43. * write will win in this case. It might be useful when you implement your own
  44. * logic to deal with this like an optimistic approach.
  45. */
  46. const LOCK_NONE = 0;
  47. /**
  48. * Creates an application-level lock on a session. The disadvantage is that the
  49. * lock is not enforced by the database and thus other, unaware parts of the
  50. * application could still concurrently modify the session. The advantage is it
  51. * does not require a transaction.
  52. * This mode is not available for SQLite and not yet implemented for oci and sqlsrv.
  53. */
  54. const LOCK_ADVISORY = 1;
  55. /**
  56. * Issues a real row lock. Since it uses a transaction between opening and
  57. * closing a session, you have to be careful when you use same database connection
  58. * that you also use for your application logic. This mode is the default because
  59. * it's the only reliable solution across DBMSs.
  60. */
  61. const LOCK_TRANSACTIONAL = 2;
  62. /**
  63. * @var \PDO|null PDO instance or null when not connected yet
  64. */
  65. private $pdo;
  66. /**
  67. * @var string|null|false DSN string or null for session.save_path or false when lazy connection disabled
  68. */
  69. private $dsn = false;
  70. /**
  71. * @var string Database driver
  72. */
  73. private $driver;
  74. /**
  75. * @var string Table name
  76. */
  77. private $table = 'sessions';
  78. /**
  79. * @var string Column for session id
  80. */
  81. private $idCol = 'sess_id';
  82. /**
  83. * @var string Column for session data
  84. */
  85. private $dataCol = 'sess_data';
  86. /**
  87. * @var string Column for lifetime
  88. */
  89. private $lifetimeCol = 'sess_lifetime';
  90. /**
  91. * @var string Column for timestamp
  92. */
  93. private $timeCol = 'sess_time';
  94. /**
  95. * @var string Username when lazy-connect
  96. */
  97. private $username = '';
  98. /**
  99. * @var string Password when lazy-connect
  100. */
  101. private $password = '';
  102. /**
  103. * @var array Connection options when lazy-connect
  104. */
  105. private $connectionOptions = array();
  106. /**
  107. * @var int The strategy for locking, see constants
  108. */
  109. private $lockMode = self::LOCK_TRANSACTIONAL;
  110. /**
  111. * It's an array to support multiple reads before closing which is manual, non-standard usage.
  112. *
  113. * @var \PDOStatement[] An array of statements to release advisory locks
  114. */
  115. private $unlockStatements = array();
  116. /**
  117. * @var bool True when the current session exists but expired according to session.gc_maxlifetime
  118. */
  119. private $sessionExpired = false;
  120. /**
  121. * @var bool Whether a transaction is active
  122. */
  123. private $inTransaction = false;
  124. /**
  125. * @var bool Whether gc() has been called
  126. */
  127. private $gcCalled = false;
  128. /**
  129. * Constructor.
  130. *
  131. * You can either pass an existing database connection as PDO instance or
  132. * pass a DSN string that will be used to lazy-connect to the database
  133. * when the session is actually used. Furthermore it's possible to pass null
  134. * which will then use the session.save_path ini setting as PDO DSN parameter.
  135. *
  136. * List of available options:
  137. * * db_table: The name of the table [default: sessions]
  138. * * db_id_col: The column where to store the session id [default: sess_id]
  139. * * db_data_col: The column where to store the session data [default: sess_data]
  140. * * db_lifetime_col: The column where to store the lifetime [default: sess_lifetime]
  141. * * db_time_col: The column where to store the timestamp [default: sess_time]
  142. * * db_username: The username when lazy-connect [default: '']
  143. * * db_password: The password when lazy-connect [default: '']
  144. * * db_connection_options: An array of driver-specific connection options [default: array()]
  145. * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
  146. *
  147. * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or null
  148. * @param array $options An associative array of options
  149. *
  150. * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
  151. */
  152. public function __construct($pdoOrDsn = null, array $options = array())
  153. {
  154. if ($pdoOrDsn instanceof \PDO) {
  155. if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
  156. throw new \InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION))', __CLASS__));
  157. }
  158. $this->pdo = $pdoOrDsn;
  159. $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
  160. } else {
  161. $this->dsn = $pdoOrDsn;
  162. }
  163. $this->table = isset($options['db_table']) ? $options['db_table'] : $this->table;
  164. $this->idCol = isset($options['db_id_col']) ? $options['db_id_col'] : $this->idCol;
  165. $this->dataCol = isset($options['db_data_col']) ? $options['db_data_col'] : $this->dataCol;
  166. $this->lifetimeCol = isset($options['db_lifetime_col']) ? $options['db_lifetime_col'] : $this->lifetimeCol;
  167. $this->timeCol = isset($options['db_time_col']) ? $options['db_time_col'] : $this->timeCol;
  168. $this->username = isset($options['db_username']) ? $options['db_username'] : $this->username;
  169. $this->password = isset($options['db_password']) ? $options['db_password'] : $this->password;
  170. $this->connectionOptions = isset($options['db_connection_options']) ? $options['db_connection_options'] : $this->connectionOptions;
  171. $this->lockMode = isset($options['lock_mode']) ? $options['lock_mode'] : $this->lockMode;
  172. }
  173. /**
  174. * Creates the table to store sessions which can be called once for setup.
  175. *
  176. * Session ID is saved in a column of maximum length 128 because that is enough even
  177. * for a 512 bit configured session.hash_function like Whirlpool. Session data is
  178. * saved in a BLOB. One could also use a shorter inlined varbinary column
  179. * if one was sure the data fits into it.
  180. *
  181. * @throws \PDOException When the table already exists
  182. * @throws \DomainException When an unsupported PDO driver is used
  183. */
  184. public function createTable()
  185. {
  186. // connect if we are not yet
  187. $this->getConnection();
  188. switch ($this->driver) {
  189. case 'mysql':
  190. // We use varbinary for the ID column because it prevents unwanted conversions:
  191. // - character set conversions between server and client
  192. // - trailing space removal
  193. // - case-insensitivity
  194. // - language processing like é == e
  195. $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol MEDIUMINT NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB";
  196. break;
  197. case 'sqlite':
  198. $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
  199. break;
  200. case 'pgsql':
  201. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
  202. break;
  203. case 'oci':
  204. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
  205. break;
  206. case 'sqlsrv':
  207. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
  208. break;
  209. default:
  210. throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver));
  211. }
  212. try {
  213. $this->pdo->exec($sql);
  214. } catch (\PDOException $e) {
  215. $this->rollback();
  216. throw $e;
  217. }
  218. }
  219. /**
  220. * Returns true when the current session exists but expired according to session.gc_maxlifetime.
  221. *
  222. * Can be used to distinguish between a new session and one that expired due to inactivity.
  223. *
  224. * @return bool Whether current session expired
  225. */
  226. public function isSessionExpired()
  227. {
  228. return $this->sessionExpired;
  229. }
  230. /**
  231. * {@inheritdoc}
  232. */
  233. public function open($savePath, $sessionName)
  234. {
  235. if (null === $this->pdo) {
  236. $this->connect($this->dsn ?: $savePath);
  237. }
  238. return true;
  239. }
  240. /**
  241. * {@inheritdoc}
  242. */
  243. public function read($sessionId)
  244. {
  245. try {
  246. return $this->doRead($sessionId);
  247. } catch (\PDOException $e) {
  248. $this->rollback();
  249. throw $e;
  250. }
  251. }
  252. /**
  253. * {@inheritdoc}
  254. */
  255. public function gc($maxlifetime)
  256. {
  257. // We delay gc() to close() so that it is executed outside the transactional and blocking read-write process.
  258. // This way, pruning expired sessions does not block them from being started while the current session is used.
  259. $this->gcCalled = true;
  260. return true;
  261. }
  262. /**
  263. * {@inheritdoc}
  264. */
  265. public function destroy($sessionId)
  266. {
  267. // delete the record associated with this id
  268. $sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
  269. try {
  270. $stmt = $this->pdo->prepare($sql);
  271. $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  272. $stmt->execute();
  273. } catch (\PDOException $e) {
  274. $this->rollback();
  275. throw $e;
  276. }
  277. return true;
  278. }
  279. /**
  280. * {@inheritdoc}
  281. */
  282. public function write($sessionId, $data)
  283. {
  284. $maxlifetime = (int) ini_get('session.gc_maxlifetime');
  285. try {
  286. // We use a single MERGE SQL query when supported by the database.
  287. $mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime);
  288. if (null !== $mergeStmt) {
  289. $mergeStmt->execute();
  290. return true;
  291. }
  292. $updateStmt = $this->pdo->prepare(
  293. "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id"
  294. );
  295. $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  296. $updateStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  297. $updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
  298. $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  299. $updateStmt->execute();
  300. // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in
  301. // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior).
  302. // We can just catch such an error and re-execute the update. This is similar to a serializable
  303. // transaction with retry logic on serialization failures but without the overhead and without possible
  304. // false positives due to longer gap locking.
  305. if (!$updateStmt->rowCount()) {
  306. try {
  307. $insertStmt = $this->pdo->prepare(
  308. "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"
  309. );
  310. $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  311. $insertStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  312. $insertStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
  313. $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  314. $insertStmt->execute();
  315. } catch (\PDOException $e) {
  316. // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
  317. if (0 === strpos($e->getCode(), '23')) {
  318. $updateStmt->execute();
  319. } else {
  320. throw $e;
  321. }
  322. }
  323. }
  324. } catch (\PDOException $e) {
  325. $this->rollback();
  326. throw $e;
  327. }
  328. return true;
  329. }
  330. /**
  331. * {@inheritdoc}
  332. */
  333. public function close()
  334. {
  335. $this->commit();
  336. while ($unlockStmt = array_shift($this->unlockStatements)) {
  337. $unlockStmt->execute();
  338. }
  339. if ($this->gcCalled) {
  340. $this->gcCalled = false;
  341. // delete the session records that have expired
  342. $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time";
  343. $stmt = $this->pdo->prepare($sql);
  344. $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
  345. $stmt->execute();
  346. }
  347. if (false !== $this->dsn) {
  348. $this->pdo = null; // only close lazy-connection
  349. }
  350. return true;
  351. }
  352. /**
  353. * Lazy-connects to the database.
  354. *
  355. * @param string $dsn DSN string
  356. */
  357. private function connect($dsn)
  358. {
  359. $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions);
  360. $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  361. $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
  362. }
  363. /**
  364. * Helper method to begin a transaction.
  365. *
  366. * Since SQLite does not support row level locks, we have to acquire a reserved lock
  367. * on the database immediately. Because of https://bugs.php.net/42766 we have to create
  368. * such a transaction manually which also means we cannot use PDO::commit or
  369. * PDO::rollback or PDO::inTransaction for SQLite.
  370. *
  371. * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions
  372. * due to http://www.mysqlperformanceblog.com/2013/12/12/one-more-innodb-gap-lock-to-avoid/ .
  373. * So we change it to READ COMMITTED.
  374. */
  375. private function beginTransaction()
  376. {
  377. if (!$this->inTransaction) {
  378. if ('sqlite' === $this->driver) {
  379. $this->pdo->exec('BEGIN IMMEDIATE TRANSACTION');
  380. } else {
  381. if ('mysql' === $this->driver) {
  382. $this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
  383. }
  384. $this->pdo->beginTransaction();
  385. }
  386. $this->inTransaction = true;
  387. }
  388. }
  389. /**
  390. * Helper method to commit a transaction.
  391. */
  392. private function commit()
  393. {
  394. if ($this->inTransaction) {
  395. try {
  396. // commit read-write transaction which also releases the lock
  397. if ('sqlite' === $this->driver) {
  398. $this->pdo->exec('COMMIT');
  399. } else {
  400. $this->pdo->commit();
  401. }
  402. $this->inTransaction = false;
  403. } catch (\PDOException $e) {
  404. $this->rollback();
  405. throw $e;
  406. }
  407. }
  408. }
  409. /**
  410. * Helper method to rollback a transaction.
  411. */
  412. private function rollback()
  413. {
  414. // We only need to rollback if we are in a transaction. Otherwise the resulting
  415. // error would hide the real problem why rollback was called. We might not be
  416. // in a transaction when not using the transactional locking behavior or when
  417. // two callbacks (e.g. destroy and write) are invoked that both fail.
  418. if ($this->inTransaction) {
  419. if ('sqlite' === $this->driver) {
  420. $this->pdo->exec('ROLLBACK');
  421. } else {
  422. $this->pdo->rollBack();
  423. }
  424. $this->inTransaction = false;
  425. }
  426. }
  427. /**
  428. * Reads the session data in respect to the different locking strategies.
  429. *
  430. * We need to make sure we do not return session data that is already considered garbage according
  431. * to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
  432. *
  433. * @param string $sessionId Session ID
  434. *
  435. * @return string The session data
  436. */
  437. private function doRead($sessionId)
  438. {
  439. $this->sessionExpired = false;
  440. if (self::LOCK_ADVISORY === $this->lockMode) {
  441. $this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
  442. }
  443. $selectSql = $this->getSelectSql();
  444. $selectStmt = $this->pdo->prepare($selectSql);
  445. $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  446. do {
  447. $selectStmt->execute();
  448. $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM);
  449. if ($sessionRows) {
  450. if ($sessionRows[0][1] + $sessionRows[0][2] < time()) {
  451. $this->sessionExpired = true;
  452. return '';
  453. }
  454. return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
  455. }
  456. if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
  457. // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block
  458. // until other connections to the session are committed.
  459. try {
  460. $insertStmt = $this->pdo->prepare(
  461. "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"
  462. );
  463. $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  464. $insertStmt->bindValue(':data', '', \PDO::PARAM_LOB);
  465. $insertStmt->bindValue(':lifetime', 0, \PDO::PARAM_INT);
  466. $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  467. $insertStmt->execute();
  468. } catch (\PDOException $e) {
  469. // Catch duplicate key error because other connection created the session already.
  470. // It would only not be the case when the other connection destroyed the session.
  471. if (0 === strpos($e->getCode(), '23')) {
  472. // Retrieve finished session data written by concurrent connection by restarting the loop.
  473. // We have to start a new transaction as a failed query will mark the current transaction as
  474. // aborted in PostgreSQL and disallow further queries within it.
  475. $this->rollback();
  476. $this->beginTransaction();
  477. continue;
  478. }
  479. throw $e;
  480. }
  481. }
  482. return '';
  483. } while (true);
  484. }
  485. /**
  486. * Executes an application-level lock on the database.
  487. *
  488. * @param string $sessionId Session ID
  489. *
  490. * @return \PDOStatement The statement that needs to be executed later to release the lock
  491. *
  492. * @throws \DomainException When an unsupported PDO driver is used
  493. *
  494. * @todo implement missing advisory locks
  495. * - for oci using DBMS_LOCK.REQUEST
  496. * - for sqlsrv using sp_getapplock with LockOwner = Session
  497. */
  498. private function doAdvisoryLock($sessionId)
  499. {
  500. switch ($this->driver) {
  501. case 'mysql':
  502. // should we handle the return value? 0 on timeout, null on error
  503. // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout
  504. $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)');
  505. $stmt->bindValue(':key', $sessionId, \PDO::PARAM_STR);
  506. $stmt->execute();
  507. $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)');
  508. $releaseStmt->bindValue(':key', $sessionId, \PDO::PARAM_STR);
  509. return $releaseStmt;
  510. case 'pgsql':
  511. // Obtaining an exclusive session level advisory lock requires an integer key.
  512. // So we convert the HEX representation of the session id to an integer.
  513. // Since integers are signed, we have to skip one hex char to fit in the range.
  514. if (4 === PHP_INT_SIZE) {
  515. $sessionInt1 = hexdec(substr($sessionId, 0, 7));
  516. $sessionInt2 = hexdec(substr($sessionId, 7, 7));
  517. $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)');
  518. $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
  519. $stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
  520. $stmt->execute();
  521. $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)');
  522. $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
  523. $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
  524. } else {
  525. $sessionBigInt = hexdec(substr($sessionId, 0, 15));
  526. $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)');
  527. $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
  528. $stmt->execute();
  529. $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)');
  530. $releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
  531. }
  532. return $releaseStmt;
  533. case 'sqlite':
  534. throw new \DomainException('SQLite does not support advisory locks.');
  535. default:
  536. throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver));
  537. }
  538. }
  539. /**
  540. * Return a locking or nonlocking SQL query to read session information.
  541. *
  542. * @return string The SQL string
  543. *
  544. * @throws \DomainException When an unsupported PDO driver is used
  545. */
  546. private function getSelectSql()
  547. {
  548. if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
  549. $this->beginTransaction();
  550. switch ($this->driver) {
  551. case 'mysql':
  552. case 'oci':
  553. case 'pgsql':
  554. return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
  555. case 'sqlsrv':
  556. return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
  557. case 'sqlite':
  558. // we already locked when starting transaction
  559. break;
  560. default:
  561. throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver));
  562. }
  563. }
  564. return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
  565. }
  566. /**
  567. * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data.
  568. *
  569. * @param string $sessionId Session ID
  570. * @param string $data Encoded session data
  571. * @param int $maxlifetime session.gc_maxlifetime
  572. *
  573. * @return \PDOStatement|null The merge statement or null when not supported
  574. */
  575. private function getMergeStatement($sessionId, $data, $maxlifetime)
  576. {
  577. $mergeSql = null;
  578. switch (true) {
  579. case 'mysql' === $this->driver:
  580. $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
  581. "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
  582. break;
  583. case 'oci' === $this->driver:
  584. // DUAL is Oracle specific dummy table
  585. $mergeSql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ".
  586. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  587. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?";
  588. break;
  589. case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
  590. // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
  591. // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
  592. $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
  593. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  594. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
  595. break;
  596. case 'sqlite' === $this->driver:
  597. $mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
  598. break;
  599. case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='):
  600. $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
  601. "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
  602. break;
  603. }
  604. if (null !== $mergeSql) {
  605. $mergeStmt = $this->pdo->prepare($mergeSql);
  606. if ('sqlsrv' === $this->driver || 'oci' === $this->driver) {
  607. $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR);
  608. $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR);
  609. $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB);
  610. $mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT);
  611. $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT);
  612. $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB);
  613. $mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT);
  614. $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT);
  615. } else {
  616. $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  617. $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  618. $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
  619. $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  620. }
  621. return $mergeStmt;
  622. }
  623. }
  624. /**
  625. * Return a PDO instance.
  626. *
  627. * @return \PDO
  628. */
  629. protected function getConnection()
  630. {
  631. if (null === $this->pdo) {
  632. $this->connect($this->dsn ?: ini_get('session.save_path'));
  633. }
  634. return $this->pdo;
  635. }
  636. }