Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Database / Driver / pgsql / Install / Tasks.php
1 <?php
2
3 namespace Drupal\Core\Database\Driver\pgsql\Install;
4
5 use Drupal\Core\Database\Database;
6 use Drupal\Core\Database\Install\Tasks as InstallTasks;
7 use Drupal\Core\Database\DatabaseNotFoundException;
8
9 /**
10  * Specifies installation tasks for PostgreSQL databases.
11  */
12 class Tasks extends InstallTasks {
13
14   /**
15    * {@inheritdoc}
16    */
17   protected $pdoDriver = 'pgsql';
18
19   /**
20    * Constructs a \Drupal\Core\Database\Driver\pgsql\Install\Tasks object.
21    */
22   public function __construct() {
23     $this->tasks[] = [
24       'function' => 'checkEncoding',
25       'arguments' => [],
26     ];
27     $this->tasks[] = [
28       'function' => 'checkBinaryOutput',
29       'arguments' => [],
30     ];
31     $this->tasks[] = [
32       'function' => 'checkStandardConformingStrings',
33       'arguments' => [],
34     ];
35     $this->tasks[] = [
36       'function' => 'initializeDatabase',
37       'arguments' => [],
38     ];
39   }
40
41   /**
42    * {@inheritdoc}
43    */
44   public function name() {
45     return t('PostgreSQL');
46   }
47
48   /**
49    * {@inheritdoc}
50    */
51   public function minimumVersion() {
52     return '9.1.2';
53   }
54
55   /**
56    * {@inheritdoc}
57    */
58   protected function connect() {
59     try {
60       // This doesn't actually test the connection.
61       db_set_active();
62       // Now actually do a check.
63       Database::getConnection();
64       $this->pass('Drupal can CONNECT to the database ok.');
65     }
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']);
73
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']);
78
79         try {
80           // Now, attempt the connection again; if it's successful, attempt to
81           // create the database.
82           Database::getConnection()->createDatabase($database);
83           Database::closeConnection();
84
85           // Now, restore the database config.
86           Database::removeConnection('default');
87           $connection_info['default']['database'] = $database;
88           Database::addConnectionInfo('default', 'default', $connection_info['default']);
89
90           // Check the database connection.
91           Database::getConnection();
92           $this->pass('Drupal can CONNECT to the database ok.');
93         }
94         catch (DatabaseNotFoundException $e) {
95           // Still no dice; probably a permission issue. Raise the error to the
96           // installer.
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()]));
98         }
99       }
100       else {
101         // Database connection failed for some other reason than the database
102         // not existing.
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()]));
104         return FALSE;
105       }
106     }
107     return TRUE;
108   }
109
110   /**
111    * Check encoding is UTF8.
112    */
113   protected function checkEncoding() {
114     try {
115       if (db_query('SHOW server_encoding')->fetchField() == 'UTF8') {
116         $this->pass(t('Database is encoded in UTF-8'));
117       }
118       else {
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(),
122         ]));
123       }
124     }
125     catch (\Exception $e) {
126       $this->fail(t('Drupal could not determine the encoding of the database was set to UTF-8'));
127     }
128   }
129
130   /**
131    * Check Binary Output.
132    *
133    * Unserializing does not work on Postgresql 9 when bytea_output is 'hex'.
134    */
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
147         // value.
148         $query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET bytea_output = 'escape';";
149         try {
150           db_query($query);
151         }
152         catch (\Exception $e) {
153           // Ignore possible errors when the user doesn't have the necessary
154           // privileges to ALTER the database.
155         }
156
157         // Close the database connection so that the configuration parameter
158         // is applied to the current connection.
159         db_close();
160
161         // Recheck, if it fails, finally just rely on the end user to do the
162         // right thing.
163         if (!$this->checkBinaryOutputSuccess()) {
164           $replacements = [
165             '%setting' => 'bytea_output',
166             '%current_value' => 'hex',
167             '%needed_value' => 'escape',
168             '@query' => $query,
169           ];
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));
171         }
172       }
173     }
174   }
175
176   /**
177    * Verify that a binary data roundtrip returns the original string.
178    */
179   protected function checkBinaryOutputSuccess() {
180     $bytea_output = db_query("SHOW bytea_output")->fetchField();
181     return ($bytea_output == 'escape');
182   }
183
184   /**
185    * Ensures standard_conforming_strings setting is 'on'.
186    *
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.
190    */
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
200       // value.
201       $query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET standard_conforming_strings = 'on';";
202       try {
203         $database_connection->query($query);
204       }
205       catch (\Exception $e) {
206         // Ignore possible errors when the user doesn't have the necessary
207         // privileges to ALTER the database.
208       }
209
210       // Close the database connection so that the configuration parameter
211       // is applied to the current connection.
212       Database::closeConnection();
213
214       // Recheck, if it fails, finally just rely on the end user to do the
215       // right thing.
216       if (!$this->checkStandardConformingStringsSuccess()) {
217         $replacements = [
218           '%setting' => 'standard_conforming_strings',
219           '%current_value' => 'off',
220           '%needed_value' => 'on',
221           '@query' => $query,
222         ];
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));
224       }
225     }
226   }
227
228   /**
229    * Verifies the standard_conforming_strings setting.
230    */
231   protected function checkStandardConformingStringsSuccess() {
232     $standard_conforming_strings = Database::getConnection()->query("SHOW standard_conforming_strings")->fetchField();
233     return ($standard_conforming_strings == 'on');
234   }
235
236   /**
237    * Make PostgreSQL Drupal friendly.
238    */
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.
246     try {
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
254           \'SELECT random();\'
255           LANGUAGE \'sql\'',
256           [],
257           [ 'allow_delimiter_in_query' => TRUE ]
258         );
259       }
260
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);\'
264           LANGUAGE \'sql\'',
265           [],
266           [ 'allow_delimiter_in_query' => TRUE ]
267         );
268       }
269       $connection->query('SELECT pg_advisory_unlock(1)');
270
271       $this->pass(t('PostgreSQL has initialized itself.'));
272     }
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()]));
275     }
276   }
277
278   /**
279    * {@inheritdoc}
280    */
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';
285     }
286     return $form;
287   }
288
289 }