PdoAdapter.php 16 KB

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