PdoTrait.php 20 KB

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