Tasks.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. <?php
  2. namespace Drupal\Core\Database\Driver\pgsql\Install;
  3. use Drupal\Core\Database\Database;
  4. use Drupal\Core\Database\Install\Tasks as InstallTasks;
  5. use Drupal\Core\Database\DatabaseNotFoundException;
  6. /**
  7. * Specifies installation tasks for PostgreSQL databases.
  8. */
  9. class Tasks extends InstallTasks {
  10. /**
  11. * {@inheritdoc}
  12. */
  13. protected $pdoDriver = 'pgsql';
  14. /**
  15. * Constructs a \Drupal\Core\Database\Driver\pgsql\Install\Tasks object.
  16. */
  17. public function __construct() {
  18. $this->tasks[] = [
  19. 'function' => 'checkEncoding',
  20. 'arguments' => [],
  21. ];
  22. $this->tasks[] = [
  23. 'function' => 'checkBinaryOutput',
  24. 'arguments' => [],
  25. ];
  26. $this->tasks[] = [
  27. 'function' => 'checkStandardConformingStrings',
  28. 'arguments' => [],
  29. ];
  30. $this->tasks[] = [
  31. 'function' => 'initializeDatabase',
  32. 'arguments' => [],
  33. ];
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function name() {
  39. return t('PostgreSQL');
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function minimumVersion() {
  45. return '9.1.2';
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. protected function connect() {
  51. try {
  52. // This doesn't actually test the connection.
  53. Database::setActiveConnection();
  54. // Now actually do a check.
  55. Database::getConnection();
  56. $this->pass('Drupal can CONNECT to the database ok.');
  57. }
  58. catch (\Exception $e) {
  59. // Attempt to create the database if it is not found.
  60. if ($e instanceof DatabaseNotFoundException) {
  61. // Remove the database string from connection info.
  62. $connection_info = Database::getConnectionInfo();
  63. $database = $connection_info['default']['database'];
  64. unset($connection_info['default']['database']);
  65. // In order to change the Database::$databaseInfo array, need to remove
  66. // the active connection, then re-add it with the new info.
  67. Database::removeConnection('default');
  68. Database::addConnectionInfo('default', 'default', $connection_info['default']);
  69. try {
  70. // Now, attempt the connection again; if it's successful, attempt to
  71. // create the database.
  72. Database::getConnection()->createDatabase($database);
  73. Database::closeConnection();
  74. // Now, restore the database config.
  75. Database::removeConnection('default');
  76. $connection_info['default']['database'] = $database;
  77. Database::addConnectionInfo('default', 'default', $connection_info['default']);
  78. // Check the database connection.
  79. Database::getConnection();
  80. $this->pass('Drupal can CONNECT to the database ok.');
  81. }
  82. catch (DatabaseNotFoundException $e) {
  83. // Still no dice; probably a permission issue. Raise the error to the
  84. // installer.
  85. $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()]));
  86. }
  87. }
  88. else {
  89. // Database connection failed for some other reason than the database
  90. // not existing.
  91. $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 and port number?</li></ul>', ['%error' => $e->getMessage()]));
  92. return FALSE;
  93. }
  94. }
  95. return TRUE;
  96. }
  97. /**
  98. * Check encoding is UTF8.
  99. */
  100. protected function checkEncoding() {
  101. try {
  102. if (Database::getConnection()->query('SHOW server_encoding')->fetchField() == 'UTF8') {
  103. $this->pass(t('Database is encoded in UTF-8'));
  104. }
  105. else {
  106. $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.', [
  107. '%encoding' => 'UTF8',
  108. '%driver' => $this->name(),
  109. ]));
  110. }
  111. }
  112. catch (\Exception $e) {
  113. $this->fail(t('Drupal could not determine the encoding of the database was set to UTF-8'));
  114. }
  115. }
  116. /**
  117. * Check Binary Output.
  118. *
  119. * Unserializing does not work on Postgresql 9 when bytea_output is 'hex'.
  120. */
  121. public function checkBinaryOutput() {
  122. // PostgreSQL < 9 doesn't support bytea_output, so verify we are running
  123. // at least PostgreSQL 9.
  124. $database_connection = Database::getConnection();
  125. if (version_compare($database_connection->version(), '9') >= 0) {
  126. if (!$this->checkBinaryOutputSuccess()) {
  127. // First try to alter the database. If it fails, raise an error telling
  128. // the user to do it themselves.
  129. $connection_options = $database_connection->getConnectionOptions();
  130. // It is safe to include the database name directly here, because this
  131. // code is only called when a connection to the database is already
  132. // established, thus the database name is guaranteed to be a correct
  133. // value.
  134. $query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET bytea_output = 'escape';";
  135. try {
  136. $database_connection->query($query);
  137. }
  138. catch (\Exception $e) {
  139. // Ignore possible errors when the user doesn't have the necessary
  140. // privileges to ALTER the database.
  141. }
  142. // Close the database connection so that the configuration parameter
  143. // is applied to the current connection.
  144. Database::closeConnection();
  145. // Recheck, if it fails, finally just rely on the end user to do the
  146. // right thing.
  147. if (!$this->checkBinaryOutputSuccess()) {
  148. $replacements = [
  149. '%setting' => 'bytea_output',
  150. '%current_value' => 'hex',
  151. '%needed_value' => 'escape',
  152. '@query' => $query,
  153. ];
  154. $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));
  155. }
  156. }
  157. }
  158. }
  159. /**
  160. * Verify that a binary data roundtrip returns the original string.
  161. */
  162. protected function checkBinaryOutputSuccess() {
  163. $bytea_output = Database::getConnection()->query("SHOW bytea_output")->fetchField();
  164. return ($bytea_output == 'escape');
  165. }
  166. /**
  167. * Ensures standard_conforming_strings setting is 'on'.
  168. *
  169. * When standard_conforming_strings setting is 'on' string literals ('...')
  170. * treat backslashes literally, as specified in the SQL standard. This allows
  171. * Drupal to convert between bytea, text and varchar columns.
  172. */
  173. public function checkStandardConformingStrings() {
  174. $database_connection = Database::getConnection();
  175. if (!$this->checkStandardConformingStringsSuccess()) {
  176. // First try to alter the database. If it fails, raise an error telling
  177. // the user to do it themselves.
  178. $connection_options = $database_connection->getConnectionOptions();
  179. // It is safe to include the database name directly here, because this
  180. // code is only called when a connection to the database is already
  181. // established, thus the database name is guaranteed to be a correct
  182. // value.
  183. $query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET standard_conforming_strings = 'on';";
  184. try {
  185. $database_connection->query($query);
  186. }
  187. catch (\Exception $e) {
  188. // Ignore possible errors when the user doesn't have the necessary
  189. // privileges to ALTER the database.
  190. }
  191. // Close the database connection so that the configuration parameter
  192. // is applied to the current connection.
  193. Database::closeConnection();
  194. // Recheck, if it fails, finally just rely on the end user to do the
  195. // right thing.
  196. if (!$this->checkStandardConformingStringsSuccess()) {
  197. $replacements = [
  198. '%setting' => 'standard_conforming_strings',
  199. '%current_value' => 'off',
  200. '%needed_value' => 'on',
  201. '@query' => $query,
  202. ];
  203. $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));
  204. }
  205. }
  206. }
  207. /**
  208. * Verifies the standard_conforming_strings setting.
  209. */
  210. protected function checkStandardConformingStringsSuccess() {
  211. $standard_conforming_strings = Database::getConnection()->query("SHOW standard_conforming_strings")->fetchField();
  212. return ($standard_conforming_strings == 'on');
  213. }
  214. /**
  215. * Make PostgreSQL Drupal friendly.
  216. */
  217. public function initializeDatabase() {
  218. // We create some functions using global names instead of prefixing them
  219. // like we do with table names. This is so that we don't double up if more
  220. // than one instance of Drupal is running on a single database. We therefore
  221. // avoid trying to create them again in that case.
  222. // At the same time checking for the existence of the function fixes
  223. // concurrency issues, when both try to update at the same time.
  224. try {
  225. $connection = Database::getConnection();
  226. // When testing, two installs might try to run the CREATE FUNCTION queries
  227. // at the same time. Do not let that happen.
  228. $connection->query('SELECT pg_advisory_lock(1)');
  229. // Don't use {} around pg_proc table.
  230. if (!$connection->query("SELECT COUNT(*) FROM pg_proc WHERE proname = 'rand'")->fetchField()) {
  231. $connection->query('CREATE OR REPLACE FUNCTION "rand"() RETURNS float AS
  232. \'SELECT random();\'
  233. LANGUAGE \'sql\'',
  234. [],
  235. ['allow_delimiter_in_query' => TRUE]
  236. );
  237. }
  238. if (!$connection->query("SELECT COUNT(*) FROM pg_proc WHERE proname = 'substring_index'")->fetchField()) {
  239. $connection->query('CREATE OR REPLACE FUNCTION "substring_index"(text, text, integer) RETURNS text AS
  240. \'SELECT array_to_string((string_to_array($1, $2)) [1:$3], $2);\'
  241. LANGUAGE \'sql\'',
  242. [],
  243. ['allow_delimiter_in_query' => TRUE]
  244. );
  245. }
  246. $connection->query('SELECT pg_advisory_unlock(1)');
  247. $this->pass(t('PostgreSQL has initialized itself.'));
  248. }
  249. catch (\Exception $e) {
  250. $this->fail(t('Drupal could not be correctly setup with the existing database due to the following error: @error.', ['@error' => $e->getMessage()]));
  251. }
  252. }
  253. /**
  254. * {@inheritdoc}
  255. */
  256. public function getFormOptions(array $database) {
  257. $form = parent::getFormOptions($database);
  258. if (empty($form['advanced_options']['port']['#default_value'])) {
  259. $form['advanced_options']['port']['#default_value'] = '5432';
  260. }
  261. return $form;
  262. }
  263. }