PdoAdapter.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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\Cache\Adapter;
  11. use Doctrine\DBAL\Connection;
  12. use Doctrine\DBAL\DBALException;
  13. use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
  14. use Doctrine\DBAL\DriverManager;
  15. use Doctrine\DBAL\Exception\TableNotFoundException;
  16. use Doctrine\DBAL\Schema\Schema;
  17. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  18. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  19. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  20. use Symfony\Component\Cache\PruneableInterface;
  21. class PdoAdapter extends AbstractAdapter implements PruneableInterface
  22. {
  23. protected $maxIdLength = 255;
  24. private $marshaller;
  25. private $conn;
  26. private $dsn;
  27. private $driver;
  28. private $serverVersion;
  29. private $table = 'cache_items';
  30. private $idCol = 'item_id';
  31. private $dataCol = 'item_data';
  32. private $lifetimeCol = 'item_lifetime';
  33. private $timeCol = 'item_time';
  34. private $username = '';
  35. private $password = '';
  36. private $connectionOptions = [];
  37. private $namespace;
  38. /**
  39. * You can either pass an existing database connection as PDO instance or
  40. * a Doctrine DBAL Connection or a DSN string that will be used to
  41. * lazy-connect to the database when the cache is actually used.
  42. *
  43. * When a Doctrine DBAL Connection is passed, the cache table is created
  44. * automatically when possible. Otherwise, use the createTable() method.
  45. *
  46. * List of available options:
  47. * * db_table: The name of the table [default: cache_items]
  48. * * db_id_col: The column where to store the cache id [default: item_id]
  49. * * db_data_col: The column where to store the cache data [default: item_data]
  50. * * db_lifetime_col: The column where to store the lifetime [default: item_lifetime]
  51. * * db_time_col: The column where to store the timestamp [default: item_time]
  52. * * db_username: The username when lazy-connect [default: '']
  53. * * db_password: The password when lazy-connect [default: '']
  54. * * db_connection_options: An array of driver-specific connection options [default: []]
  55. *
  56. * @param \PDO|Connection|string $connOrDsn a \PDO or Connection instance or DSN string or null
  57. *
  58. * @throws InvalidArgumentException When first argument is not PDO nor Connection nor string
  59. * @throws InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
  60. * @throws InvalidArgumentException When namespace contains invalid characters
  61. */
  62. public function __construct($connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = [], MarshallerInterface $marshaller = null)
  63. {
  64. if (isset($namespace[0]) && preg_match('#[^-+.A-Za-z0-9]#', $namespace, $match)) {
  65. throw new InvalidArgumentException(sprintf('Namespace contains "%s" but only characters in [-+.A-Za-z0-9] are allowed.', $match[0]));
  66. }
  67. if ($connOrDsn instanceof \PDO) {
  68. if (\PDO::ERRMODE_EXCEPTION !== $connOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
  69. 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__));
  70. }
  71. $this->conn = $connOrDsn;
  72. } elseif ($connOrDsn instanceof Connection) {
  73. $this->conn = $connOrDsn;
  74. } elseif (\is_string($connOrDsn)) {
  75. $this->dsn = $connOrDsn;
  76. } else {
  77. throw new InvalidArgumentException(sprintf('"%s" requires PDO or Doctrine\DBAL\Connection instance or DSN string as first argument, "%s" given.', __CLASS__, \is_object($connOrDsn) ? \get_class($connOrDsn) : \gettype($connOrDsn)));
  78. }
  79. $this->table = isset($options['db_table']) ? $options['db_table'] : $this->table;
  80. $this->idCol = isset($options['db_id_col']) ? $options['db_id_col'] : $this->idCol;
  81. $this->dataCol = isset($options['db_data_col']) ? $options['db_data_col'] : $this->dataCol;
  82. $this->lifetimeCol = isset($options['db_lifetime_col']) ? $options['db_lifetime_col'] : $this->lifetimeCol;
  83. $this->timeCol = isset($options['db_time_col']) ? $options['db_time_col'] : $this->timeCol;
  84. $this->username = isset($options['db_username']) ? $options['db_username'] : $this->username;
  85. $this->password = isset($options['db_password']) ? $options['db_password'] : $this->password;
  86. $this->connectionOptions = isset($options['db_connection_options']) ? $options['db_connection_options'] : $this->connectionOptions;
  87. $this->namespace = $namespace;
  88. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  89. parent::__construct($namespace, $defaultLifetime);
  90. }
  91. /**
  92. * Creates the table to store cache items which can be called once for setup.
  93. *
  94. * Cache ID are saved in a column of maximum length 255. Cache data is
  95. * saved in a BLOB.
  96. *
  97. * @throws \PDOException When the table already exists
  98. * @throws DBALException When the table already exists
  99. * @throws \DomainException When an unsupported PDO driver is used
  100. */
  101. public function createTable()
  102. {
  103. // connect if we are not yet
  104. $conn = $this->getConnection();
  105. if ($conn instanceof Connection) {
  106. $types = [
  107. 'mysql' => 'binary',
  108. 'sqlite' => 'text',
  109. 'pgsql' => 'string',
  110. 'oci' => 'string',
  111. 'sqlsrv' => 'string',
  112. ];
  113. if (!isset($types[$this->driver])) {
  114. throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver));
  115. }
  116. $schema = new Schema();
  117. $table = $schema->createTable($this->table);
  118. $table->addColumn($this->idCol, $types[$this->driver], ['length' => 255]);
  119. $table->addColumn($this->dataCol, 'blob', ['length' => 16777215]);
  120. $table->addColumn($this->lifetimeCol, 'integer', ['unsigned' => true, 'notnull' => false]);
  121. $table->addColumn($this->timeCol, 'integer', ['unsigned' => true]);
  122. $table->setPrimaryKey([$this->idCol]);
  123. foreach ($schema->toSql($conn->getDatabasePlatform()) as $sql) {
  124. $conn->exec($sql);
  125. }
  126. return;
  127. }
  128. switch ($this->driver) {
  129. case 'mysql':
  130. // We use varbinary for the ID column because it prevents unwanted conversions:
  131. // - character set conversions between server and client
  132. // - trailing space removal
  133. // - case-insensitivity
  134. // - language processing like é == e
  135. $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(255) NOT NULL PRIMARY KEY, $this->dataCol MEDIUMBLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB";
  136. break;
  137. case 'sqlite':
  138. $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)";
  139. break;
  140. case 'pgsql':
  141. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)";
  142. break;
  143. case 'oci':
  144. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(255) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)";
  145. break;
  146. case 'sqlsrv':
  147. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)";
  148. break;
  149. default:
  150. throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver));
  151. }
  152. $conn->exec($sql);
  153. }
  154. /**
  155. * {@inheritdoc}
  156. */
  157. public function prune()
  158. {
  159. $deleteSql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol <= :time";
  160. if ('' !== $this->namespace) {
  161. $deleteSql .= " AND $this->idCol LIKE :namespace";
  162. }
  163. try {
  164. $delete = $this->getConnection()->prepare($deleteSql);
  165. } catch (TableNotFoundException $e) {
  166. return true;
  167. } catch (\PDOException $e) {
  168. return true;
  169. }
  170. $delete->bindValue(':time', time(), \PDO::PARAM_INT);
  171. if ('' !== $this->namespace) {
  172. $delete->bindValue(':namespace', sprintf('%s%%', $this->namespace), \PDO::PARAM_STR);
  173. }
  174. try {
  175. return $delete->execute();
  176. } catch (TableNotFoundException $e) {
  177. return true;
  178. } catch (\PDOException $e) {
  179. return true;
  180. }
  181. }
  182. /**
  183. * {@inheritdoc}
  184. */
  185. protected function doFetch(array $ids)
  186. {
  187. $now = time();
  188. $expired = [];
  189. $sql = str_pad('', (\count($ids) << 1) - 1, '?,');
  190. $sql = "SELECT $this->idCol, CASE WHEN $this->lifetimeCol IS NULL OR $this->lifetimeCol + $this->timeCol > ? THEN $this->dataCol ELSE NULL END FROM $this->table WHERE $this->idCol IN ($sql)";
  191. $stmt = $this->getConnection()->prepare($sql);
  192. $stmt->bindValue($i = 1, $now, \PDO::PARAM_INT);
  193. foreach ($ids as $id) {
  194. $stmt->bindValue(++$i, $id);
  195. }
  196. $stmt->execute();
  197. while ($row = $stmt->fetch(\PDO::FETCH_NUM)) {
  198. if (null === $row[1]) {
  199. $expired[] = $row[0];
  200. } else {
  201. yield $row[0] => $this->marshaller->unmarshall(\is_resource($row[1]) ? stream_get_contents($row[1]) : $row[1]);
  202. }
  203. }
  204. if ($expired) {
  205. $sql = str_pad('', (\count($expired) << 1) - 1, '?,');
  206. $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol <= ? AND $this->idCol IN ($sql)";
  207. $stmt = $this->getConnection()->prepare($sql);
  208. $stmt->bindValue($i = 1, $now, \PDO::PARAM_INT);
  209. foreach ($expired as $id) {
  210. $stmt->bindValue(++$i, $id);
  211. }
  212. $stmt->execute();
  213. }
  214. }
  215. /**
  216. * {@inheritdoc}
  217. */
  218. protected function doHave(string $id)
  219. {
  220. $sql = "SELECT 1 FROM $this->table WHERE $this->idCol = :id AND ($this->lifetimeCol IS NULL OR $this->lifetimeCol + $this->timeCol > :time)";
  221. $stmt = $this->getConnection()->prepare($sql);
  222. $stmt->bindValue(':id', $id);
  223. $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
  224. $stmt->execute();
  225. return (bool) $stmt->fetchColumn();
  226. }
  227. /**
  228. * {@inheritdoc}
  229. */
  230. protected function doClear(string $namespace)
  231. {
  232. $conn = $this->getConnection();
  233. if ('' === $namespace) {
  234. if ('sqlite' === $this->driver) {
  235. $sql = "DELETE FROM $this->table";
  236. } else {
  237. $sql = "TRUNCATE TABLE $this->table";
  238. }
  239. } else {
  240. $sql = "DELETE FROM $this->table WHERE $this->idCol LIKE '$namespace%'";
  241. }
  242. try {
  243. $conn->exec($sql);
  244. } catch (TableNotFoundException $e) {
  245. } catch (\PDOException $e) {
  246. }
  247. return true;
  248. }
  249. /**
  250. * {@inheritdoc}
  251. */
  252. protected function doDelete(array $ids)
  253. {
  254. $sql = str_pad('', (\count($ids) << 1) - 1, '?,');
  255. $sql = "DELETE FROM $this->table WHERE $this->idCol IN ($sql)";
  256. try {
  257. $stmt = $this->getConnection()->prepare($sql);
  258. $stmt->execute(array_values($ids));
  259. } catch (TableNotFoundException $e) {
  260. } catch (\PDOException $e) {
  261. }
  262. return true;
  263. }
  264. /**
  265. * {@inheritdoc}
  266. */
  267. protected function doSave(array $values, int $lifetime)
  268. {
  269. if (!$values = $this->marshaller->marshall($values, $failed)) {
  270. return $failed;
  271. }
  272. $conn = $this->getConnection();
  273. $driver = $this->driver;
  274. $insertSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
  275. switch (true) {
  276. case 'mysql' === $driver:
  277. $sql = $insertSql." ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
  278. break;
  279. case 'oci' === $driver:
  280. // DUAL is Oracle specific dummy table
  281. $sql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ".
  282. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  283. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?";
  284. break;
  285. case 'sqlsrv' === $driver && version_compare($this->getServerVersion(), '10', '>='):
  286. // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
  287. // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
  288. $sql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
  289. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  290. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
  291. break;
  292. case 'sqlite' === $driver:
  293. $sql = 'INSERT OR REPLACE'.substr($insertSql, 6);
  294. break;
  295. case 'pgsql' === $driver && version_compare($this->getServerVersion(), '9.5', '>='):
  296. $sql = $insertSql." ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
  297. break;
  298. default:
  299. $driver = null;
  300. $sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id";
  301. break;
  302. }
  303. $now = time();
  304. $lifetime = $lifetime ?: null;
  305. try {
  306. $stmt = $conn->prepare($sql);
  307. } catch (TableNotFoundException $e) {
  308. if (!$conn->isTransactionActive() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
  309. $this->createTable();
  310. }
  311. $stmt = $conn->prepare($sql);
  312. } catch (\PDOException $e) {
  313. if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
  314. $this->createTable();
  315. }
  316. $stmt = $conn->prepare($sql);
  317. }
  318. if ('sqlsrv' === $driver || 'oci' === $driver) {
  319. $stmt->bindParam(1, $id);
  320. $stmt->bindParam(2, $id);
  321. $stmt->bindParam(3, $data, \PDO::PARAM_LOB);
  322. $stmt->bindValue(4, $lifetime, \PDO::PARAM_INT);
  323. $stmt->bindValue(5, $now, \PDO::PARAM_INT);
  324. $stmt->bindParam(6, $data, \PDO::PARAM_LOB);
  325. $stmt->bindValue(7, $lifetime, \PDO::PARAM_INT);
  326. $stmt->bindValue(8, $now, \PDO::PARAM_INT);
  327. } else {
  328. $stmt->bindParam(':id', $id);
  329. $stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  330. $stmt->bindValue(':lifetime', $lifetime, \PDO::PARAM_INT);
  331. $stmt->bindValue(':time', $now, \PDO::PARAM_INT);
  332. }
  333. if (null === $driver) {
  334. $insertStmt = $conn->prepare($insertSql);
  335. $insertStmt->bindParam(':id', $id);
  336. $insertStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  337. $insertStmt->bindValue(':lifetime', $lifetime, \PDO::PARAM_INT);
  338. $insertStmt->bindValue(':time', $now, \PDO::PARAM_INT);
  339. }
  340. foreach ($values as $id => $data) {
  341. try {
  342. $stmt->execute();
  343. } catch (TableNotFoundException $e) {
  344. if (!$conn->isTransactionActive() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
  345. $this->createTable();
  346. }
  347. $stmt->execute();
  348. } catch (\PDOException $e) {
  349. if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
  350. $this->createTable();
  351. }
  352. $stmt->execute();
  353. }
  354. if (null === $driver && !$stmt->rowCount()) {
  355. try {
  356. $insertStmt->execute();
  357. } catch (DBALException $e) {
  358. } catch (\PDOException $e) {
  359. // A concurrent write won, let it be
  360. }
  361. }
  362. }
  363. return $failed;
  364. }
  365. /**
  366. * @return \PDO|Connection
  367. */
  368. private function getConnection(): object
  369. {
  370. if (null === $this->conn) {
  371. if (strpos($this->dsn, '://')) {
  372. if (!class_exists(DriverManager::class)) {
  373. throw new InvalidArgumentException(sprintf('Failed to parse the DSN "%s". Try running "composer require doctrine/dbal".', $this->dsn));
  374. }
  375. $this->conn = DriverManager::getConnection(['url' => $this->dsn]);
  376. } else {
  377. $this->conn = new \PDO($this->dsn, $this->username, $this->password, $this->connectionOptions);
  378. $this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  379. }
  380. }
  381. if (null === $this->driver) {
  382. if ($this->conn instanceof \PDO) {
  383. $this->driver = $this->conn->getAttribute(\PDO::ATTR_DRIVER_NAME);
  384. } else {
  385. switch ($this->driver = $this->conn->getDriver()->getName()) {
  386. case 'mysqli':
  387. throw new \LogicException(sprintf('The adapter "%s" does not support the mysqli driver, use pdo_mysql instead.', static::class));
  388. case 'pdo_mysql':
  389. case 'drizzle_pdo_mysql':
  390. $this->driver = 'mysql';
  391. break;
  392. case 'pdo_sqlite':
  393. $this->driver = 'sqlite';
  394. break;
  395. case 'pdo_pgsql':
  396. $this->driver = 'pgsql';
  397. break;
  398. case 'oci8':
  399. case 'pdo_oracle':
  400. $this->driver = 'oci';
  401. break;
  402. case 'pdo_sqlsrv':
  403. $this->driver = 'sqlsrv';
  404. break;
  405. }
  406. }
  407. }
  408. return $this->conn;
  409. }
  410. private function getServerVersion(): string
  411. {
  412. if (null === $this->serverVersion) {
  413. $conn = $this->conn instanceof \PDO ? $this->conn : $this->conn->getWrappedConnection();
  414. if ($conn instanceof \PDO) {
  415. $this->serverVersion = $conn->getAttribute(\PDO::ATTR_SERVER_VERSION);
  416. } elseif ($conn instanceof ServerInfoAwareConnection) {
  417. $this->serverVersion = $conn->getServerVersion();
  418. } else {
  419. $this->serverVersion = '0';
  420. }
  421. }
  422. return $this->serverVersion;
  423. }
  424. }