PdoTrait.php 18 KB

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