Schema.php 33 KB

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