PdoTrait.php 17 KB

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