DoctrineDbalAdapter.php 15 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 Doctrine\DBAL\ArrayParameterType;
  12. use Doctrine\DBAL\Configuration;
  13. use Doctrine\DBAL\Connection;
  14. use Doctrine\DBAL\DriverManager;
  15. use Doctrine\DBAL\Exception as DBALException;
  16. use Doctrine\DBAL\Exception\TableNotFoundException;
  17. use Doctrine\DBAL\ParameterType;
  18. use Doctrine\DBAL\Schema\DefaultSchemaManagerFactory;
  19. use Doctrine\DBAL\Schema\Name\Identifier;
  20. use Doctrine\DBAL\Schema\Name\UnqualifiedName;
  21. use Doctrine\DBAL\Schema\PrimaryKeyConstraint;
  22. use Doctrine\DBAL\Schema\Schema;
  23. use Doctrine\DBAL\Tools\DsnParser;
  24. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  25. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  26. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  27. use Symfony\Component\Cache\PruneableInterface;
  28. class DoctrineDbalAdapter extends AbstractAdapter implements PruneableInterface
  29. {
  30. private const MAX_KEY_LENGTH = 255;
  31. private MarshallerInterface $marshaller;
  32. private Connection $conn;
  33. private string $platformName;
  34. private string $table = 'cache_items';
  35. private string $idCol = 'item_id';
  36. private string $dataCol = 'item_data';
  37. private string $lifetimeCol = 'item_lifetime';
  38. private string $timeCol = 'item_time';
  39. /**
  40. * You can either pass an existing database Doctrine DBAL Connection or
  41. * a DSN string that will be used to connect to the database.
  42. *
  43. * The cache table is created automatically when possible.
  44. * 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. *
  53. * @throws InvalidArgumentException When namespace contains invalid characters
  54. */
  55. public function __construct(
  56. Connection|string $connOrDsn,
  57. private string $namespace = '',
  58. int $defaultLifetime = 0,
  59. array $options = [],
  60. ?MarshallerInterface $marshaller = null,
  61. ) {
  62. if (isset($namespace[0]) && preg_match('#[^-+.A-Za-z0-9]#', $namespace, $match)) {
  63. throw new InvalidArgumentException(\sprintf('Namespace contains "%s" but only characters in [-+.A-Za-z0-9] are allowed.', $match[0]));
  64. }
  65. if ($connOrDsn instanceof Connection) {
  66. $this->conn = $connOrDsn;
  67. } else {
  68. if (!class_exists(DriverManager::class)) {
  69. throw new InvalidArgumentException('Failed to parse DSN. Try running "composer require doctrine/dbal".');
  70. }
  71. $params = (new DsnParser([
  72. 'db2' => 'ibm_db2',
  73. 'mssql' => 'pdo_sqlsrv',
  74. 'mysql' => 'pdo_mysql',
  75. 'mysql2' => 'pdo_mysql',
  76. 'postgres' => 'pdo_pgsql',
  77. 'postgresql' => 'pdo_pgsql',
  78. 'pgsql' => 'pdo_pgsql',
  79. 'sqlite' => 'pdo_sqlite',
  80. 'sqlite3' => 'pdo_sqlite',
  81. ]))->parse($connOrDsn);
  82. $config = new Configuration();
  83. $config->setSchemaManagerFactory(new DefaultSchemaManagerFactory());
  84. $this->conn = DriverManager::getConnection($params, $config);
  85. }
  86. $this->maxIdLength = self::MAX_KEY_LENGTH;
  87. $this->table = $options['db_table'] ?? $this->table;
  88. $this->idCol = $options['db_id_col'] ?? $this->idCol;
  89. $this->dataCol = $options['db_data_col'] ?? $this->dataCol;
  90. $this->lifetimeCol = $options['db_lifetime_col'] ?? $this->lifetimeCol;
  91. $this->timeCol = $options['db_time_col'] ?? $this->timeCol;
  92. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  93. parent::__construct($namespace, $defaultLifetime);
  94. }
  95. /**
  96. * Creates the table to store cache items which can be called once for setup.
  97. *
  98. * Cache ID are saved in a column of maximum length 255. Cache data is
  99. * saved in a BLOB.
  100. *
  101. * @throws DBALException When the table already exists
  102. */
  103. public function createTable(): void
  104. {
  105. $schema = new Schema();
  106. $this->addTableToSchema($schema);
  107. foreach ($schema->toSql($this->conn->getDatabasePlatform()) as $sql) {
  108. $this->conn->executeStatement($sql);
  109. }
  110. }
  111. public function configureSchema(Schema $schema, Connection $forConnection, \Closure $isSameDatabase): void
  112. {
  113. if ($schema->hasTable($this->table)) {
  114. return;
  115. }
  116. if ($forConnection !== $this->conn && !$isSameDatabase($this->conn->executeStatement(...))) {
  117. return;
  118. }
  119. $this->addTableToSchema($schema);
  120. }
  121. public function prune(): bool
  122. {
  123. $deleteSql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol <= ?";
  124. $params = [time()];
  125. $paramTypes = [ParameterType::INTEGER];
  126. if ('' !== $this->namespace) {
  127. $deleteSql .= " AND $this->idCol LIKE ?";
  128. $params[] = \sprintf('%s%%', $this->namespace);
  129. $paramTypes[] = ParameterType::STRING;
  130. }
  131. try {
  132. $this->conn->executeStatement($deleteSql, $params, $paramTypes);
  133. } catch (TableNotFoundException) {
  134. }
  135. return true;
  136. }
  137. protected function doFetch(array $ids): iterable
  138. {
  139. $now = time();
  140. $expired = [];
  141. $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 (?)";
  142. $result = $this->conn->executeQuery($sql, [
  143. $now,
  144. $ids,
  145. ], [
  146. ParameterType::INTEGER,
  147. ArrayParameterType::STRING,
  148. ])->iterateNumeric();
  149. foreach ($result as $row) {
  150. if (null === $row[1]) {
  151. $expired[] = $row[0];
  152. } else {
  153. yield $row[0] => $this->marshaller->unmarshall(\is_resource($row[1]) ? stream_get_contents($row[1]) : $row[1]);
  154. }
  155. }
  156. if ($expired) {
  157. $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol <= ? AND $this->idCol IN (?)";
  158. $this->conn->executeStatement($sql, [
  159. $now,
  160. $expired,
  161. ], [
  162. ParameterType::INTEGER,
  163. ArrayParameterType::STRING,
  164. ]);
  165. }
  166. }
  167. protected function doHave(string $id): bool
  168. {
  169. $sql = "SELECT 1 FROM $this->table WHERE $this->idCol = ? AND ($this->lifetimeCol IS NULL OR $this->lifetimeCol + $this->timeCol > ?)";
  170. $result = $this->conn->executeQuery($sql, [
  171. $id,
  172. time(),
  173. ], [
  174. ParameterType::STRING,
  175. ParameterType::INTEGER,
  176. ]);
  177. return (bool) $result->fetchOne();
  178. }
  179. protected function doClear(string $namespace): bool
  180. {
  181. if ('' === $namespace) {
  182. $sql = $this->conn->getDatabasePlatform()->getTruncateTableSQL($this->table);
  183. } else {
  184. $sql = "DELETE FROM $this->table WHERE $this->idCol LIKE '$namespace%'";
  185. }
  186. try {
  187. $this->conn->executeStatement($sql);
  188. } catch (TableNotFoundException) {
  189. }
  190. return true;
  191. }
  192. protected function doDelete(array $ids): bool
  193. {
  194. $sql = "DELETE FROM $this->table WHERE $this->idCol IN (?)";
  195. try {
  196. $this->conn->executeStatement($sql, [array_values($ids)], [ArrayParameterType::STRING]);
  197. } catch (TableNotFoundException) {
  198. }
  199. return true;
  200. }
  201. protected function doSave(array $values, int $lifetime): array|bool
  202. {
  203. if (!$values = $this->marshaller->marshall($values, $failed)) {
  204. return $failed;
  205. }
  206. $platformName = $this->getPlatformName();
  207. $insertSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?)";
  208. switch ($platformName) {
  209. case 'mysql':
  210. $sql = $insertSql." ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
  211. break;
  212. case 'oci':
  213. // DUAL is Oracle specific dummy table
  214. $sql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ".
  215. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  216. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?";
  217. break;
  218. case 'sqlsrv':
  219. // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
  220. // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
  221. $sql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
  222. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  223. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
  224. break;
  225. case 'sqlite':
  226. $sql = 'INSERT OR REPLACE'.substr($insertSql, 6);
  227. break;
  228. case 'pgsql':
  229. $sql = $insertSql." ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
  230. break;
  231. default:
  232. $platformName = null;
  233. $sql = "UPDATE $this->table SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ? WHERE $this->idCol = ?";
  234. break;
  235. }
  236. $now = time();
  237. $lifetime = $lifetime ?: null;
  238. try {
  239. $stmt = $this->conn->prepare($sql);
  240. } catch (TableNotFoundException) {
  241. if (!$this->conn->isTransactionActive() || \in_array($platformName, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
  242. $this->createTable();
  243. }
  244. $stmt = $this->conn->prepare($sql);
  245. }
  246. if ('sqlsrv' === $platformName || 'oci' === $platformName) {
  247. $bind = static function ($id, $data) use ($stmt) {
  248. $stmt->bindValue(1, $id);
  249. $stmt->bindValue(2, $id);
  250. $stmt->bindValue(3, $data, ParameterType::LARGE_OBJECT);
  251. $stmt->bindValue(6, $data, ParameterType::LARGE_OBJECT);
  252. };
  253. $stmt->bindValue(4, $lifetime, ParameterType::INTEGER);
  254. $stmt->bindValue(5, $now, ParameterType::INTEGER);
  255. $stmt->bindValue(7, $lifetime, ParameterType::INTEGER);
  256. $stmt->bindValue(8, $now, ParameterType::INTEGER);
  257. } elseif (null !== $platformName) {
  258. $bind = static function ($id, $data) use ($stmt) {
  259. $stmt->bindValue(1, $id);
  260. $stmt->bindValue(2, $data, ParameterType::LARGE_OBJECT);
  261. };
  262. $stmt->bindValue(3, $lifetime, ParameterType::INTEGER);
  263. $stmt->bindValue(4, $now, ParameterType::INTEGER);
  264. } else {
  265. $stmt->bindValue(2, $lifetime, ParameterType::INTEGER);
  266. $stmt->bindValue(3, $now, ParameterType::INTEGER);
  267. $insertStmt = $this->conn->prepare($insertSql);
  268. $insertStmt->bindValue(3, $lifetime, ParameterType::INTEGER);
  269. $insertStmt->bindValue(4, $now, ParameterType::INTEGER);
  270. $bind = static function ($id, $data) use ($stmt, $insertStmt) {
  271. $stmt->bindValue(1, $data, ParameterType::LARGE_OBJECT);
  272. $stmt->bindValue(4, $id);
  273. $insertStmt->bindValue(1, $id);
  274. $insertStmt->bindValue(2, $data, ParameterType::LARGE_OBJECT);
  275. };
  276. }
  277. foreach ($values as $id => $data) {
  278. $bind($id, $data);
  279. try {
  280. $rowCount = $stmt->executeStatement();
  281. } catch (TableNotFoundException) {
  282. if (!$this->conn->isTransactionActive() || \in_array($platformName, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
  283. $this->createTable();
  284. }
  285. $rowCount = $stmt->executeStatement();
  286. }
  287. if (null === $platformName && 0 === $rowCount) {
  288. try {
  289. $insertStmt->executeStatement();
  290. } catch (DBALException) {
  291. // A concurrent write won, let it be
  292. }
  293. }
  294. }
  295. return $failed;
  296. }
  297. /**
  298. * @internal
  299. */
  300. protected function getId(mixed $key, ?string $namespace = null): string
  301. {
  302. if ('pgsql' !== $this->platformName ??= $this->getPlatformName()) {
  303. return parent::getId($key, $namespace);
  304. }
  305. if (str_contains($key, "\0") || str_contains($key, '%') || !preg_match('//u', $key)) {
  306. $key = rawurlencode($key);
  307. }
  308. return parent::getId($key, $namespace);
  309. }
  310. private function getPlatformName(): string
  311. {
  312. if (isset($this->platformName)) {
  313. return $this->platformName;
  314. }
  315. $platform = $this->conn->getDatabasePlatform();
  316. if (interface_exists(DBALException::class)) {
  317. // DBAL 4+
  318. $sqlitePlatformClass = 'Doctrine\DBAL\Platforms\SQLitePlatform';
  319. } else {
  320. $sqlitePlatformClass = 'Doctrine\DBAL\Platforms\SqlitePlatform';
  321. }
  322. return $this->platformName = match (true) {
  323. $platform instanceof \Doctrine\DBAL\Platforms\AbstractMySQLPlatform => 'mysql',
  324. $platform instanceof $sqlitePlatformClass => 'sqlite',
  325. $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform => 'pgsql',
  326. $platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform => 'oci',
  327. $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform => 'sqlsrv',
  328. default => $platform::class,
  329. };
  330. }
  331. private function addTableToSchema(Schema $schema): void
  332. {
  333. $types = [
  334. 'mysql' => 'binary',
  335. 'sqlite' => 'text',
  336. ];
  337. $table = $schema->createTable($this->table);
  338. $table->addColumn($this->idCol, $types[$this->getPlatformName()] ?? 'string', ['length' => 255]);
  339. $table->addColumn($this->dataCol, 'blob', ['length' => 16777215]);
  340. $table->addColumn($this->lifetimeCol, 'integer', ['unsigned' => true, 'notnull' => false]);
  341. $table->addColumn($this->timeCol, 'integer', ['unsigned' => true]);
  342. if (class_exists(PrimaryKeyConstraint::class)) {
  343. $table->addPrimaryKeyConstraint(new PrimaryKeyConstraint(null, [new UnqualifiedName(Identifier::unquoted($this->idCol))], true));
  344. } else {
  345. $table->setPrimaryKey([$this->idCol]);
  346. }
  347. }
  348. }