3 namespace Drupal\Core\Database\Driver\pgsql\Install;
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\Install\Tasks as InstallTasks;
7 use Drupal\Core\Database\DatabaseNotFoundException;
10 * Specifies installation tasks for PostgreSQL databases.
12 class Tasks extends InstallTasks {
17 protected $pdoDriver = 'pgsql';
20 * Constructs a \Drupal\Core\Database\Driver\pgsql\Install\Tasks object.
22 public function __construct() {
24 'function' => 'checkEncoding',
28 'function' => 'checkBinaryOutput',
32 'function' => 'checkStandardConformingStrings',
36 'function' => 'initializeDatabase',
44 public function name() {
45 return t('PostgreSQL');
51 public function minimumVersion() {
58 protected function connect() {
60 // This doesn't actually test the connection.
62 // Now actually do a check.
63 Database::getConnection();
64 $this->pass('Drupal can CONNECT to the database ok.');
66 catch (\Exception $e) {
67 // Attempt to create the database if it is not found.
68 if ($e instanceof DatabaseNotFoundException) {
69 // Remove the database string from connection info.
70 $connection_info = Database::getConnectionInfo();
71 $database = $connection_info['default']['database'];
72 unset($connection_info['default']['database']);
74 // In order to change the Database::$databaseInfo array, need to remove
75 // the active connection, then re-add it with the new info.
76 Database::removeConnection('default');
77 Database::addConnectionInfo('default', 'default', $connection_info['default']);
80 // Now, attempt the connection again; if it's successful, attempt to
81 // create the database.
82 Database::getConnection()->createDatabase($database);
83 Database::closeConnection();
85 // Now, restore the database config.
86 Database::removeConnection('default');
87 $connection_info['default']['database'] = $database;
88 Database::addConnectionInfo('default', 'default', $connection_info['default']);
90 // Check the database connection.
91 Database::getConnection();
92 $this->pass('Drupal can CONNECT to the database ok.');
94 catch (DatabaseNotFoundException $e) {
95 // Still no dice; probably a permission issue. Raise the error to the
97 $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', ['%database' => $database, '%error' => $e->getMessage()]));
101 // Database connection failed for some other reason than the database
103 $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist, and have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', ['%error' => $e->getMessage()]));
111 * Check encoding is UTF8.
113 protected function checkEncoding() {
115 if (db_query('SHOW server_encoding')->fetchField() == 'UTF8') {
116 $this->pass(t('Database is encoded in UTF-8'));
119 $this->fail(t('The %driver database must use %encoding encoding to work with Drupal. Recreate the database with %encoding encoding. See <a href="INSTALL.pgsql.txt">INSTALL.pgsql.txt</a> for more details.', [
120 '%encoding' => 'UTF8',
121 '%driver' => $this->name(),
125 catch (\Exception $e) {
126 $this->fail(t('Drupal could not determine the encoding of the database was set to UTF-8'));
131 * Check Binary Output.
133 * Unserializing does not work on Postgresql 9 when bytea_output is 'hex'.
135 public function checkBinaryOutput() {
136 // PostgreSQL < 9 doesn't support bytea_output, so verify we are running
137 // at least PostgreSQL 9.
138 $database_connection = Database::getConnection();
139 if (version_compare($database_connection->version(), '9') >= 0) {
140 if (!$this->checkBinaryOutputSuccess()) {
141 // First try to alter the database. If it fails, raise an error telling
142 // the user to do it themselves.
143 $connection_options = $database_connection->getConnectionOptions();
144 // It is safe to include the database name directly here, because this
145 // code is only called when a connection to the database is already
146 // established, thus the database name is guaranteed to be a correct
148 $query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET bytea_output = 'escape';";
152 catch (\Exception $e) {
153 // Ignore possible errors when the user doesn't have the necessary
154 // privileges to ALTER the database.
157 // Close the database connection so that the configuration parameter
158 // is applied to the current connection.
161 // Recheck, if it fails, finally just rely on the end user to do the
163 if (!$this->checkBinaryOutputSuccess()) {
165 '%setting' => 'bytea_output',
166 '%current_value' => 'hex',
167 '%needed_value' => 'escape',
170 $this->fail(t("The %setting setting is currently set to '%current_value', but needs to be '%needed_value'. Change this by running the following query: <code>@query</code>", $replacements));
177 * Verify that a binary data roundtrip returns the original string.
179 protected function checkBinaryOutputSuccess() {
180 $bytea_output = db_query("SHOW bytea_output")->fetchField();
181 return ($bytea_output == 'escape');
185 * Ensures standard_conforming_strings setting is 'on'.
187 * When standard_conforming_strings setting is 'on' string literals ('...')
188 * treat backslashes literally, as specified in the SQL standard. This allows
189 * Drupal to convert between bytea, text and varchar columns.
191 public function checkStandardConformingStrings() {
192 $database_connection = Database::getConnection();
193 if (!$this->checkStandardConformingStringsSuccess()) {
194 // First try to alter the database. If it fails, raise an error telling
195 // the user to do it themselves.
196 $connection_options = $database_connection->getConnectionOptions();
197 // It is safe to include the database name directly here, because this
198 // code is only called when a connection to the database is already
199 // established, thus the database name is guaranteed to be a correct
201 $query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET standard_conforming_strings = 'on';";
203 $database_connection->query($query);
205 catch (\Exception $e) {
206 // Ignore possible errors when the user doesn't have the necessary
207 // privileges to ALTER the database.
210 // Close the database connection so that the configuration parameter
211 // is applied to the current connection.
212 Database::closeConnection();
214 // Recheck, if it fails, finally just rely on the end user to do the
216 if (!$this->checkStandardConformingStringsSuccess()) {
218 '%setting' => 'standard_conforming_strings',
219 '%current_value' => 'off',
220 '%needed_value' => 'on',
223 $this->fail(t("The %setting setting is currently set to '%current_value', but needs to be '%needed_value'. Change this by running the following query: <code>@query</code>", $replacements));
229 * Verifies the standard_conforming_strings setting.
231 protected function checkStandardConformingStringsSuccess() {
232 $standard_conforming_strings = Database::getConnection()->query("SHOW standard_conforming_strings")->fetchField();
233 return ($standard_conforming_strings == 'on');
237 * Make PostgreSQL Drupal friendly.
239 public function initializeDatabase() {
240 // We create some functions using global names instead of prefixing them
241 // like we do with table names. This is so that we don't double up if more
242 // than one instance of Drupal is running on a single database. We therefore
243 // avoid trying to create them again in that case.
244 // At the same time checking for the existence of the function fixes
245 // concurrency issues, when both try to update at the same time.
247 $connection = Database::getConnection();
248 // When testing, two installs might try to run the CREATE FUNCTION queries
249 // at the same time. Do not let that happen.
250 $connection->query('SELECT pg_advisory_lock(1)');
251 // Don't use {} around pg_proc table.
252 if (!$connection->query("SELECT COUNT(*) FROM pg_proc WHERE proname = 'rand'")->fetchField()) {
253 $connection->query('CREATE OR REPLACE FUNCTION "rand"() RETURNS float AS
257 [ 'allow_delimiter_in_query' => TRUE ]
261 if (!$connection->query("SELECT COUNT(*) FROM pg_proc WHERE proname = 'substring_index'")->fetchField()) {
262 $connection->query('CREATE OR REPLACE FUNCTION "substring_index"(text, text, integer) RETURNS text AS
263 \'SELECT array_to_string((string_to_array($1, $2)) [1:$3], $2);\'
266 [ 'allow_delimiter_in_query' => TRUE ]
269 $connection->query('SELECT pg_advisory_unlock(1)');
271 $this->pass(t('PostgreSQL has initialized itself.'));
273 catch (\Exception $e) {
274 $this->fail(t('Drupal could not be correctly setup with the existing database due to the following error: @error.', ['@error' => $e->getMessage()]));
281 public function getFormOptions(array $database) {
282 $form = parent::getFormOptions($database);
283 if (empty($form['advanced_options']['port']['#default_value'])) {
284 $form['advanced_options']['port']['#default_value'] = '5432';