Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; Chris@0: Chris@0: /** Chris@0: * Session handler using a PDO connection to read and write data. Chris@0: * Chris@0: * It works with MySQL, PostgreSQL, Oracle, SQL Server and SQLite and implements Chris@0: * different locking strategies to handle concurrent access to the same session. Chris@0: * Locking is necessary to prevent loss of data due to race conditions and to keep Chris@0: * the session data consistent between read() and write(). With locking, requests Chris@0: * for the same session will wait until the other one finished writing. For this Chris@0: * reason it's best practice to close a session as early as possible to improve Chris@0: * concurrency. PHPs internal files session handler also implements locking. Chris@0: * Chris@0: * Attention: Since SQLite does not support row level locks but locks the whole database, Chris@0: * it means only one session can be accessed at a time. Even different sessions would wait Chris@0: * for another to finish. So saving session in SQLite should only be considered for Chris@0: * development or prototypes. Chris@0: * Chris@0: * Session data is a binary string that can contain non-printable characters like the null byte. Chris@0: * For this reason it must be saved in a binary column in the database like BLOB in MySQL. Chris@0: * Saving it in a character column could corrupt the data. You can use createTable() Chris@0: * to initialize a correctly defined table. Chris@0: * Chris@0: * @see http://php.net/sessionhandlerinterface Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: * @author Michael Williams Chris@0: * @author Tobias Schultze Chris@0: */ Chris@0: class PdoSessionHandler implements \SessionHandlerInterface Chris@0: { Chris@0: /** Chris@0: * No locking is done. This means sessions are prone to loss of data due to Chris@0: * race conditions of concurrent requests to the same session. The last session Chris@0: * write will win in this case. It might be useful when you implement your own Chris@0: * logic to deal with this like an optimistic approach. Chris@0: */ Chris@0: const LOCK_NONE = 0; Chris@0: Chris@0: /** Chris@0: * Creates an application-level lock on a session. The disadvantage is that the Chris@0: * lock is not enforced by the database and thus other, unaware parts of the Chris@0: * application could still concurrently modify the session. The advantage is it Chris@0: * does not require a transaction. Chris@0: * This mode is not available for SQLite and not yet implemented for oci and sqlsrv. Chris@0: */ Chris@0: const LOCK_ADVISORY = 1; Chris@0: Chris@0: /** Chris@0: * Issues a real row lock. Since it uses a transaction between opening and Chris@0: * closing a session, you have to be careful when you use same database connection Chris@0: * that you also use for your application logic. This mode is the default because Chris@0: * it's the only reliable solution across DBMSs. Chris@0: */ Chris@0: const LOCK_TRANSACTIONAL = 2; Chris@0: Chris@0: /** Chris@0: * @var \PDO|null PDO instance or null when not connected yet Chris@0: */ Chris@0: private $pdo; Chris@0: Chris@0: /** Chris@0: * @var string|null|false DSN string or null for session.save_path or false when lazy connection disabled Chris@0: */ Chris@0: private $dsn = false; Chris@0: Chris@0: /** Chris@0: * @var string Database driver Chris@0: */ Chris@0: private $driver; Chris@0: Chris@0: /** Chris@0: * @var string Table name Chris@0: */ Chris@0: private $table = 'sessions'; Chris@0: Chris@0: /** Chris@0: * @var string Column for session id Chris@0: */ Chris@0: private $idCol = 'sess_id'; Chris@0: Chris@0: /** Chris@0: * @var string Column for session data Chris@0: */ Chris@0: private $dataCol = 'sess_data'; Chris@0: Chris@0: /** Chris@0: * @var string Column for lifetime Chris@0: */ Chris@0: private $lifetimeCol = 'sess_lifetime'; Chris@0: Chris@0: /** Chris@0: * @var string Column for timestamp Chris@0: */ Chris@0: private $timeCol = 'sess_time'; Chris@0: Chris@0: /** Chris@0: * @var string Username when lazy-connect Chris@0: */ Chris@0: private $username = ''; Chris@0: Chris@0: /** Chris@0: * @var string Password when lazy-connect Chris@0: */ Chris@0: private $password = ''; Chris@0: Chris@0: /** Chris@0: * @var array Connection options when lazy-connect Chris@0: */ Chris@0: private $connectionOptions = array(); Chris@0: Chris@0: /** Chris@0: * @var int The strategy for locking, see constants Chris@0: */ Chris@0: private $lockMode = self::LOCK_TRANSACTIONAL; Chris@0: Chris@0: /** Chris@0: * It's an array to support multiple reads before closing which is manual, non-standard usage. Chris@0: * Chris@0: * @var \PDOStatement[] An array of statements to release advisory locks Chris@0: */ Chris@0: private $unlockStatements = array(); Chris@0: Chris@0: /** Chris@0: * @var bool True when the current session exists but expired according to session.gc_maxlifetime Chris@0: */ Chris@0: private $sessionExpired = false; Chris@0: Chris@0: /** Chris@0: * @var bool Whether a transaction is active Chris@0: */ Chris@0: private $inTransaction = false; Chris@0: Chris@0: /** Chris@0: * @var bool Whether gc() has been called Chris@0: */ Chris@0: private $gcCalled = false; Chris@0: Chris@0: /** Chris@0: * Constructor. Chris@0: * Chris@0: * You can either pass an existing database connection as PDO instance or Chris@0: * pass a DSN string that will be used to lazy-connect to the database Chris@0: * when the session is actually used. Furthermore it's possible to pass null Chris@0: * which will then use the session.save_path ini setting as PDO DSN parameter. Chris@0: * Chris@0: * List of available options: Chris@0: * * db_table: The name of the table [default: sessions] Chris@0: * * db_id_col: The column where to store the session id [default: sess_id] Chris@0: * * db_data_col: The column where to store the session data [default: sess_data] Chris@0: * * db_lifetime_col: The column where to store the lifetime [default: sess_lifetime] Chris@0: * * db_time_col: The column where to store the timestamp [default: sess_time] Chris@0: * * db_username: The username when lazy-connect [default: ''] Chris@0: * * db_password: The password when lazy-connect [default: ''] Chris@0: * * db_connection_options: An array of driver-specific connection options [default: array()] Chris@0: * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL] Chris@0: * Chris@0: * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or null Chris@0: * @param array $options An associative array of options Chris@0: * Chris@0: * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION Chris@0: */ Chris@0: public function __construct($pdoOrDsn = null, array $options = array()) Chris@0: { Chris@0: if ($pdoOrDsn instanceof \PDO) { Chris@0: if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) { Chris@0: 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__)); Chris@0: } Chris@0: Chris@0: $this->pdo = $pdoOrDsn; Chris@0: $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); Chris@0: } else { Chris@0: $this->dsn = $pdoOrDsn; Chris@0: } Chris@0: Chris@0: $this->table = isset($options['db_table']) ? $options['db_table'] : $this->table; Chris@0: $this->idCol = isset($options['db_id_col']) ? $options['db_id_col'] : $this->idCol; Chris@0: $this->dataCol = isset($options['db_data_col']) ? $options['db_data_col'] : $this->dataCol; Chris@0: $this->lifetimeCol = isset($options['db_lifetime_col']) ? $options['db_lifetime_col'] : $this->lifetimeCol; Chris@0: $this->timeCol = isset($options['db_time_col']) ? $options['db_time_col'] : $this->timeCol; Chris@0: $this->username = isset($options['db_username']) ? $options['db_username'] : $this->username; Chris@0: $this->password = isset($options['db_password']) ? $options['db_password'] : $this->password; Chris@0: $this->connectionOptions = isset($options['db_connection_options']) ? $options['db_connection_options'] : $this->connectionOptions; Chris@0: $this->lockMode = isset($options['lock_mode']) ? $options['lock_mode'] : $this->lockMode; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates the table to store sessions which can be called once for setup. Chris@0: * Chris@0: * Session ID is saved in a column of maximum length 128 because that is enough even Chris@0: * for a 512 bit configured session.hash_function like Whirlpool. Session data is Chris@0: * saved in a BLOB. One could also use a shorter inlined varbinary column Chris@0: * if one was sure the data fits into it. Chris@0: * Chris@0: * @throws \PDOException When the table already exists Chris@0: * @throws \DomainException When an unsupported PDO driver is used Chris@0: */ Chris@0: public function createTable() Chris@0: { Chris@0: // connect if we are not yet Chris@0: $this->getConnection(); Chris@0: Chris@0: switch ($this->driver) { Chris@0: case 'mysql': Chris@0: // We use varbinary for the ID column because it prevents unwanted conversions: Chris@0: // - character set conversions between server and client Chris@0: // - trailing space removal Chris@0: // - case-insensitivity Chris@0: // - language processing like é == e Chris@0: $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"; Chris@0: break; Chris@0: case 'sqlite': Chris@0: $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)"; Chris@0: break; Chris@0: case 'pgsql': Chris@0: $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)"; Chris@0: break; Chris@0: case 'oci': Chris@0: $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)"; Chris@0: break; Chris@0: case 'sqlsrv': Chris@0: $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)"; Chris@0: break; Chris@0: default: Chris@0: throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver)); Chris@0: } Chris@0: Chris@0: try { Chris@0: $this->pdo->exec($sql); Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true when the current session exists but expired according to session.gc_maxlifetime. Chris@0: * Chris@0: * Can be used to distinguish between a new session and one that expired due to inactivity. Chris@0: * Chris@0: * @return bool Whether current session expired Chris@0: */ Chris@0: public function isSessionExpired() Chris@0: { Chris@0: return $this->sessionExpired; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function open($savePath, $sessionName) Chris@0: { Chris@0: if (null === $this->pdo) { Chris@0: $this->connect($this->dsn ?: $savePath); Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function read($sessionId) Chris@0: { Chris@0: try { Chris@0: return $this->doRead($sessionId); Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function gc($maxlifetime) Chris@0: { Chris@0: // We delay gc() to close() so that it is executed outside the transactional and blocking read-write process. Chris@0: // This way, pruning expired sessions does not block them from being started while the current session is used. Chris@0: $this->gcCalled = true; Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function destroy($sessionId) Chris@0: { Chris@0: // delete the record associated with this id Chris@0: $sql = "DELETE FROM $this->table WHERE $this->idCol = :id"; Chris@0: Chris@0: try { Chris@0: $stmt = $this->pdo->prepare($sql); Chris@0: $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@0: $stmt->execute(); Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function write($sessionId, $data) Chris@0: { Chris@0: $maxlifetime = (int) ini_get('session.gc_maxlifetime'); Chris@0: Chris@0: try { Chris@0: // We use a single MERGE SQL query when supported by the database. Chris@0: $mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime); Chris@0: if (null !== $mergeStmt) { Chris@0: $mergeStmt->execute(); Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: $updateStmt = $this->pdo->prepare( Chris@0: "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id" Chris@0: ); Chris@0: $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@0: $updateStmt->bindParam(':data', $data, \PDO::PARAM_LOB); Chris@0: $updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); Chris@0: $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@0: $updateStmt->execute(); Chris@0: Chris@0: // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in Chris@0: // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior). Chris@0: // We can just catch such an error and re-execute the update. This is similar to a serializable Chris@0: // transaction with retry logic on serialization failures but without the overhead and without possible Chris@0: // false positives due to longer gap locking. Chris@0: if (!$updateStmt->rowCount()) { Chris@0: try { Chris@0: $insertStmt = $this->pdo->prepare( Chris@0: "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)" Chris@0: ); Chris@0: $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@0: $insertStmt->bindParam(':data', $data, \PDO::PARAM_LOB); Chris@0: $insertStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); Chris@0: $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@0: $insertStmt->execute(); Chris@0: } catch (\PDOException $e) { Chris@0: // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys Chris@0: if (0 === strpos($e->getCode(), '23')) { Chris@0: $updateStmt->execute(); Chris@0: } else { Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: } Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function close() Chris@0: { Chris@0: $this->commit(); Chris@0: Chris@0: while ($unlockStmt = array_shift($this->unlockStatements)) { Chris@0: $unlockStmt->execute(); Chris@0: } Chris@0: Chris@0: if ($this->gcCalled) { Chris@0: $this->gcCalled = false; Chris@0: Chris@0: // delete the session records that have expired Chris@0: $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time"; Chris@0: Chris@0: $stmt = $this->pdo->prepare($sql); Chris@0: $stmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@0: $stmt->execute(); Chris@0: } Chris@0: Chris@0: if (false !== $this->dsn) { Chris@0: $this->pdo = null; // only close lazy-connection Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Lazy-connects to the database. Chris@0: * Chris@0: * @param string $dsn DSN string Chris@0: */ Chris@0: private function connect($dsn) Chris@0: { Chris@0: $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions); Chris@0: $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); Chris@0: $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper method to begin a transaction. Chris@0: * Chris@0: * Since SQLite does not support row level locks, we have to acquire a reserved lock Chris@0: * on the database immediately. Because of https://bugs.php.net/42766 we have to create Chris@0: * such a transaction manually which also means we cannot use PDO::commit or Chris@0: * PDO::rollback or PDO::inTransaction for SQLite. Chris@0: * Chris@0: * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions Chris@0: * due to http://www.mysqlperformanceblog.com/2013/12/12/one-more-innodb-gap-lock-to-avoid/ . Chris@0: * So we change it to READ COMMITTED. Chris@0: */ Chris@0: private function beginTransaction() Chris@0: { Chris@0: if (!$this->inTransaction) { Chris@0: if ('sqlite' === $this->driver) { Chris@0: $this->pdo->exec('BEGIN IMMEDIATE TRANSACTION'); Chris@0: } else { Chris@0: if ('mysql' === $this->driver) { Chris@0: $this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED'); Chris@0: } Chris@0: $this->pdo->beginTransaction(); Chris@0: } Chris@0: $this->inTransaction = true; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper method to commit a transaction. Chris@0: */ Chris@0: private function commit() Chris@0: { Chris@0: if ($this->inTransaction) { Chris@0: try { Chris@0: // commit read-write transaction which also releases the lock Chris@0: if ('sqlite' === $this->driver) { Chris@0: $this->pdo->exec('COMMIT'); Chris@0: } else { Chris@0: $this->pdo->commit(); Chris@0: } Chris@0: $this->inTransaction = false; Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper method to rollback a transaction. Chris@0: */ Chris@0: private function rollback() Chris@0: { Chris@0: // We only need to rollback if we are in a transaction. Otherwise the resulting Chris@0: // error would hide the real problem why rollback was called. We might not be Chris@0: // in a transaction when not using the transactional locking behavior or when Chris@0: // two callbacks (e.g. destroy and write) are invoked that both fail. Chris@0: if ($this->inTransaction) { Chris@0: if ('sqlite' === $this->driver) { Chris@0: $this->pdo->exec('ROLLBACK'); Chris@0: } else { Chris@0: $this->pdo->rollBack(); Chris@0: } Chris@0: $this->inTransaction = false; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Reads the session data in respect to the different locking strategies. Chris@0: * Chris@0: * We need to make sure we do not return session data that is already considered garbage according Chris@0: * to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes. Chris@0: * Chris@0: * @param string $sessionId Session ID Chris@0: * Chris@0: * @return string The session data Chris@0: */ Chris@0: private function doRead($sessionId) Chris@0: { Chris@0: $this->sessionExpired = false; Chris@0: Chris@0: if (self::LOCK_ADVISORY === $this->lockMode) { Chris@0: $this->unlockStatements[] = $this->doAdvisoryLock($sessionId); Chris@0: } Chris@0: Chris@0: $selectSql = $this->getSelectSql(); Chris@0: $selectStmt = $this->pdo->prepare($selectSql); Chris@0: $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@0: Chris@0: do { Chris@0: $selectStmt->execute(); Chris@0: $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM); Chris@0: Chris@0: if ($sessionRows) { Chris@0: if ($sessionRows[0][1] + $sessionRows[0][2] < time()) { Chris@0: $this->sessionExpired = true; Chris@0: Chris@0: return ''; Chris@0: } Chris@0: Chris@0: return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0]; Chris@0: } Chris@0: Chris@0: if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { Chris@0: // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block Chris@0: // until other connections to the session are committed. Chris@0: try { Chris@0: $insertStmt = $this->pdo->prepare( Chris@0: "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)" Chris@0: ); Chris@0: $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@0: $insertStmt->bindValue(':data', '', \PDO::PARAM_LOB); Chris@0: $insertStmt->bindValue(':lifetime', 0, \PDO::PARAM_INT); Chris@0: $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@0: $insertStmt->execute(); Chris@0: } catch (\PDOException $e) { Chris@0: // Catch duplicate key error because other connection created the session already. Chris@0: // It would only not be the case when the other connection destroyed the session. Chris@0: if (0 === strpos($e->getCode(), '23')) { Chris@0: // Retrieve finished session data written by concurrent connection by restarting the loop. Chris@0: // We have to start a new transaction as a failed query will mark the current transaction as Chris@0: // aborted in PostgreSQL and disallow further queries within it. Chris@0: $this->rollback(); Chris@0: $this->beginTransaction(); Chris@0: continue; Chris@0: } Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: return ''; Chris@0: } while (true); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Executes an application-level lock on the database. Chris@0: * Chris@0: * @param string $sessionId Session ID Chris@0: * Chris@0: * @return \PDOStatement The statement that needs to be executed later to release the lock Chris@0: * Chris@0: * @throws \DomainException When an unsupported PDO driver is used Chris@0: * Chris@0: * @todo implement missing advisory locks Chris@0: * - for oci using DBMS_LOCK.REQUEST Chris@0: * - for sqlsrv using sp_getapplock with LockOwner = Session Chris@0: */ Chris@0: private function doAdvisoryLock($sessionId) Chris@0: { Chris@0: switch ($this->driver) { Chris@0: case 'mysql': Chris@0: // should we handle the return value? 0 on timeout, null on error Chris@0: // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout Chris@0: $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)'); Chris@0: $stmt->bindValue(':key', $sessionId, \PDO::PARAM_STR); Chris@0: $stmt->execute(); Chris@0: Chris@0: $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)'); Chris@0: $releaseStmt->bindValue(':key', $sessionId, \PDO::PARAM_STR); Chris@0: Chris@0: return $releaseStmt; Chris@0: case 'pgsql': Chris@0: // Obtaining an exclusive session level advisory lock requires an integer key. Chris@0: // So we convert the HEX representation of the session id to an integer. Chris@0: // Since integers are signed, we have to skip one hex char to fit in the range. Chris@0: if (4 === PHP_INT_SIZE) { Chris@0: $sessionInt1 = hexdec(substr($sessionId, 0, 7)); Chris@0: $sessionInt2 = hexdec(substr($sessionId, 7, 7)); Chris@0: Chris@0: $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)'); Chris@0: $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT); Chris@0: $stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT); Chris@0: $stmt->execute(); Chris@0: Chris@0: $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)'); Chris@0: $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT); Chris@0: $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT); Chris@0: } else { Chris@0: $sessionBigInt = hexdec(substr($sessionId, 0, 15)); Chris@0: Chris@0: $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)'); Chris@0: $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT); Chris@0: $stmt->execute(); Chris@0: Chris@0: $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)'); Chris@0: $releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT); Chris@0: } Chris@0: Chris@0: return $releaseStmt; Chris@0: case 'sqlite': Chris@0: throw new \DomainException('SQLite does not support advisory locks.'); Chris@0: default: Chris@0: throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver)); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Return a locking or nonlocking SQL query to read session information. Chris@0: * Chris@0: * @return string The SQL string Chris@0: * Chris@0: * @throws \DomainException When an unsupported PDO driver is used Chris@0: */ Chris@0: private function getSelectSql() Chris@0: { Chris@0: if (self::LOCK_TRANSACTIONAL === $this->lockMode) { Chris@0: $this->beginTransaction(); Chris@0: Chris@0: switch ($this->driver) { Chris@0: case 'mysql': Chris@0: case 'oci': Chris@0: case 'pgsql': Chris@0: return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE"; Chris@0: case 'sqlsrv': Chris@0: return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id"; Chris@0: case 'sqlite': Chris@0: // we already locked when starting transaction Chris@0: break; Chris@0: default: Chris@0: throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver)); Chris@0: } Chris@0: } Chris@0: Chris@0: return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id"; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data. Chris@0: * Chris@0: * @param string $sessionId Session ID Chris@0: * @param string $data Encoded session data Chris@0: * @param int $maxlifetime session.gc_maxlifetime Chris@0: * Chris@0: * @return \PDOStatement|null The merge statement or null when not supported Chris@0: */ Chris@0: private function getMergeStatement($sessionId, $data, $maxlifetime) Chris@0: { Chris@0: $mergeSql = null; Chris@0: switch (true) { Chris@0: case 'mysql' === $this->driver: Chris@0: $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". Chris@0: "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)"; Chris@0: break; Chris@0: case 'oci' === $this->driver: Chris@0: // DUAL is Oracle specific dummy table Chris@0: $mergeSql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ". Chris@0: "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". Chris@0: "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?"; Chris@0: break; Chris@0: case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='): Chris@0: // MERGE is only available since SQL Server 2008 and must be terminated by semicolon Chris@0: // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx Chris@0: $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ". Chris@0: "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". Chris@0: "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;"; Chris@0: break; Chris@0: case 'sqlite' === $this->driver: Chris@0: $mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"; Chris@0: break; Chris@0: case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='): Chris@0: $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". Chris@0: "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)"; Chris@0: break; Chris@0: } Chris@0: Chris@0: if (null !== $mergeSql) { Chris@0: $mergeStmt = $this->pdo->prepare($mergeSql); Chris@0: Chris@0: if ('sqlsrv' === $this->driver || 'oci' === $this->driver) { Chris@0: $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR); Chris@0: $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR); Chris@0: $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB); Chris@0: $mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT); Chris@0: $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT); Chris@0: $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB); Chris@0: $mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT); Chris@0: $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT); Chris@0: } else { Chris@0: $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@0: $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB); Chris@0: $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); Chris@0: $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@0: } Chris@0: Chris@0: return $mergeStmt; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Return a PDO instance. Chris@0: * Chris@0: * @return \PDO Chris@0: */ Chris@0: protected function getConnection() Chris@0: { Chris@0: if (null === $this->pdo) { Chris@0: $this->connect($this->dsn ?: ini_get('session.save_path')); Chris@0: } Chris@0: Chris@0: return $this->pdo; Chris@0: } Chris@0: }