Schema.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. <?php
  2. namespace Drupal\Core\Database\Driver\pgsql;
  3. use Drupal\Core\Database\SchemaObjectExistsException;
  4. use Drupal\Core\Database\SchemaObjectDoesNotExistException;
  5. use Drupal\Core\Database\Schema as DatabaseSchema;
  6. /**
  7. * @addtogroup schemaapi
  8. * @{
  9. */
  10. /**
  11. * PostgreSQL implementation of \Drupal\Core\Database\Schema.
  12. */
  13. class Schema extends DatabaseSchema {
  14. /**
  15. * A cache of information about blob columns and sequences of tables.
  16. *
  17. * This is collected by Schema::queryTableInformation(), by introspecting the
  18. * database.
  19. *
  20. * @see \Drupal\Core\Database\Driver\pgsql\Schema::queryTableInformation()
  21. * @var array
  22. */
  23. protected $tableInformation = [];
  24. /**
  25. * The maximum allowed length for index, primary key and constraint names.
  26. *
  27. * Value will usually be set to a 63 chars limit but PostgreSQL allows
  28. * to higher this value before compiling, so we need to check for that.
  29. *
  30. * @var int
  31. */
  32. protected $maxIdentifierLength;
  33. /**
  34. * PostgreSQL's temporary namespace name.
  35. *
  36. * @var string
  37. */
  38. protected $tempNamespaceName;
  39. /**
  40. * Make sure to limit identifiers according to PostgreSQL compiled in length.
  41. *
  42. * PostgreSQL allows in standard configuration identifiers no longer than 63
  43. * chars for table/relation names, indexes, primary keys, and constraints. So
  44. * we map all identifiers that are too long to drupal_base64hash_tag, where
  45. * tag is one of:
  46. * - idx for indexes
  47. * - key for constraints
  48. * - pkey for primary keys
  49. * - seq for sequences
  50. *
  51. * @param string $table_identifier_part
  52. * The first argument used to build the identifier string. This usually
  53. * refers to a table/relation name.
  54. * @param string $column_identifier_part
  55. * The second argument used to build the identifier string. This usually
  56. * refers to one or more column names.
  57. * @param string $tag
  58. * The identifier tag. It can be one of 'idx', 'key', 'pkey' or 'seq'.
  59. * @param string $separator
  60. * (optional) The separator used to glue together the aforementioned
  61. * identifier parts. Defaults to '__'.
  62. *
  63. * @return string
  64. * The index/constraint/pkey identifier.
  65. */
  66. protected function ensureIdentifiersLength($table_identifier_part, $column_identifier_part, $tag, $separator = '__') {
  67. $info = $this->getPrefixInfo($table_identifier_part);
  68. $table_identifier_part = $info['table'];
  69. $identifierName = implode($separator, [$table_identifier_part, $column_identifier_part, $tag]);
  70. // Retrieve the max identifier length which is usually 63 characters
  71. // but can be altered before PostgreSQL is compiled so we need to check.
  72. if (empty($this->maxIdentifierLength)) {
  73. $this->maxIdentifierLength = $this->connection->query("SHOW max_identifier_length")->fetchField();
  74. }
  75. if (strlen($identifierName) > $this->maxIdentifierLength) {
  76. $saveIdentifier = '"drupal_' . $this->hashBase64($identifierName) . '_' . $tag . '"';
  77. }
  78. else {
  79. $saveIdentifier = $identifierName;
  80. }
  81. return $saveIdentifier;
  82. }
  83. /**
  84. * Fetch the list of blobs and sequences used on a table.
  85. *
  86. * We introspect the database to collect the information required by insert
  87. * and update queries.
  88. *
  89. * @param $table_name
  90. * The non-prefixed name of the table.
  91. *
  92. * @return
  93. * An object with two member variables:
  94. * - 'blob_fields' that lists all the blob fields in the table.
  95. * - 'sequences' that lists the sequences used in that table.
  96. */
  97. public function queryTableInformation($table) {
  98. // Generate a key to reference this table's information on.
  99. $key = $this->connection->prefixTables('{' . $table . '}');
  100. // Take into account that temporary tables are stored in a different schema.
  101. // \Drupal\Core\Database\Connection::generateTemporaryTableName() sets the
  102. // 'db_temporary_' prefix to all temporary tables.
  103. if (strpos($key, '.') === FALSE && strpos($table, 'db_temporary_') === FALSE) {
  104. $key = 'public.' . $key;
  105. }
  106. else {
  107. $key = $this->getTempNamespaceName() . '.' . $key;
  108. }
  109. if (!isset($this->tableInformation[$key])) {
  110. $table_information = (object) [
  111. 'blob_fields' => [],
  112. 'sequences' => [],
  113. ];
  114. $this->connection->addSavepoint();
  115. try {
  116. // The bytea columns and sequences for a table can be found in
  117. // pg_attribute, which is significantly faster than querying the
  118. // information_schema. The data type of a field can be found by lookup
  119. // of the attribute ID, and the default value must be extracted from the
  120. // node tree for the attribute definition instead of the historical
  121. // human-readable column, adsrc.
  122. $sql = <<<'EOD'
  123. SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS data_type, pg_get_expr(pg_attrdef.adbin, pg_attribute.attrelid) AS column_default
  124. FROM pg_attribute
  125. LEFT JOIN pg_attrdef ON pg_attrdef.adrelid = pg_attribute.attrelid AND pg_attrdef.adnum = pg_attribute.attnum
  126. WHERE pg_attribute.attnum > 0
  127. AND NOT pg_attribute.attisdropped
  128. AND pg_attribute.attrelid = :key::regclass
  129. AND (format_type(pg_attribute.atttypid, pg_attribute.atttypmod) = 'bytea'
  130. OR pg_get_expr(pg_attrdef.adbin, pg_attribute.attrelid) LIKE 'nextval%')
  131. EOD;
  132. $result = $this->connection->query($sql, [
  133. ':key' => $key,
  134. ]);
  135. }
  136. catch (\Exception $e) {
  137. $this->connection->rollbackSavepoint();
  138. throw $e;
  139. }
  140. $this->connection->releaseSavepoint();
  141. // If the table information does not yet exist in the PostgreSQL
  142. // metadata, then return the default table information here, so that it
  143. // will not be cached.
  144. if (empty($result)) {
  145. return $table_information;
  146. }
  147. foreach ($result as $column) {
  148. if ($column->data_type == 'bytea') {
  149. $table_information->blob_fields[$column->column_name] = TRUE;
  150. }
  151. elseif (preg_match("/nextval\('([^']+)'/", $column->column_default, $matches)) {
  152. // We must know of any sequences in the table structure to help us
  153. // return the last insert id. If there is more than 1 sequences the
  154. // first one (index 0 of the sequences array) will be used.
  155. $table_information->sequences[] = $matches[1];
  156. $table_information->serial_fields[] = $column->column_name;
  157. }
  158. }
  159. $this->tableInformation[$key] = $table_information;
  160. }
  161. return $this->tableInformation[$key];
  162. }
  163. /**
  164. * Gets PostgreSQL's temporary namespace name.
  165. *
  166. * @return string
  167. * PostgreSQL's temporary namespace name.
  168. */
  169. protected function getTempNamespaceName() {
  170. if (!isset($this->tempNamespaceName)) {
  171. $this->tempNamespaceName = $this->connection->query('SELECT nspname FROM pg_namespace WHERE oid = pg_my_temp_schema()')->fetchField();
  172. }
  173. return $this->tempNamespaceName;
  174. }
  175. /**
  176. * Resets information about table blobs, sequences and serial fields.
  177. *
  178. * @param $table
  179. * The non-prefixed name of the table.
  180. */
  181. protected function resetTableInformation($table) {
  182. $key = $this->connection->prefixTables('{' . $table . '}');
  183. if (strpos($key, '.') === FALSE) {
  184. $key = 'public.' . $key;
  185. }
  186. unset($this->tableInformation[$key]);
  187. }
  188. /**
  189. * Fetches the list of constraints used on a field.
  190. *
  191. * We introspect the database to collect the information required by field
  192. * alteration.
  193. *
  194. * @param string $table
  195. * The non-prefixed name of the table.
  196. * @param string $field
  197. * The name of the field.
  198. * @param string $constraint_type
  199. * (optional) The type of the constraint. This can be one of the following:
  200. * - c: check constraint;
  201. * - f: foreign key constraint;
  202. * - p: primary key constraint;
  203. * - u: unique constraint;
  204. * - t: constraint trigger;
  205. * - x: exclusion constraint.
  206. * Defaults to 'c' for a CHECK constraint.
  207. * @see https://www.postgresql.org/docs/current/catalog-pg-constraint.html
  208. *
  209. * @return array
  210. * An array containing all the constraint names for the field.
  211. */
  212. public function queryFieldInformation($table, $field, $constraint_type = 'c') {
  213. assert(in_array($constraint_type, ['c', 'f', 'p', 'u', 't', 'x']));
  214. $prefixInfo = $this->getPrefixInfo($table, TRUE);
  215. // Split the key into schema and table for querying.
  216. $schema = $prefixInfo['schema'];
  217. $table_name = $prefixInfo['table'];
  218. $this->connection->addSavepoint();
  219. try {
  220. $checks = $this->connection->query("SELECT conname FROM pg_class cl INNER JOIN pg_constraint co ON co.conrelid = cl.oid INNER JOIN pg_attribute attr ON attr.attrelid = cl.oid AND attr.attnum = ANY (co.conkey) INNER JOIN pg_namespace ns ON cl.relnamespace = ns.oid WHERE co.contype = :constraint_type AND ns.nspname = :schema AND cl.relname = :table AND attr.attname = :column", [
  221. ':constraint_type' => $constraint_type,
  222. ':schema' => $schema,
  223. ':table' => $table_name,
  224. ':column' => $field,
  225. ]);
  226. }
  227. catch (\Exception $e) {
  228. $this->connection->rollbackSavepoint();
  229. throw $e;
  230. }
  231. $this->connection->releaseSavepoint();
  232. $field_information = $checks->fetchCol();
  233. return $field_information;
  234. }
  235. /**
  236. * Generate SQL to create a new table from a Drupal schema definition.
  237. *
  238. * @param $name
  239. * The name of the table to create.
  240. * @param $table
  241. * A Schema API table definition array.
  242. *
  243. * @return
  244. * An array of SQL statements to create the table.
  245. */
  246. protected function createTableSql($name, $table) {
  247. $sql_fields = [];
  248. foreach ($table['fields'] as $field_name => $field) {
  249. $sql_fields[] = $this->createFieldSql($field_name, $this->processField($field));
  250. }
  251. $sql_keys = [];
  252. if (!empty($table['primary key']) && is_array($table['primary key'])) {
  253. $this->ensureNotNullPrimaryKey($table['primary key'], $table['fields']);
  254. $sql_keys[] = 'CONSTRAINT ' . $this->ensureIdentifiersLength($name, '', 'pkey') . ' PRIMARY KEY (' . $this->createPrimaryKeySql($table['primary key']) . ')';
  255. }
  256. if (isset($table['unique keys']) && is_array($table['unique keys'])) {
  257. foreach ($table['unique keys'] as $key_name => $key) {
  258. $sql_keys[] = 'CONSTRAINT ' . $this->ensureIdentifiersLength($name, $key_name, 'key') . ' UNIQUE (' . implode(', ', $key) . ')';
  259. }
  260. }
  261. $sql = "CREATE TABLE {" . $name . "} (\n\t";
  262. $sql .= implode(",\n\t", $sql_fields);
  263. if (count($sql_keys) > 0) {
  264. $sql .= ",\n\t";
  265. }
  266. $sql .= implode(",\n\t", $sql_keys);
  267. $sql .= "\n)";
  268. $statements[] = $sql;
  269. if (isset($table['indexes']) && is_array($table['indexes'])) {
  270. foreach ($table['indexes'] as $key_name => $key) {
  271. $statements[] = $this->_createIndexSql($name, $key_name, $key);
  272. }
  273. }
  274. // Add table comment.
  275. if (!empty($table['description'])) {
  276. $statements[] = 'COMMENT ON TABLE {' . $name . '} IS ' . $this->prepareComment($table['description']);
  277. }
  278. // Add column comments.
  279. foreach ($table['fields'] as $field_name => $field) {
  280. if (!empty($field['description'])) {
  281. $statements[] = 'COMMENT ON COLUMN {' . $name . '}.' . $field_name . ' IS ' . $this->prepareComment($field['description']);
  282. }
  283. }
  284. return $statements;
  285. }
  286. /**
  287. * Create an SQL string for a field to be used in table creation or
  288. * alteration.
  289. *
  290. * Before passing a field out of a schema definition into this
  291. * function it has to be processed by _db_process_field().
  292. *
  293. * @param $name
  294. * Name of the field.
  295. * @param $spec
  296. * The field specification, as per the schema data structure format.
  297. */
  298. protected function createFieldSql($name, $spec) {
  299. // The PostgreSQL server converts names into lowercase, unless quoted.
  300. $sql = '"' . $name . '" ' . $spec['pgsql_type'];
  301. if (isset($spec['type']) && $spec['type'] == 'serial') {
  302. unset($spec['not null']);
  303. }
  304. if (in_array($spec['pgsql_type'], ['varchar', 'character']) && isset($spec['length'])) {
  305. $sql .= '(' . $spec['length'] . ')';
  306. }
  307. elseif (isset($spec['precision']) && isset($spec['scale'])) {
  308. $sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
  309. }
  310. if (!empty($spec['unsigned'])) {
  311. $sql .= " CHECK ($name >= 0)";
  312. }
  313. if (isset($spec['not null'])) {
  314. if ($spec['not null']) {
  315. $sql .= ' NOT NULL';
  316. }
  317. else {
  318. $sql .= ' NULL';
  319. }
  320. }
  321. if (array_key_exists('default', $spec)) {
  322. $default = $this->escapeDefaultValue($spec['default']);
  323. $sql .= " default $default";
  324. }
  325. return $sql;
  326. }
  327. /**
  328. * Set database-engine specific properties for a field.
  329. *
  330. * @param $field
  331. * A field description array, as specified in the schema documentation.
  332. */
  333. protected function processField($field) {
  334. if (!isset($field['size'])) {
  335. $field['size'] = 'normal';
  336. }
  337. // Set the correct database-engine specific datatype.
  338. // In case one is already provided, force it to lowercase.
  339. if (isset($field['pgsql_type'])) {
  340. $field['pgsql_type'] = mb_strtolower($field['pgsql_type']);
  341. }
  342. else {
  343. $map = $this->getFieldTypeMap();
  344. $field['pgsql_type'] = $map[$field['type'] . ':' . $field['size']];
  345. }
  346. if (!empty($field['unsigned'])) {
  347. // Unsigned data types are not supported in PostgreSQL 9.1. In MySQL,
  348. // they are used to ensure a positive number is inserted and it also
  349. // doubles the maximum integer size that can be stored in a field.
  350. // The PostgreSQL schema in Drupal creates a check constraint
  351. // to ensure that a value inserted is >= 0. To provide the extra
  352. // integer capacity, here, we bump up the column field size.
  353. if (!isset($map)) {
  354. $map = $this->getFieldTypeMap();
  355. }
  356. switch ($field['pgsql_type']) {
  357. case 'smallint':
  358. $field['pgsql_type'] = $map['int:medium'];
  359. break;
  360. case 'int':
  361. $field['pgsql_type'] = $map['int:big'];
  362. break;
  363. }
  364. }
  365. if (isset($field['type']) && $field['type'] == 'serial') {
  366. unset($field['not null']);
  367. }
  368. return $field;
  369. }
  370. /**
  371. * {@inheritdoc}
  372. */
  373. public function getFieldTypeMap() {
  374. // Put :normal last so it gets preserved by array_flip. This makes
  375. // it much easier for modules (such as schema.module) to map
  376. // database types back into schema types.
  377. // $map does not use drupal_static as its value never changes.
  378. static $map = [
  379. 'varchar_ascii:normal' => 'varchar',
  380. 'varchar:normal' => 'varchar',
  381. 'char:normal' => 'character',
  382. 'text:tiny' => 'text',
  383. 'text:small' => 'text',
  384. 'text:medium' => 'text',
  385. 'text:big' => 'text',
  386. 'text:normal' => 'text',
  387. 'int:tiny' => 'smallint',
  388. 'int:small' => 'smallint',
  389. 'int:medium' => 'int',
  390. 'int:big' => 'bigint',
  391. 'int:normal' => 'int',
  392. 'float:tiny' => 'real',
  393. 'float:small' => 'real',
  394. 'float:medium' => 'real',
  395. 'float:big' => 'double precision',
  396. 'float:normal' => 'real',
  397. 'numeric:normal' => 'numeric',
  398. 'blob:big' => 'bytea',
  399. 'blob:normal' => 'bytea',
  400. 'serial:tiny' => 'serial',
  401. 'serial:small' => 'serial',
  402. 'serial:medium' => 'serial',
  403. 'serial:big' => 'bigserial',
  404. 'serial:normal' => 'serial',
  405. ];
  406. return $map;
  407. }
  408. protected function _createKeySql($fields) {
  409. $return = [];
  410. foreach ($fields as $field) {
  411. if (is_array($field)) {
  412. $return[] = 'substr(' . $field[0] . ', 1, ' . $field[1] . ')';
  413. }
  414. else {
  415. $return[] = '"' . $field . '"';
  416. }
  417. }
  418. return implode(', ', $return);
  419. }
  420. /**
  421. * Create the SQL expression for primary keys.
  422. *
  423. * Postgresql does not support key length. It does support fillfactor, but
  424. * that requires a separate database lookup for each column in the key. The
  425. * key length defined in the schema is ignored.
  426. */
  427. protected function createPrimaryKeySql($fields) {
  428. $return = [];
  429. foreach ($fields as $field) {
  430. if (is_array($field)) {
  431. $return[] = '"' . $field[0] . '"';
  432. }
  433. else {
  434. $return[] = '"' . $field . '"';
  435. }
  436. }
  437. return implode(', ', $return);
  438. }
  439. /**
  440. * {@inheritdoc}
  441. */
  442. public function tableExists($table) {
  443. $prefixInfo = $this->getPrefixInfo($table, TRUE);
  444. return (bool) $this->connection->query("SELECT 1 FROM pg_tables WHERE schemaname = :schema AND tablename = :table", [':schema' => $prefixInfo['schema'], ':table' => $prefixInfo['table']])->fetchField();
  445. }
  446. /**
  447. * {@inheritdoc}
  448. */
  449. public function findTables($table_expression) {
  450. $individually_prefixed_tables = $this->connection->getUnprefixedTablesMap();
  451. $default_prefix = $this->connection->tablePrefix();
  452. $default_prefix_length = strlen($default_prefix);
  453. $tables = [];
  454. // Load all the tables up front in order to take into account per-table
  455. // prefixes. The actual matching is done at the bottom of the method.
  456. $results = $this->connection->query("SELECT tablename FROM pg_tables WHERE schemaname = :schema", [':schema' => $this->defaultSchema]);
  457. foreach ($results as $table) {
  458. // Take into account tables that have an individual prefix.
  459. if (isset($individually_prefixed_tables[$table->tablename])) {
  460. $prefix_length = strlen($this->connection->tablePrefix($individually_prefixed_tables[$table->tablename]));
  461. }
  462. elseif ($default_prefix && substr($table->tablename, 0, $default_prefix_length) !== $default_prefix) {
  463. // This table name does not start the default prefix, which means that
  464. // it is not managed by Drupal so it should be excluded from the result.
  465. continue;
  466. }
  467. else {
  468. $prefix_length = $default_prefix_length;
  469. }
  470. // Remove the prefix from the returned tables.
  471. $unprefixed_table_name = substr($table->tablename, $prefix_length);
  472. // The pattern can match a table which is the same as the prefix. That
  473. // will become an empty string when we remove the prefix, which will
  474. // probably surprise the caller, besides not being a prefixed table. So
  475. // remove it.
  476. if (!empty($unprefixed_table_name)) {
  477. $tables[$unprefixed_table_name] = $unprefixed_table_name;
  478. }
  479. }
  480. // Convert the table expression from its SQL LIKE syntax to a regular
  481. // expression and escape the delimiter that will be used for matching.
  482. $table_expression = str_replace(['%', '_'], ['.*?', '.'], preg_quote($table_expression, '/'));
  483. $tables = preg_grep('/^' . $table_expression . '$/i', $tables);
  484. return $tables;
  485. }
  486. /**
  487. * {@inheritdoc}
  488. */
  489. public function renameTable($table, $new_name) {
  490. if (!$this->tableExists($table)) {
  491. throw new SchemaObjectDoesNotExistException("Cannot rename '$table' to '$new_name': table '$table' doesn't exist.");
  492. }
  493. if ($this->tableExists($new_name)) {
  494. throw new SchemaObjectExistsException("Cannot rename '$table' to '$new_name': table '$new_name' already exists.");
  495. }
  496. // Get the schema and tablename for the old table.
  497. $old_full_name = $this->connection->prefixTables('{' . $table . '}');
  498. list($old_schema, $old_table_name) = strpos($old_full_name, '.') ? explode('.', $old_full_name) : ['public', $old_full_name];
  499. // Index names and constraint names are global in PostgreSQL, so we need to
  500. // rename them when renaming the table.
  501. $indexes = $this->connection->query('SELECT indexname FROM pg_indexes WHERE schemaname = :schema AND tablename = :table', [':schema' => $old_schema, ':table' => $old_table_name]);
  502. foreach ($indexes as $index) {
  503. // Get the index type by suffix, e.g. idx/key/pkey
  504. $index_type = substr($index->indexname, strrpos($index->indexname, '_') + 1);
  505. // If the index is already rewritten by ensureIdentifiersLength() to not
  506. // exceed the 63 chars limit of PostgreSQL, we need to take care of that.
  507. // Example (drupal_Gk7Su_T1jcBHVuvSPeP22_I3Ni4GrVEgTYlIYnBJkro_idx).
  508. if (strpos($index->indexname, 'drupal_') !== FALSE) {
  509. preg_match('/^drupal_(.*)_' . preg_quote($index_type) . '/', $index->indexname, $matches);
  510. $index_name = $matches[1];
  511. }
  512. else {
  513. // Make sure to remove the suffix from index names, because
  514. // $this->ensureIdentifiersLength() will add the suffix again and thus
  515. // would result in a wrong index name.
  516. preg_match('/^' . preg_quote($old_full_name) . '__(.*)__' . preg_quote($index_type) . '/', $index->indexname, $matches);
  517. $index_name = $matches[1];
  518. }
  519. $this->connection->query('ALTER INDEX "' . $index->indexname . '" RENAME TO ' . $this->ensureIdentifiersLength($new_name, $index_name, $index_type) . '');
  520. }
  521. // Ensure the new table name does not include schema syntax.
  522. $prefixInfo = $this->getPrefixInfo($new_name);
  523. // Rename sequences if the table contains serial fields.
  524. $info = $this->queryTableInformation($table);
  525. if (!empty($info->serial_fields)) {
  526. foreach ($info->serial_fields as $field) {
  527. // The initial name of the sequence is generated automatically by
  528. // PostgreSQL when the table is created, so we need to use
  529. // pg_get_serial_sequence() to retrieve it.
  530. $old_sequence = $this->connection->query("SELECT pg_get_serial_sequence('" . $old_full_name . "', '" . $field . "')")->fetchField();
  531. // If the new sequence name exceeds the maximum identifier length limit,
  532. // it will not match the pattern that is automatically applied by
  533. // PostgreSQL on table creation, but that's ok because
  534. // pg_get_serial_sequence() will return our non-standard name on
  535. // subsequent table renames.
  536. $new_sequence = $this->ensureIdentifiersLength($new_name, $field, 'seq', '_');
  537. $this->connection->query('ALTER SEQUENCE ' . $old_sequence . ' RENAME TO ' . $new_sequence);
  538. }
  539. }
  540. // Now rename the table.
  541. $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO ' . $prefixInfo['table']);
  542. $this->resetTableInformation($table);
  543. }
  544. /**
  545. * {@inheritdoc}
  546. */
  547. public function dropTable($table) {
  548. if (!$this->tableExists($table)) {
  549. return FALSE;
  550. }
  551. $this->connection->query('DROP TABLE {' . $table . '}');
  552. $this->resetTableInformation($table);
  553. return TRUE;
  554. }
  555. /**
  556. * {@inheritdoc}
  557. */
  558. public function addField($table, $field, $spec, $new_keys = []) {
  559. if (!$this->tableExists($table)) {
  560. throw new SchemaObjectDoesNotExistException("Cannot add field '$table.$field': table doesn't exist.");
  561. }
  562. if ($this->fieldExists($table, $field)) {
  563. throw new SchemaObjectExistsException("Cannot add field '$table.$field': field already exists.");
  564. }
  565. // Fields that are part of a PRIMARY KEY must be added as NOT NULL.
  566. $is_primary_key = isset($new_keys['primary key']) && in_array($field, $new_keys['primary key'], TRUE);
  567. if ($is_primary_key) {
  568. $this->ensureNotNullPrimaryKey($new_keys['primary key'], [$field => $spec]);
  569. }
  570. $fixnull = FALSE;
  571. if (!empty($spec['not null']) && !isset($spec['default']) && !$is_primary_key) {
  572. $fixnull = TRUE;
  573. $spec['not null'] = FALSE;
  574. }
  575. $query = 'ALTER TABLE {' . $table . '} ADD COLUMN ';
  576. $query .= $this->createFieldSql($field, $this->processField($spec));
  577. $this->connection->query($query);
  578. if (isset($spec['initial_from_field'])) {
  579. if (isset($spec['initial'])) {
  580. $expression = 'COALESCE(' . $spec['initial_from_field'] . ', :default_initial_value)';
  581. $arguments = [':default_initial_value' => $spec['initial']];
  582. }
  583. else {
  584. $expression = $spec['initial_from_field'];
  585. $arguments = [];
  586. }
  587. $this->connection->update($table)
  588. ->expression($field, $expression, $arguments)
  589. ->execute();
  590. }
  591. elseif (isset($spec['initial'])) {
  592. $this->connection->update($table)
  593. ->fields([$field => $spec['initial']])
  594. ->execute();
  595. }
  596. if ($fixnull) {
  597. $this->connection->query("ALTER TABLE {" . $table . "} ALTER $field SET NOT NULL");
  598. }
  599. if (isset($new_keys)) {
  600. // Make sure to drop the existing primary key before adding a new one.
  601. // This is only needed when adding a field because this method, unlike
  602. // changeField(), is supposed to handle primary keys automatically.
  603. if (isset($new_keys['primary key']) && $this->constraintExists($table, 'pkey')) {
  604. $this->dropPrimaryKey($table);
  605. }
  606. $this->_createKeys($table, $new_keys);
  607. }
  608. // Add column comment.
  609. if (!empty($spec['description'])) {
  610. $this->connection->query('COMMENT ON COLUMN {' . $table . '}.' . $field . ' IS ' . $this->prepareComment($spec['description']));
  611. }
  612. $this->resetTableInformation($table);
  613. }
  614. /**
  615. * {@inheritdoc}
  616. */
  617. public function dropField($table, $field) {
  618. if (!$this->fieldExists($table, $field)) {
  619. return FALSE;
  620. }
  621. $this->connection->query('ALTER TABLE {' . $table . '} DROP COLUMN "' . $field . '"');
  622. $this->resetTableInformation($table);
  623. return TRUE;
  624. }
  625. /**
  626. * {@inheritdoc}
  627. */
  628. public function fieldSetDefault($table, $field, $default) {
  629. @trigger_error('fieldSetDefault() is deprecated in drupal:8.7.0 and will be removed before drupal:9.0.0. Instead, call ::changeField() passing a full field specification. See https://www.drupal.org/node/2999035', E_USER_DEPRECATED);
  630. if (!$this->fieldExists($table, $field)) {
  631. throw new SchemaObjectDoesNotExistException("Cannot set default value of field '$table.$field': field doesn't exist.");
  632. }
  633. $default = $this->escapeDefaultValue($default);
  634. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" SET DEFAULT ' . $default);
  635. }
  636. /**
  637. * {@inheritdoc}
  638. */
  639. public function fieldSetNoDefault($table, $field) {
  640. @trigger_error('fieldSetNoDefault() is deprecated in drupal:8.7.0 and will be removed before drupal:9.0.0. Instead, call ::changeField() passing a full field specification. See https://www.drupal.org/node/2999035', E_USER_DEPRECATED);
  641. if (!$this->fieldExists($table, $field)) {
  642. throw new SchemaObjectDoesNotExistException("Cannot remove default value of field '$table.$field': field doesn't exist.");
  643. }
  644. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT');
  645. }
  646. /**
  647. * {@inheritdoc}
  648. */
  649. public function fieldExists($table, $column) {
  650. $prefixInfo = $this->getPrefixInfo($table);
  651. return (bool) $this->connection->query("SELECT 1 FROM pg_attribute WHERE attrelid = :key::regclass AND attname = :column AND NOT attisdropped AND attnum > 0", [':key' => $prefixInfo['schema'] . '.' . $prefixInfo['table'], ':column' => $column])->fetchField();
  652. }
  653. /**
  654. * {@inheritdoc}
  655. */
  656. public function indexExists($table, $name) {
  657. // Details http://www.postgresql.org/docs/9.1/interactive/view-pg-indexes.html
  658. $index_name = $this->ensureIdentifiersLength($table, $name, 'idx');
  659. // Remove leading and trailing quotes because the index name is in a WHERE
  660. // clause and not used as an identifier.
  661. $index_name = str_replace('"', '', $index_name);
  662. return (bool) $this->connection->query("SELECT 1 FROM pg_indexes WHERE indexname = '$index_name'")->fetchField();
  663. }
  664. /**
  665. * Helper function: check if a constraint (PK, FK, UK) exists.
  666. *
  667. * @param string $table
  668. * The name of the table.
  669. * @param string $name
  670. * The name of the constraint (typically 'pkey' or '[constraint]__key').
  671. *
  672. * @return bool
  673. * TRUE if the constraint exists, FALSE otherwise.
  674. */
  675. public function constraintExists($table, $name) {
  676. // ::ensureIdentifiersLength() expects three parameters, although not
  677. // explicitly stated in its signature, thus we split our constraint name in
  678. // a proper name and a suffix.
  679. if ($name == 'pkey') {
  680. $suffix = $name;
  681. $name = '';
  682. }
  683. else {
  684. $pos = strrpos($name, '__');
  685. $suffix = substr($name, $pos + 2);
  686. $name = substr($name, 0, $pos);
  687. }
  688. $constraint_name = $this->ensureIdentifiersLength($table, $name, $suffix);
  689. // Remove leading and trailing quotes because the index name is in a WHERE
  690. // clause and not used as an identifier.
  691. $constraint_name = str_replace('"', '', $constraint_name);
  692. return (bool) $this->connection->query("SELECT 1 FROM pg_constraint WHERE conname = '$constraint_name'")->fetchField();
  693. }
  694. /**
  695. * {@inheritdoc}
  696. */
  697. public function addPrimaryKey($table, $fields) {
  698. if (!$this->tableExists($table)) {
  699. throw new SchemaObjectDoesNotExistException("Cannot add primary key to table '$table': table doesn't exist.");
  700. }
  701. if ($this->constraintExists($table, 'pkey')) {
  702. throw new SchemaObjectExistsException("Cannot add primary key to table '$table': primary key already exists.");
  703. }
  704. $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey') . ' PRIMARY KEY (' . $this->createPrimaryKeySql($fields) . ')');
  705. $this->resetTableInformation($table);
  706. }
  707. /**
  708. * {@inheritdoc}
  709. */
  710. public function dropPrimaryKey($table) {
  711. if (!$this->constraintExists($table, 'pkey')) {
  712. return FALSE;
  713. }
  714. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey'));
  715. $this->resetTableInformation($table);
  716. return TRUE;
  717. }
  718. /**
  719. * {@inheritdoc}
  720. */
  721. protected function findPrimaryKeyColumns($table) {
  722. if (!$this->tableExists($table)) {
  723. return FALSE;
  724. }
  725. // Fetch the 'indkey' column from 'pg_index' to figure out the order of the
  726. // primary key.
  727. // @todo Use 'array_position()' to be able to perform the ordering in SQL
  728. // directly when 9.5 is the minimum PostgreSQL version.
  729. $result = $this->connection->query("SELECT a.attname, i.indkey FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indrelid = '{" . $table . "}'::regclass AND i.indisprimary")->fetchAllKeyed();
  730. if (!$result) {
  731. return [];
  732. }
  733. $order = explode(' ', reset($result));
  734. $columns = array_combine($order, array_keys($result));
  735. ksort($columns);
  736. return array_values($columns);
  737. }
  738. /**
  739. * {@inheritdoc}
  740. */
  741. public function addUniqueKey($table, $name, $fields) {
  742. if (!$this->tableExists($table)) {
  743. throw new SchemaObjectDoesNotExistException("Cannot add unique key '$name' to table '$table': table doesn't exist.");
  744. }
  745. if ($this->constraintExists($table, $name . '__key')) {
  746. throw new SchemaObjectExistsException("Cannot add unique key '$name' to table '$table': unique key already exists.");
  747. }
  748. $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key') . ' UNIQUE (' . implode(',', $fields) . ')');
  749. $this->resetTableInformation($table);
  750. }
  751. /**
  752. * {@inheritdoc}
  753. */
  754. public function dropUniqueKey($table, $name) {
  755. if (!$this->constraintExists($table, $name . '__key')) {
  756. return FALSE;
  757. }
  758. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key'));
  759. $this->resetTableInformation($table);
  760. return TRUE;
  761. }
  762. /**
  763. * {@inheritdoc}
  764. */
  765. public function addIndex($table, $name, $fields, array $spec) {
  766. if (!$this->tableExists($table)) {
  767. throw new SchemaObjectDoesNotExistException("Cannot add index '$name' to table '$table': table doesn't exist.");
  768. }
  769. if ($this->indexExists($table, $name)) {
  770. throw new SchemaObjectExistsException("Cannot add index '$name' to table '$table': index already exists.");
  771. }
  772. $this->connection->query($this->_createIndexSql($table, $name, $fields));
  773. $this->resetTableInformation($table);
  774. }
  775. /**
  776. * {@inheritdoc}
  777. */
  778. public function dropIndex($table, $name) {
  779. if (!$this->indexExists($table, $name)) {
  780. return FALSE;
  781. }
  782. $this->connection->query('DROP INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx'));
  783. $this->resetTableInformation($table);
  784. return TRUE;
  785. }
  786. /**
  787. * {@inheritdoc}
  788. */
  789. protected function introspectIndexSchema($table) {
  790. if (!$this->tableExists($table)) {
  791. throw new SchemaObjectDoesNotExistException("The table $table doesn't exist.");
  792. }
  793. $index_schema = [
  794. 'primary key' => [],
  795. 'unique keys' => [],
  796. 'indexes' => [],
  797. ];
  798. $result = $this->connection->query("SELECT i.relname AS index_name, a.attname AS column_name FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' AND t.relname = :table_name ORDER BY index_name ASC, column_name ASC", [
  799. ':table_name' => $this->connection->prefixTables('{' . $table . '}'),
  800. ])->fetchAll();
  801. foreach ($result as $row) {
  802. if (preg_match('/_pkey$/', $row->index_name)) {
  803. $index_schema['primary key'][] = $row->column_name;
  804. }
  805. elseif (preg_match('/_key$/', $row->index_name)) {
  806. $index_schema['unique keys'][$row->index_name][] = $row->column_name;
  807. }
  808. elseif (preg_match('/_idx$/', $row->index_name)) {
  809. $index_schema['indexes'][$row->index_name][] = $row->column_name;
  810. }
  811. }
  812. return $index_schema;
  813. }
  814. /**
  815. * {@inheritdoc}
  816. */
  817. public function changeField($table, $field, $field_new, $spec, $new_keys = []) {
  818. if (!$this->fieldExists($table, $field)) {
  819. throw new SchemaObjectDoesNotExistException("Cannot change the definition of field '$table.$field': field doesn't exist.");
  820. }
  821. if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
  822. throw new SchemaObjectExistsException("Cannot rename field '$table.$field' to '$field_new': target field already exists.");
  823. }
  824. if (isset($new_keys['primary key']) && in_array($field_new, $new_keys['primary key'], TRUE)) {
  825. $this->ensureNotNullPrimaryKey($new_keys['primary key'], [$field_new => $spec]);
  826. }
  827. $spec = $this->processField($spec);
  828. // Type 'serial' is known to PostgreSQL, but only during table creation,
  829. // not when altering. Because of that, we create it here as an 'int'. After
  830. // we create it we manually re-apply the sequence.
  831. if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
  832. $field_def = 'int';
  833. }
  834. else {
  835. $field_def = $spec['pgsql_type'];
  836. }
  837. if (in_array($spec['pgsql_type'], ['varchar', 'character', 'text']) && isset($spec['length'])) {
  838. $field_def .= '(' . $spec['length'] . ')';
  839. }
  840. elseif (isset($spec['precision']) && isset($spec['scale'])) {
  841. $field_def .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
  842. }
  843. // Remove old check constraints.
  844. $field_info = $this->queryFieldInformation($table, $field);
  845. foreach ($field_info as $check) {
  846. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"');
  847. }
  848. // Remove old default.
  849. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT');
  850. // Convert field type.
  851. // Usually, we do this via a simple typecast 'USING fieldname::type'. But
  852. // the typecast does not work for conversions to bytea.
  853. // @see http://www.postgresql.org/docs/current/static/datatype-binary.html
  854. $table_information = $this->queryTableInformation($table);
  855. $is_bytea = !empty($table_information->blob_fields[$field]);
  856. if ($spec['pgsql_type'] != 'bytea') {
  857. if ($is_bytea) {
  858. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING convert_from("' . $field . '"' . ", 'UTF8')");
  859. }
  860. else {
  861. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING "' . $field . '"::' . $field_def);
  862. }
  863. }
  864. else {
  865. // Do not attempt to convert a field that is bytea already.
  866. if (!$is_bytea) {
  867. // Convert to a bytea type by using the SQL replace() function to
  868. // convert any single backslashes in the field content to double
  869. // backslashes ('\' to '\\').
  870. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING decode(replace("' . $field . '"' . ", E'\\\\', E'\\\\\\\\'), 'escape');");
  871. }
  872. }
  873. if (isset($spec['not null'])) {
  874. if ($spec['not null']) {
  875. $nullaction = 'SET NOT NULL';
  876. }
  877. else {
  878. $nullaction = 'DROP NOT NULL';
  879. }
  880. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $nullaction);
  881. }
  882. if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
  883. // Type "serial" is known to PostgreSQL, but *only* during table creation,
  884. // not when altering. Because of that, the sequence needs to be created
  885. // and initialized by hand.
  886. $seq = $this->connection->makeSequenceName($table, $field_new);
  887. $this->connection->query("CREATE SEQUENCE " . $seq);
  888. // Set sequence to maximal field value to not conflict with existing
  889. // entries.
  890. $this->connection->query("SELECT setval('" . $seq . "', MAX(\"" . $field . '")) FROM {' . $table . "}");
  891. $this->connection->query('ALTER TABLE {' . $table . '} ALTER ' . $field . ' SET DEFAULT nextval(' . $this->connection->quote($seq) . ')');
  892. }
  893. // Rename the column if necessary.
  894. if ($field != $field_new) {
  895. $this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"');
  896. }
  897. // Add unsigned check if necessary.
  898. if (!empty($spec['unsigned'])) {
  899. $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)');
  900. }
  901. // Add default if necessary.
  902. if (isset($spec['default'])) {
  903. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field_new . '" SET DEFAULT ' . $this->escapeDefaultValue($spec['default']));
  904. }
  905. // Change description if necessary.
  906. if (!empty($spec['description'])) {
  907. $this->connection->query('COMMENT ON COLUMN {' . $table . '}."' . $field_new . '" IS ' . $this->prepareComment($spec['description']));
  908. }
  909. if (isset($new_keys)) {
  910. $this->_createKeys($table, $new_keys);
  911. }
  912. $this->resetTableInformation($table);
  913. }
  914. protected function _createIndexSql($table, $name, $fields) {
  915. $query = 'CREATE INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx') . ' ON {' . $table . '} (';
  916. $query .= $this->_createKeySql($fields) . ')';
  917. return $query;
  918. }
  919. protected function _createKeys($table, $new_keys) {
  920. if (isset($new_keys['primary key'])) {
  921. $this->addPrimaryKey($table, $new_keys['primary key']);
  922. }
  923. if (isset($new_keys['unique keys'])) {
  924. foreach ($new_keys['unique keys'] as $name => $fields) {
  925. $this->addUniqueKey($table, $name, $fields);
  926. }
  927. }
  928. if (isset($new_keys['indexes'])) {
  929. foreach ($new_keys['indexes'] as $name => $fields) {
  930. // Even though $new_keys is not a full schema it still has 'indexes' and
  931. // so is a partial schema. Technically addIndex() doesn't do anything
  932. // with it so passing an empty array would work as well.
  933. $this->addIndex($table, $name, $fields, $new_keys);
  934. }
  935. }
  936. }
  937. /**
  938. * Retrieve a table or column comment.
  939. */
  940. public function getComment($table, $column = NULL) {
  941. $info = $this->getPrefixInfo($table);
  942. // Don't use {} around pg_class, pg_attribute tables.
  943. if (isset($column)) {
  944. return $this->connection->query('SELECT col_description(oid, attnum) FROM pg_class, pg_attribute WHERE attrelid = oid AND relname = ? AND attname = ?', [$info['table'], $column])->fetchField();
  945. }
  946. else {
  947. return $this->connection->query('SELECT obj_description(oid, ?) FROM pg_class WHERE relname = ?', ['pg_class', $info['table']])->fetchField();
  948. }
  949. }
  950. /**
  951. * Calculates a base-64 encoded, PostgreSQL-safe sha-256 hash per PostgreSQL
  952. * documentation: 4.1. Lexical Structure.
  953. *
  954. * @param $data
  955. * String to be hashed.
  956. *
  957. * @return string
  958. * A base-64 encoded sha-256 hash, with + and / replaced with _ and any =
  959. * padding characters removed.
  960. */
  961. protected function hashBase64($data) {
  962. $hash = base64_encode(hash('sha256', $data, TRUE));
  963. // Modify the hash so it's safe to use in PostgreSQL identifiers.
  964. return strtr($hash, ['+' => '_', '/' => '_', '=' => '']);
  965. }
  966. }
  967. /**
  968. * @} End of "addtogroup schemaapi".
  969. */