PdoTrait.php 20 KB

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