DoctrineDbalAdapter.php 15 KB

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