Connection.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <?php
  2. namespace Drupal\Core\Database\Driver\pgsql;
  3. use Drupal\Core\Database\Database;
  4. use Drupal\Core\Database\Connection as DatabaseConnection;
  5. use Drupal\Core\Database\DatabaseAccessDeniedException;
  6. use Drupal\Core\Database\DatabaseNotFoundException;
  7. /**
  8. * @addtogroup database
  9. * @{
  10. */
  11. /**
  12. * PostgreSQL implementation of \Drupal\Core\Database\Connection.
  13. */
  14. class Connection extends DatabaseConnection {
  15. /**
  16. * The name by which to obtain a lock for retrieve the next insert id.
  17. */
  18. const POSTGRESQL_NEXTID_LOCK = 1000;
  19. /**
  20. * Error code for "Unknown database" error.
  21. */
  22. const DATABASE_NOT_FOUND = 7;
  23. /**
  24. * Error code for "Connection failure" errors.
  25. *
  26. * Technically this is an internal error code that will only be shown in the
  27. * PDOException message. It will need to get extracted.
  28. */
  29. const CONNECTION_FAILURE = '08006';
  30. /**
  31. * A map of condition operators to PostgreSQL operators.
  32. *
  33. * In PostgreSQL, 'LIKE' is case-sensitive. ILIKE should be used for
  34. * case-insensitive statements.
  35. */
  36. protected static $postgresqlConditionOperatorMap = [
  37. 'LIKE' => ['operator' => 'ILIKE'],
  38. 'LIKE BINARY' => ['operator' => 'LIKE'],
  39. 'NOT LIKE' => ['operator' => 'NOT ILIKE'],
  40. 'REGEXP' => ['operator' => '~*'],
  41. ];
  42. /**
  43. * The list of PostgreSQL reserved key words.
  44. *
  45. * @see http://www.postgresql.org/docs/9.4/static/sql-keywords-appendix.html
  46. */
  47. protected $postgresqlReservedKeyWords = ['all', 'analyse', 'analyze', 'and',
  48. 'any', 'array', 'as', 'asc', 'asymmetric', 'authorization', 'binary', 'both',
  49. 'case', 'cast', 'check', 'collate', 'collation', 'column', 'concurrently',
  50. 'constraint', 'create', 'cross', 'current_catalog', 'current_date',
  51. 'current_role', 'current_schema', 'current_time', 'current_timestamp',
  52. 'current_user', 'default', 'deferrable', 'desc', 'distinct', 'do', 'else',
  53. 'end', 'except', 'false', 'fetch', 'for', 'foreign', 'freeze', 'from', 'full',
  54. 'grant', 'group', 'having', 'ilike', 'in', 'initially', 'inner', 'intersect',
  55. 'into', 'is', 'isnull', 'join', 'lateral', 'leading', 'left', 'like', 'limit',
  56. 'localtime', 'localtimestamp', 'natural', 'not', 'notnull', 'null', 'offset',
  57. 'on', 'only', 'or', 'order', 'outer', 'over', 'overlaps', 'placing',
  58. 'primary', 'references', 'returning', 'right', 'select', 'session_user',
  59. 'similar', 'some', 'symmetric', 'table', 'then', 'to', 'trailing', 'true',
  60. 'union', 'unique', 'user', 'using', 'variadic', 'verbose', 'when', 'where',
  61. 'window', 'with',
  62. ];
  63. /**
  64. * Constructs a connection object.
  65. */
  66. public function __construct(\PDO $connection, array $connection_options) {
  67. parent::__construct($connection, $connection_options);
  68. // This driver defaults to transaction support, except if explicitly passed FALSE.
  69. $this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);
  70. // Transactional DDL is always available in PostgreSQL,
  71. // but we'll only enable it if standard transactions are.
  72. $this->transactionalDDLSupport = $this->transactionSupport;
  73. $this->connectionOptions = $connection_options;
  74. // Force PostgreSQL to use the UTF-8 character set by default.
  75. $this->connection->exec("SET NAMES 'UTF8'");
  76. // Execute PostgreSQL init_commands.
  77. if (isset($connection_options['init_commands'])) {
  78. $this->connection->exec(implode('; ', $connection_options['init_commands']));
  79. }
  80. }
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public static function open(array &$connection_options = []) {
  85. // Default to TCP connection on port 5432.
  86. if (empty($connection_options['port'])) {
  87. $connection_options['port'] = 5432;
  88. }
  89. // PostgreSQL in trust mode doesn't require a password to be supplied.
  90. if (empty($connection_options['password'])) {
  91. $connection_options['password'] = NULL;
  92. }
  93. // If the password contains a backslash it is treated as an escape character
  94. // http://bugs.php.net/bug.php?id=53217
  95. // so backslashes in the password need to be doubled up.
  96. // The bug was reported against pdo_pgsql 1.0.2, backslashes in passwords
  97. // will break on this doubling up when the bug is fixed, so check the version
  98. // elseif (phpversion('pdo_pgsql') < 'version_this_was_fixed_in') {
  99. else {
  100. $connection_options['password'] = str_replace('\\', '\\\\', $connection_options['password']);
  101. }
  102. $connection_options['database'] = (!empty($connection_options['database']) ? $connection_options['database'] : 'template1');
  103. $dsn = 'pgsql:host=' . $connection_options['host'] . ' dbname=' . $connection_options['database'] . ' port=' . $connection_options['port'];
  104. // Allow PDO options to be overridden.
  105. $connection_options += [
  106. 'pdo' => [],
  107. ];
  108. $connection_options['pdo'] += [
  109. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  110. // Prepared statements are most effective for performance when queries
  111. // are recycled (used several times). However, if they are not re-used,
  112. // prepared statements become inefficient. Since most of Drupal's
  113. // prepared queries are not re-used, it should be faster to emulate
  114. // the preparation than to actually ready statements for re-use. If in
  115. // doubt, reset to FALSE and measure performance.
  116. \PDO::ATTR_EMULATE_PREPARES => TRUE,
  117. // Convert numeric values to strings when fetching.
  118. \PDO::ATTR_STRINGIFY_FETCHES => TRUE,
  119. ];
  120. try {
  121. $pdo = new \PDO($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);
  122. }
  123. catch (\PDOException $e) {
  124. if (static::getSQLState($e) == static::CONNECTION_FAILURE) {
  125. if (strpos($e->getMessage(), 'password authentication failed for user') !== FALSE) {
  126. throw new DatabaseAccessDeniedException($e->getMessage(), $e->getCode(), $e);
  127. }
  128. elseif (strpos($e->getMessage(), 'database') !== FALSE && strpos($e->getMessage(), 'does not exist') !== FALSE) {
  129. throw new DatabaseNotFoundException($e->getMessage(), $e->getCode(), $e);
  130. }
  131. }
  132. throw $e;
  133. }
  134. return $pdo;
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function query($query, array $args = [], $options = []) {
  140. $options += $this->defaultOptions();
  141. // The PDO PostgreSQL driver has a bug which doesn't type cast booleans
  142. // correctly when parameters are bound using associative arrays.
  143. // @see http://bugs.php.net/bug.php?id=48383
  144. foreach ($args as &$value) {
  145. if (is_bool($value)) {
  146. $value = (int) $value;
  147. }
  148. }
  149. // We need to wrap queries with a savepoint if:
  150. // - Currently in a transaction.
  151. // - A 'mimic_implicit_commit' does not exist already.
  152. // - The query is not a savepoint query.
  153. $wrap_with_savepoint = $this->inTransaction() &&
  154. !isset($this->transactionLayers['mimic_implicit_commit']) &&
  155. !(is_string($query) && (
  156. stripos($query, 'ROLLBACK TO SAVEPOINT ') === 0 ||
  157. stripos($query, 'RELEASE SAVEPOINT ') === 0 ||
  158. stripos($query, 'SAVEPOINT ') === 0
  159. )
  160. );
  161. if ($wrap_with_savepoint) {
  162. // Create a savepoint so we can rollback a failed query. This is so we can
  163. // mimic MySQL and SQLite transactions which don't fail if a single query
  164. // fails. This is important for tables that are created on demand. For
  165. // example, \Drupal\Core\Cache\DatabaseBackend.
  166. $this->addSavepoint();
  167. try {
  168. $return = parent::query($query, $args, $options);
  169. $this->releaseSavepoint();
  170. }
  171. catch (\Exception $e) {
  172. $this->rollbackSavepoint();
  173. throw $e;
  174. }
  175. }
  176. else {
  177. $return = parent::query($query, $args, $options);
  178. }
  179. return $return;
  180. }
  181. public function prepareQuery($query) {
  182. // mapConditionOperator converts some operations (LIKE, REGEXP, etc.) to
  183. // PostgreSQL equivalents (ILIKE, ~*, etc.). However PostgreSQL doesn't
  184. // automatically cast the fields to the right type for these operators,
  185. // so we need to alter the query and add the type-cast.
  186. return parent::prepareQuery(preg_replace('/ ([^ ]+) +(I*LIKE|NOT +I*LIKE|~\*) /i', ' ${1}::text ${2} ', $query));
  187. }
  188. public function queryRange($query, $from, $count, array $args = [], array $options = []) {
  189. return $this->query($query . ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from, $args, $options);
  190. }
  191. public function queryTemporary($query, array $args = [], array $options = []) {
  192. $tablename = $this->generateTemporaryTableName();
  193. $this->query('CREATE TEMPORARY TABLE {' . $tablename . '} AS ' . $query, $args, $options);
  194. return $tablename;
  195. }
  196. /**
  197. * {@inheritdoc}
  198. */
  199. public function escapeField($field) {
  200. $escaped = parent::escapeField($field);
  201. // Remove any invalid start character.
  202. $escaped = preg_replace('/^[^A-Za-z0-9_]/', '', $escaped);
  203. // The pgsql database driver does not support field names that contain
  204. // periods (supported by PostgreSQL server) because this method may be
  205. // called by a field with a table alias as part of SQL conditions or
  206. // order by statements. This will consider a period as a table alias
  207. // identifier, and split the string at the first period.
  208. if (preg_match('/^([A-Za-z0-9_]+)"?[.]"?([A-Za-z0-9_.]+)/', $escaped, $parts)) {
  209. $table = $parts[1];
  210. $column = $parts[2];
  211. // Use escape alias because escapeField may contain multiple periods that
  212. // need to be escaped.
  213. $escaped = $this->escapeTable($table) . '.' . $this->escapeAlias($column);
  214. }
  215. else {
  216. $escaped = $this->doEscape($escaped);
  217. }
  218. return $escaped;
  219. }
  220. /**
  221. * {@inheritdoc}
  222. */
  223. public function escapeAlias($field) {
  224. $escaped = preg_replace('/[^A-Za-z0-9_]+/', '', $field);
  225. $escaped = $this->doEscape($escaped);
  226. return $escaped;
  227. }
  228. /**
  229. * {@inheritdoc}
  230. */
  231. public function escapeTable($table) {
  232. $escaped = parent::escapeTable($table);
  233. // Ensure that each part (database, schema and table) of the table name is
  234. // properly and independently escaped.
  235. $parts = explode('.', $escaped);
  236. $parts = array_map([$this, 'doEscape'], $parts);
  237. $escaped = implode('.', $parts);
  238. return $escaped;
  239. }
  240. /**
  241. * Escape a string if needed.
  242. *
  243. * @param $string
  244. * The string to escape.
  245. * @return string
  246. * The escaped string.
  247. */
  248. protected function doEscape($string) {
  249. // Quote identifier to make it case-sensitive.
  250. if (preg_match('/[A-Z]/', $string)) {
  251. $string = '"' . $string . '"';
  252. }
  253. elseif (in_array(strtolower($string), $this->postgresqlReservedKeyWords)) {
  254. // Quote the string for PostgreSQL reserved key words.
  255. $string = '"' . $string . '"';
  256. }
  257. return $string;
  258. }
  259. public function driver() {
  260. return 'pgsql';
  261. }
  262. public function databaseType() {
  263. return 'pgsql';
  264. }
  265. /**
  266. * Overrides \Drupal\Core\Database\Connection::createDatabase().
  267. *
  268. * @param string $database
  269. * The name of the database to create.
  270. *
  271. * @throws \Drupal\Core\Database\DatabaseNotFoundException
  272. */
  273. public function createDatabase($database) {
  274. // Escape the database name.
  275. $database = Database::getConnection()->escapeDatabase($database);
  276. // If the PECL intl extension is installed, use it to determine the proper
  277. // locale. Otherwise, fall back to en_US.
  278. if (class_exists('Locale')) {
  279. $locale = \Locale::getDefault();
  280. }
  281. else {
  282. $locale = 'en_US';
  283. }
  284. try {
  285. // Create the database and set it as active.
  286. $this->connection->exec("CREATE DATABASE $database WITH TEMPLATE template0 ENCODING='utf8' LC_CTYPE='$locale.utf8' LC_COLLATE='$locale.utf8'");
  287. }
  288. catch (\Exception $e) {
  289. throw new DatabaseNotFoundException($e->getMessage());
  290. }
  291. }
  292. public function mapConditionOperator($operator) {
  293. return isset(static::$postgresqlConditionOperatorMap[$operator]) ? static::$postgresqlConditionOperatorMap[$operator] : NULL;
  294. }
  295. /**
  296. * Retrieve a the next id in a sequence.
  297. *
  298. * PostgreSQL has built in sequences. We'll use these instead of inserting
  299. * and updating a sequences table.
  300. */
  301. public function nextId($existing = 0) {
  302. // Retrieve the name of the sequence. This information cannot be cached
  303. // because the prefix may change, for example, like it does in simpletests.
  304. $sequence_name = $this->makeSequenceName('sequences', 'value');
  305. // When PostgreSQL gets a value too small then it will lock the table,
  306. // retry the INSERT and if it's still too small then alter the sequence.
  307. $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
  308. if ($id > $existing) {
  309. return $id;
  310. }
  311. // PostgreSQL advisory locks are simply locks to be used by an
  312. // application such as Drupal. This will prevent other Drupal processes
  313. // from altering the sequence while we are.
  314. $this->query("SELECT pg_advisory_lock(" . self::POSTGRESQL_NEXTID_LOCK . ")");
  315. // While waiting to obtain the lock, the sequence may have been altered
  316. // so lets try again to obtain an adequate value.
  317. $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
  318. if ($id > $existing) {
  319. $this->query("SELECT pg_advisory_unlock(" . self::POSTGRESQL_NEXTID_LOCK . ")");
  320. return $id;
  321. }
  322. // Reset the sequence to a higher value than the existing id.
  323. $this->query("ALTER SEQUENCE " . $sequence_name . " RESTART WITH " . ($existing + 1));
  324. // Retrieve the next id. We know this will be as high as we want it.
  325. $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
  326. $this->query("SELECT pg_advisory_unlock(" . self::POSTGRESQL_NEXTID_LOCK . ")");
  327. return $id;
  328. }
  329. /**
  330. * {@inheritdoc}
  331. */
  332. public function getFullQualifiedTableName($table) {
  333. $options = $this->getConnectionOptions();
  334. $prefix = $this->tablePrefix($table);
  335. // The fully qualified table name in PostgreSQL is in the form of
  336. // <database>.<schema>.<table>, so we have to include the 'public' schema in
  337. // the return value.
  338. return $options['database'] . '.public.' . $prefix . $table;
  339. }
  340. /**
  341. * Add a new savepoint with an unique name.
  342. *
  343. * The main use for this method is to mimic InnoDB functionality, which
  344. * provides an inherent savepoint before any query in a transaction.
  345. *
  346. * @param $savepoint_name
  347. * A string representing the savepoint name. By default,
  348. * "mimic_implicit_commit" is used.
  349. *
  350. * @see Drupal\Core\Database\Connection::pushTransaction()
  351. */
  352. public function addSavepoint($savepoint_name = 'mimic_implicit_commit') {
  353. if ($this->inTransaction()) {
  354. $this->pushTransaction($savepoint_name);
  355. }
  356. }
  357. /**
  358. * Release a savepoint by name.
  359. *
  360. * @param $savepoint_name
  361. * A string representing the savepoint name. By default,
  362. * "mimic_implicit_commit" is used.
  363. *
  364. * @see Drupal\Core\Database\Connection::popTransaction()
  365. */
  366. public function releaseSavepoint($savepoint_name = 'mimic_implicit_commit') {
  367. if (isset($this->transactionLayers[$savepoint_name])) {
  368. $this->popTransaction($savepoint_name);
  369. }
  370. }
  371. /**
  372. * Rollback a savepoint by name if it exists.
  373. *
  374. * @param $savepoint_name
  375. * A string representing the savepoint name. By default,
  376. * "mimic_implicit_commit" is used.
  377. */
  378. public function rollbackSavepoint($savepoint_name = 'mimic_implicit_commit') {
  379. if (isset($this->transactionLayers[$savepoint_name])) {
  380. $this->rollBack($savepoint_name);
  381. }
  382. }
  383. /**
  384. * {@inheritdoc}
  385. */
  386. public function upsert($table, array $options = []) {
  387. // Use the (faster) native Upsert implementation for PostgreSQL >= 9.5.
  388. if (version_compare($this->version(), '9.5', '>=')) {
  389. $class = $this->getDriverClass('NativeUpsert');
  390. }
  391. else {
  392. $class = $this->getDriverClass('Upsert');
  393. }
  394. return new $class($this, $table, $options);
  395. }
  396. }
  397. /**
  398. * @} End of "addtogroup database".
  399. */