PdoAdapter.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 Symfony\Component\Cache\Exception\InvalidArgumentException;
  13. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  14. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  15. use Symfony\Component\Cache\PruneableInterface;
  16. class PdoAdapter extends AbstractAdapter implements PruneableInterface
  17. {
  18. protected $maxIdLength = 255;
  19. private $marshaller;
  20. private $conn;
  21. private string $dsn;
  22. private string $driver;
  23. private string $serverVersion;
  24. private mixed $table = 'cache_items';
  25. private mixed $idCol = 'item_id';
  26. private mixed $dataCol = 'item_data';
  27. private mixed $lifetimeCol = 'item_lifetime';
  28. private mixed $timeCol = 'item_time';
  29. private mixed $username = '';
  30. private mixed $password = '';
  31. private mixed $connectionOptions = [];
  32. private string $namespace;
  33. /**
  34. * You can either pass an existing database connection as PDO instance or
  35. * a DSN string that will be used to lazy-connect to the database when the
  36. * cache is actually used.
  37. *
  38. * List of available options:
  39. * * db_table: The name of the table [default: cache_items]
  40. * * db_id_col: The column where to store the cache id [default: item_id]
  41. * * db_data_col: The column where to store the cache data [default: item_data]
  42. * * db_lifetime_col: The column where to store the lifetime [default: item_lifetime]
  43. * * db_time_col: The column where to store the timestamp [default: item_time]
  44. * * db_username: The username when lazy-connect [default: '']
  45. * * db_password: The password when lazy-connect [default: '']
  46. * * db_connection_options: An array of driver-specific connection options [default: []]
  47. *
  48. * @throws InvalidArgumentException When first argument is not PDO nor Connection nor string
  49. * @throws InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
  50. * @throws InvalidArgumentException When namespace contains invalid characters
  51. */
  52. public function __construct(\PDO|string $connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = [], MarshallerInterface $marshaller = null)
  53. {
  54. if (\is_string($connOrDsn) && str_contains($connOrDsn, '://')) {
  55. throw new InvalidArgumentException(sprintf('Usage of Doctrine DBAL URL with "%s" is not supported. Use a PDO DSN or "%s" instead. Got "%s".', __CLASS__, DoctrineDbalAdapter::class, $connOrDsn));
  56. }
  57. if (isset($namespace[0]) && preg_match('#[^-+.A-Za-z0-9]#', $namespace, $match)) {
  58. throw new InvalidArgumentException(sprintf('Namespace contains "%s" but only characters in [-+.A-Za-z0-9] are allowed.', $match[0]));
  59. }
  60. if ($connOrDsn instanceof \PDO) {
  61. if (\PDO::ERRMODE_EXCEPTION !== $connOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
  62. 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__));
  63. }
  64. $this->conn = $connOrDsn;
  65. } else {
  66. $this->dsn = $connOrDsn;
  67. }
  68. $this->table = $options['db_table'] ?? $this->table;
  69. $this->idCol = $options['db_id_col'] ?? $this->idCol;
  70. $this->dataCol = $options['db_data_col'] ?? $this->dataCol;
  71. $this->lifetimeCol = $options['db_lifetime_col'] ?? $this->lifetimeCol;
  72. $this->timeCol = $options['db_time_col'] ?? $this->timeCol;
  73. $this->username = $options['db_username'] ?? $this->username;
  74. $this->password = $options['db_password'] ?? $this->password;
  75. $this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions;
  76. $this->namespace = $namespace;
  77. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  78. parent::__construct($namespace, $defaultLifetime);
  79. }
  80. /**
  81. * Creates the table to store cache items which can be called once for setup.
  82. *
  83. * Cache ID are saved in a column of maximum length 255. Cache data is
  84. * saved in a BLOB.
  85. *
  86. * @throws \PDOException When the table already exists
  87. * @throws \DomainException When an unsupported PDO driver is used
  88. */
  89. public function createTable()
  90. {
  91. // connect if we are not yet
  92. $conn = $this->getConnection();
  93. switch ($this->driver) {
  94. case 'mysql':
  95. // We use varbinary for the ID column because it prevents unwanted conversions:
  96. // - character set conversions between server and client
  97. // - trailing space removal
  98. // - case-insensitivity
  99. // - language processing like é == e
  100. $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 utf8mb4_bin, ENGINE = InnoDB";
  101. break;
  102. case 'sqlite':
  103. $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)";
  104. break;
  105. case 'pgsql':
  106. $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)";
  107. break;
  108. case 'oci':
  109. $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)";
  110. break;
  111. case 'sqlsrv':
  112. $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)";
  113. break;
  114. default:
  115. throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver));
  116. }
  117. $conn->exec($sql);
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function prune(): bool
  123. {
  124. $deleteSql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol <= :time";
  125. if ('' !== $this->namespace) {
  126. $deleteSql .= " AND $this->idCol LIKE :namespace";
  127. }
  128. $connection = $this->getConnection();
  129. try {
  130. $delete = $connection->prepare($deleteSql);
  131. } catch (\PDOException $e) {
  132. return true;
  133. }
  134. $delete->bindValue(':time', time(), \PDO::PARAM_INT);
  135. if ('' !== $this->namespace) {
  136. $delete->bindValue(':namespace', sprintf('%s%%', $this->namespace), \PDO::PARAM_STR);
  137. }
  138. try {
  139. return $delete->execute();
  140. } catch (\PDOException $e) {
  141. return true;
  142. }
  143. }
  144. /**
  145. * {@inheritdoc}
  146. */
  147. protected function doFetch(array $ids): iterable
  148. {
  149. $connection = $this->getConnection();
  150. $now = time();
  151. $expired = [];
  152. $sql = str_pad('', (\count($ids) << 1) - 1, '?,');
  153. $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)";
  154. $stmt = $connection->prepare($sql);
  155. $stmt->bindValue($i = 1, $now, \PDO::PARAM_INT);
  156. foreach ($ids as $id) {
  157. $stmt->bindValue(++$i, $id);
  158. }
  159. $result = $stmt->execute();
  160. if (\is_object($result)) {
  161. $result = $result->iterateNumeric();
  162. } else {
  163. $stmt->setFetchMode(\PDO::FETCH_NUM);
  164. $result = $stmt;
  165. }
  166. foreach ($result as $row) {
  167. if (null === $row[1]) {
  168. $expired[] = $row[0];
  169. } else {
  170. yield $row[0] => $this->marshaller->unmarshall(\is_resource($row[1]) ? stream_get_contents($row[1]) : $row[1]);
  171. }
  172. }
  173. if ($expired) {
  174. $sql = str_pad('', (\count($expired) << 1) - 1, '?,');
  175. $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol <= ? AND $this->idCol IN ($sql)";
  176. $stmt = $connection->prepare($sql);
  177. $stmt->bindValue($i = 1, $now, \PDO::PARAM_INT);
  178. foreach ($expired as $id) {
  179. $stmt->bindValue(++$i, $id);
  180. }
  181. $stmt->execute();
  182. }
  183. }
  184. /**
  185. * {@inheritdoc}
  186. */
  187. protected function doHave(string $id): bool
  188. {
  189. $connection = $this->getConnection();
  190. $sql = "SELECT 1 FROM $this->table WHERE $this->idCol = :id AND ($this->lifetimeCol IS NULL OR $this->lifetimeCol + $this->timeCol > :time)";
  191. $stmt = $connection->prepare($sql);
  192. $stmt->bindValue(':id', $id);
  193. $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
  194. $stmt->execute();
  195. return (bool) $stmt->fetchColumn();
  196. }
  197. /**
  198. * {@inheritdoc}
  199. */
  200. protected function doClear(string $namespace): bool
  201. {
  202. $conn = $this->getConnection();
  203. if ('' === $namespace) {
  204. if ('sqlite' === $this->driver) {
  205. $sql = "DELETE FROM $this->table";
  206. } else {
  207. $sql = "TRUNCATE TABLE $this->table";
  208. }
  209. } else {
  210. $sql = "DELETE FROM $this->table WHERE $this->idCol LIKE '$namespace%'";
  211. }
  212. try {
  213. $conn->exec($sql);
  214. } catch (\PDOException $e) {
  215. }
  216. return true;
  217. }
  218. /**
  219. * {@inheritdoc}
  220. */
  221. protected function doDelete(array $ids): bool
  222. {
  223. $sql = str_pad('', (\count($ids) << 1) - 1, '?,');
  224. $sql = "DELETE FROM $this->table WHERE $this->idCol IN ($sql)";
  225. try {
  226. $stmt = $this->getConnection()->prepare($sql);
  227. $stmt->execute(array_values($ids));
  228. } catch (\PDOException $e) {
  229. }
  230. return true;
  231. }
  232. /**
  233. * {@inheritdoc}
  234. */
  235. protected function doSave(array $values, int $lifetime): array|bool
  236. {
  237. if (!$values = $this->marshaller->marshall($values, $failed)) {
  238. return $failed;
  239. }
  240. $conn = $this->getConnection();
  241. $driver = $this->driver;
  242. $insertSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
  243. switch (true) {
  244. case 'mysql' === $driver:
  245. $sql = $insertSql." ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
  246. break;
  247. case 'oci' === $driver:
  248. // DUAL is Oracle specific dummy table
  249. $sql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ".
  250. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  251. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?";
  252. break;
  253. case 'sqlsrv' === $driver && version_compare($this->getServerVersion(), '10', '>='):
  254. // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
  255. // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
  256. $sql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
  257. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  258. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
  259. break;
  260. case 'sqlite' === $driver:
  261. $sql = 'INSERT OR REPLACE'.substr($insertSql, 6);
  262. break;
  263. case 'pgsql' === $driver && version_compare($this->getServerVersion(), '9.5', '>='):
  264. $sql = $insertSql." ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
  265. break;
  266. default:
  267. $driver = null;
  268. $sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id";
  269. break;
  270. }
  271. $now = time();
  272. $lifetime = $lifetime ?: null;
  273. try {
  274. $stmt = $conn->prepare($sql);
  275. } catch (\PDOException $e) {
  276. if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
  277. $this->createTable();
  278. }
  279. $stmt = $conn->prepare($sql);
  280. }
  281. // $id and $data are defined later in the loop. Binding is done by reference, values are read on execution.
  282. if ('sqlsrv' === $driver || 'oci' === $driver) {
  283. $stmt->bindParam(1, $id);
  284. $stmt->bindParam(2, $id);
  285. $stmt->bindParam(3, $data, \PDO::PARAM_LOB);
  286. $stmt->bindValue(4, $lifetime, \PDO::PARAM_INT);
  287. $stmt->bindValue(5, $now, \PDO::PARAM_INT);
  288. $stmt->bindParam(6, $data, \PDO::PARAM_LOB);
  289. $stmt->bindValue(7, $lifetime, \PDO::PARAM_INT);
  290. $stmt->bindValue(8, $now, \PDO::PARAM_INT);
  291. } else {
  292. $stmt->bindParam(':id', $id);
  293. $stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  294. $stmt->bindValue(':lifetime', $lifetime, \PDO::PARAM_INT);
  295. $stmt->bindValue(':time', $now, \PDO::PARAM_INT);
  296. }
  297. if (null === $driver) {
  298. $insertStmt = $conn->prepare($insertSql);
  299. $insertStmt->bindParam(':id', $id);
  300. $insertStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  301. $insertStmt->bindValue(':lifetime', $lifetime, \PDO::PARAM_INT);
  302. $insertStmt->bindValue(':time', $now, \PDO::PARAM_INT);
  303. }
  304. foreach ($values as $id => $data) {
  305. try {
  306. $stmt->execute();
  307. } catch (\PDOException $e) {
  308. if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
  309. $this->createTable();
  310. }
  311. $stmt->execute();
  312. }
  313. if (null === $driver && !$stmt->rowCount()) {
  314. try {
  315. $insertStmt->execute();
  316. } catch (\PDOException $e) {
  317. // A concurrent write won, let it be
  318. }
  319. }
  320. }
  321. return $failed;
  322. }
  323. private function getConnection(): \PDO
  324. {
  325. if (!isset($this->conn)) {
  326. $this->conn = new \PDO($this->dsn, $this->username, $this->password, $this->connectionOptions);
  327. $this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  328. }
  329. $this->driver ??= $this->conn->getAttribute(\PDO::ATTR_DRIVER_NAME);
  330. return $this->conn;
  331. }
  332. private function getServerVersion(): string
  333. {
  334. return $this->serverVersion ??= $this->conn->getAttribute(\PDO::ATTR_SERVER_VERSION);
  335. }
  336. }