Schema.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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 no longer identifiers 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. *
  50. * @param $identifiers
  51. * The arguments to build the identifier string
  52. * @return
  53. * The index/constraint/pkey identifier
  54. */
  55. protected function ensureIdentifiersLength($identifier) {
  56. $args = func_get_args();
  57. $info = $this->getPrefixInfo($identifier);
  58. $args[0] = $info['table'];
  59. $identifierName = implode('__', $args);
  60. // Retrieve the max identifier length which is usually 63 characters
  61. // but can be altered before PostgreSQL is compiled so we need to check.
  62. $this->maxIdentifierLength = $this->connection->query("SHOW max_identifier_length")->fetchField();
  63. if (strlen($identifierName) > $this->maxIdentifierLength) {
  64. $saveIdentifier = '"drupal_' . $this->hashBase64($identifierName) . '_' . $args[2] . '"';
  65. }
  66. else {
  67. $saveIdentifier = $identifierName;
  68. }
  69. return $saveIdentifier;
  70. }
  71. /**
  72. * Fetch the list of blobs and sequences used on a table.
  73. *
  74. * We introspect the database to collect the information required by insert
  75. * and update queries.
  76. *
  77. * @param $table_name
  78. * The non-prefixed name of the table.
  79. * @return
  80. * An object with two member variables:
  81. * - 'blob_fields' that lists all the blob fields in the table.
  82. * - 'sequences' that lists the sequences used in that table.
  83. */
  84. public function queryTableInformation($table) {
  85. // Generate a key to reference this table's information on.
  86. $key = $this->connection->prefixTables('{' . $table . '}');
  87. // Take into account that temporary tables are stored in a different schema.
  88. // \Drupal\Core\Database\Connection::generateTemporaryTableName() sets the
  89. // 'db_temporary_' prefix to all temporary tables.
  90. if (strpos($key, '.') === FALSE && strpos($table, 'db_temporary_') === FALSE) {
  91. $key = 'public.' . $key;
  92. }
  93. else {
  94. $key = $this->getTempNamespaceName() . '.' . $key;
  95. }
  96. if (!isset($this->tableInformation[$key])) {
  97. $table_information = (object) [
  98. 'blob_fields' => [],
  99. 'sequences' => [],
  100. ];
  101. $this->connection->addSavepoint();
  102. try {
  103. // The bytea columns and sequences for a table can be found in
  104. // pg_attribute, which is significantly faster than querying the
  105. // information_schema. The data type of a field can be found by lookup
  106. // of the attribute ID, and the default value must be extracted from the
  107. // node tree for the attribute definition instead of the historical
  108. // human-readable column, adsrc.
  109. $sql = <<<'EOD'
  110. 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
  111. FROM pg_attribute
  112. LEFT JOIN pg_attrdef ON pg_attrdef.adrelid = pg_attribute.attrelid AND pg_attrdef.adnum = pg_attribute.attnum
  113. WHERE pg_attribute.attnum > 0
  114. AND NOT pg_attribute.attisdropped
  115. AND pg_attribute.attrelid = :key::regclass
  116. AND (format_type(pg_attribute.atttypid, pg_attribute.atttypmod) = 'bytea'
  117. OR pg_attrdef.adsrc LIKE 'nextval%')
  118. EOD;
  119. $result = $this->connection->query($sql, [
  120. ':key' => $key,
  121. ]);
  122. }
  123. catch (\Exception $e) {
  124. $this->connection->rollbackSavepoint();
  125. throw $e;
  126. }
  127. $this->connection->releaseSavepoint();
  128. // If the table information does not yet exist in the PostgreSQL
  129. // metadata, then return the default table information here, so that it
  130. // will not be cached.
  131. if (empty($result)) {
  132. return $table_information;
  133. }
  134. foreach ($result as $column) {
  135. if ($column->data_type == 'bytea') {
  136. $table_information->blob_fields[$column->column_name] = TRUE;
  137. }
  138. elseif (preg_match("/nextval\('([^']+)'/", $column->column_default, $matches)) {
  139. // We must know of any sequences in the table structure to help us
  140. // return the last insert id. If there is more than 1 sequences the
  141. // first one (index 0 of the sequences array) will be used.
  142. $table_information->sequences[] = $matches[1];
  143. $table_information->serial_fields[] = $column->column_name;
  144. }
  145. }
  146. $this->tableInformation[$key] = $table_information;
  147. }
  148. return $this->tableInformation[$key];
  149. }
  150. /**
  151. * Gets PostgreSQL's temporary namespace name.
  152. *
  153. * @return string
  154. * PostgreSQL's temporary namespace name.
  155. */
  156. protected function getTempNamespaceName() {
  157. if (!isset($this->tempNamespaceName)) {
  158. $this->tempNamespaceName = $this->connection->query('SELECT nspname FROM pg_namespace WHERE oid = pg_my_temp_schema()')->fetchField();
  159. }
  160. return $this->tempNamespaceName;
  161. }
  162. /**
  163. * Resets information about table blobs, sequences and serial fields.
  164. *
  165. * @param $table
  166. * The non-prefixed name of the table.
  167. */
  168. protected function resetTableInformation($table) {
  169. $key = $this->connection->prefixTables('{' . $table . '}');
  170. if (strpos($key, '.') === FALSE) {
  171. $key = 'public.' . $key;
  172. }
  173. unset($this->tableInformation[$key]);
  174. }
  175. /**
  176. * Fetch the list of CHECK constraints used on a field.
  177. *
  178. * We introspect the database to collect the information required by field
  179. * alteration.
  180. *
  181. * @param $table
  182. * The non-prefixed name of the table.
  183. * @param $field
  184. * The name of the field.
  185. * @return
  186. * An array of all the checks for the field.
  187. */
  188. public function queryFieldInformation($table, $field) {
  189. $prefixInfo = $this->getPrefixInfo($table, TRUE);
  190. // Split the key into schema and table for querying.
  191. $schema = $prefixInfo['schema'];
  192. $table_name = $prefixInfo['table'];
  193. $this->connection->addSavepoint();
  194. try {
  195. $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", [
  196. ':schema' => $schema,
  197. ':table' => $table_name,
  198. ':column' => $field,
  199. ]);
  200. }
  201. catch (\Exception $e) {
  202. $this->connection->rollbackSavepoint();
  203. throw $e;
  204. }
  205. $this->connection->releaseSavepoint();
  206. $field_information = $checks->fetchCol();
  207. return $field_information;
  208. }
  209. /**
  210. * Generate SQL to create a new table from a Drupal schema definition.
  211. *
  212. * @param $name
  213. * The name of the table to create.
  214. * @param $table
  215. * A Schema API table definition array.
  216. * @return
  217. * An array of SQL statements to create the table.
  218. */
  219. protected function createTableSql($name, $table) {
  220. $sql_fields = [];
  221. foreach ($table['fields'] as $field_name => $field) {
  222. $sql_fields[] = $this->createFieldSql($field_name, $this->processField($field));
  223. }
  224. $sql_keys = [];
  225. if (!empty($table['primary key']) && is_array($table['primary key'])) {
  226. $this->ensureNotNullPrimaryKey($table['primary key'], $table['fields']);
  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'] = mb_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 data types 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($new_keys['primary key']) && in_array($field, $new_keys['primary key'], TRUE);
  492. if ($is_primary_key) {
  493. $this->ensureNotNullPrimaryKey($new_keys['primary key'], [$field => $spec]);
  494. }
  495. $fixnull = FALSE;
  496. if (!empty($spec['not null']) && !isset($spec['default']) && !$is_primary_key) {
  497. $fixnull = TRUE;
  498. $spec['not null'] = FALSE;
  499. }
  500. $query = 'ALTER TABLE {' . $table . '} ADD COLUMN ';
  501. $query .= $this->createFieldSql($field, $this->processField($spec));
  502. $this->connection->query($query);
  503. if (isset($spec['initial_from_field'])) {
  504. if (isset($spec['initial'])) {
  505. $expression = 'COALESCE(' . $spec['initial_from_field'] . ', :default_initial_value)';
  506. $arguments = [':default_initial_value' => $spec['initial']];
  507. }
  508. else {
  509. $expression = $spec['initial_from_field'];
  510. $arguments = [];
  511. }
  512. $this->connection->update($table)
  513. ->expression($field, $expression, $arguments)
  514. ->execute();
  515. }
  516. elseif (isset($spec['initial'])) {
  517. $this->connection->update($table)
  518. ->fields([$field => $spec['initial']])
  519. ->execute();
  520. }
  521. if ($fixnull) {
  522. $this->connection->query("ALTER TABLE {" . $table . "} ALTER $field SET NOT NULL");
  523. }
  524. if (isset($new_keys)) {
  525. // Make sure to drop the existing primary key before adding a new one.
  526. // This is only needed when adding a field because this method, unlike
  527. // changeField(), is supposed to handle primary keys automatically.
  528. if (isset($new_keys['primary key']) && $this->constraintExists($table, 'pkey')) {
  529. $this->dropPrimaryKey($table);
  530. }
  531. $this->_createKeys($table, $new_keys);
  532. }
  533. // Add column comment.
  534. if (!empty($spec['description'])) {
  535. $this->connection->query('COMMENT ON COLUMN {' . $table . '}.' . $field . ' IS ' . $this->prepareComment($spec['description']));
  536. }
  537. $this->resetTableInformation($table);
  538. }
  539. /**
  540. * {@inheritdoc}
  541. */
  542. public function dropField($table, $field) {
  543. if (!$this->fieldExists($table, $field)) {
  544. return FALSE;
  545. }
  546. $this->connection->query('ALTER TABLE {' . $table . '} DROP COLUMN "' . $field . '"');
  547. $this->resetTableInformation($table);
  548. return TRUE;
  549. }
  550. /**
  551. * {@inheritdoc}
  552. */
  553. public function fieldSetDefault($table, $field, $default) {
  554. if (!$this->fieldExists($table, $field)) {
  555. throw new SchemaObjectDoesNotExistException(t("Cannot set default value of field @table.@field: field doesn't exist.", ['@table' => $table, '@field' => $field]));
  556. }
  557. $default = $this->escapeDefaultValue($default);
  558. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" SET DEFAULT ' . $default);
  559. }
  560. /**
  561. * {@inheritdoc}
  562. */
  563. public function fieldSetNoDefault($table, $field) {
  564. if (!$this->fieldExists($table, $field)) {
  565. throw new SchemaObjectDoesNotExistException(t("Cannot remove default value of field @table.@field: field doesn't exist.", ['@table' => $table, '@field' => $field]));
  566. }
  567. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT');
  568. }
  569. /**
  570. * {@inheritdoc}
  571. */
  572. public function fieldExists($table, $column) {
  573. $prefixInfo = $this->getPrefixInfo($table);
  574. 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();
  575. }
  576. /**
  577. * {@inheritdoc}
  578. */
  579. public function indexExists($table, $name) {
  580. // Details http://www.postgresql.org/docs/9.1/interactive/view-pg-indexes.html
  581. $index_name = $this->ensureIdentifiersLength($table, $name, 'idx');
  582. // Remove leading and trailing quotes because the index name is in a WHERE
  583. // clause and not used as an identifier.
  584. $index_name = str_replace('"', '', $index_name);
  585. return (bool) $this->connection->query("SELECT 1 FROM pg_indexes WHERE indexname = '$index_name'")->fetchField();
  586. }
  587. /**
  588. * Helper function: check if a constraint (PK, FK, UK) exists.
  589. *
  590. * @param string $table
  591. * The name of the table.
  592. * @param string $name
  593. * The name of the constraint (typically 'pkey' or '[constraint]__key').
  594. *
  595. * @return bool
  596. * TRUE if the constraint exists, FALSE otherwise.
  597. */
  598. public function constraintExists($table, $name) {
  599. // ::ensureIdentifiersLength() expects three parameters, although not
  600. // explicitly stated in its signature, thus we split our constraint name in
  601. // a proper name and a suffix.
  602. if ($name == 'pkey') {
  603. $suffix = $name;
  604. $name = '';
  605. }
  606. else {
  607. $pos = strrpos($name, '__');
  608. $suffix = substr($name, $pos + 2);
  609. $name = substr($name, 0, $pos);
  610. }
  611. $constraint_name = $this->ensureIdentifiersLength($table, $name, $suffix);
  612. // Remove leading and trailing quotes because the index name is in a WHERE
  613. // clause and not used as an identifier.
  614. $constraint_name = str_replace('"', '', $constraint_name);
  615. return (bool) $this->connection->query("SELECT 1 FROM pg_constraint WHERE conname = '$constraint_name'")->fetchField();
  616. }
  617. /**
  618. * {@inheritdoc}
  619. */
  620. public function addPrimaryKey($table, $fields) {
  621. if (!$this->tableExists($table)) {
  622. throw new SchemaObjectDoesNotExistException(t("Cannot add primary key to table @table: table doesn't exist.", ['@table' => $table]));
  623. }
  624. if ($this->constraintExists($table, 'pkey')) {
  625. throw new SchemaObjectExistsException(t("Cannot add primary key to table @table: primary key already exists.", ['@table' => $table]));
  626. }
  627. $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey') . ' PRIMARY KEY (' . $this->createPrimaryKeySql($fields) . ')');
  628. $this->resetTableInformation($table);
  629. }
  630. /**
  631. * {@inheritdoc}
  632. */
  633. public function dropPrimaryKey($table) {
  634. if (!$this->constraintExists($table, 'pkey')) {
  635. return FALSE;
  636. }
  637. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, '', 'pkey'));
  638. $this->resetTableInformation($table);
  639. return TRUE;
  640. }
  641. /**
  642. * {@inheritdoc}
  643. */
  644. protected function findPrimaryKeyColumns($table) {
  645. if (!$this->tableExists($table)) {
  646. return FALSE;
  647. }
  648. // Fetch the 'indkey' column from 'pg_index' to figure out the order of the
  649. // primary key.
  650. // @todo Use 'array_position()' to be able to perform the ordering in SQL
  651. // directly when 9.5 is the minimum PostgreSQL version.
  652. $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();
  653. if (!$result) {
  654. return [];
  655. }
  656. $order = explode(' ', reset($result));
  657. $columns = array_combine($order, array_keys($result));
  658. ksort($columns);
  659. return array_values($columns);
  660. }
  661. /**
  662. * {@inheritdoc}
  663. */
  664. public function addUniqueKey($table, $name, $fields) {
  665. if (!$this->tableExists($table)) {
  666. throw new SchemaObjectDoesNotExistException(t("Cannot add unique key @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
  667. }
  668. if ($this->constraintExists($table, $name . '__key')) {
  669. throw new SchemaObjectExistsException(t("Cannot add unique key @name to table @table: unique key already exists.", ['@table' => $table, '@name' => $name]));
  670. }
  671. $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key') . ' UNIQUE (' . implode(',', $fields) . ')');
  672. $this->resetTableInformation($table);
  673. }
  674. /**
  675. * {@inheritdoc}
  676. */
  677. public function dropUniqueKey($table, $name) {
  678. if (!$this->constraintExists($table, $name . '__key')) {
  679. return FALSE;
  680. }
  681. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->ensureIdentifiersLength($table, $name, 'key'));
  682. $this->resetTableInformation($table);
  683. return TRUE;
  684. }
  685. /**
  686. * {@inheritdoc}
  687. */
  688. public function addIndex($table, $name, $fields, array $spec) {
  689. if (!$this->tableExists($table)) {
  690. throw new SchemaObjectDoesNotExistException(t("Cannot add index @name to table @table: table doesn't exist.", ['@table' => $table, '@name' => $name]));
  691. }
  692. if ($this->indexExists($table, $name)) {
  693. throw new SchemaObjectExistsException(t("Cannot add index @name to table @table: index already exists.", ['@table' => $table, '@name' => $name]));
  694. }
  695. $this->connection->query($this->_createIndexSql($table, $name, $fields));
  696. $this->resetTableInformation($table);
  697. }
  698. /**
  699. * {@inheritdoc}
  700. */
  701. public function dropIndex($table, $name) {
  702. if (!$this->indexExists($table, $name)) {
  703. return FALSE;
  704. }
  705. $this->connection->query('DROP INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx'));
  706. $this->resetTableInformation($table);
  707. return TRUE;
  708. }
  709. /**
  710. * {@inheritdoc}
  711. */
  712. public function changeField($table, $field, $field_new, $spec, $new_keys = []) {
  713. if (!$this->fieldExists($table, $field)) {
  714. throw new SchemaObjectDoesNotExistException(t("Cannot change the definition of field @table.@name: field doesn't exist.", ['@table' => $table, '@name' => $field]));
  715. }
  716. if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
  717. throw new SchemaObjectExistsException(t("Cannot rename field @table.@name to @name_new: target field already exists.", ['@table' => $table, '@name' => $field, '@name_new' => $field_new]));
  718. }
  719. if (isset($new_keys['primary key']) && in_array($field_new, $new_keys['primary key'], TRUE)) {
  720. $this->ensureNotNullPrimaryKey($new_keys['primary key'], [$field_new => $spec]);
  721. }
  722. $spec = $this->processField($spec);
  723. // Type 'serial' is known to PostgreSQL, but only during table creation,
  724. // not when altering. Because of that, we create it here as an 'int'. After
  725. // we create it we manually re-apply the sequence.
  726. if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
  727. $field_def = 'int';
  728. }
  729. else {
  730. $field_def = $spec['pgsql_type'];
  731. }
  732. if (in_array($spec['pgsql_type'], ['varchar', 'character', 'text']) && isset($spec['length'])) {
  733. $field_def .= '(' . $spec['length'] . ')';
  734. }
  735. elseif (isset($spec['precision']) && isset($spec['scale'])) {
  736. $field_def .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
  737. }
  738. // Remove old check constraints.
  739. $field_info = $this->queryFieldInformation($table, $field);
  740. foreach ($field_info as $check) {
  741. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"');
  742. }
  743. // Remove old default.
  744. $this->fieldSetNoDefault($table, $field);
  745. // Convert field type.
  746. // Usually, we do this via a simple typecast 'USING fieldname::type'. But
  747. // the typecast does not work for conversions to bytea.
  748. // @see http://www.postgresql.org/docs/current/static/datatype-binary.html
  749. $table_information = $this->queryTableInformation($table);
  750. $is_bytea = !empty($table_information->blob_fields[$field]);
  751. if ($spec['pgsql_type'] != 'bytea') {
  752. if ($is_bytea) {
  753. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING convert_from("' . $field . '"' . ", 'UTF8')");
  754. }
  755. else {
  756. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING "' . $field . '"::' . $field_def);
  757. }
  758. }
  759. else {
  760. // Do not attempt to convert a field that is bytea already.
  761. if (!$is_bytea) {
  762. // Convert to a bytea type by using the SQL replace() function to
  763. // convert any single backslashes in the field content to double
  764. // backslashes ('\' to '\\').
  765. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $field_def . ' USING decode(replace("' . $field . '"' . ", E'\\\\', E'\\\\\\\\'), 'escape');");
  766. }
  767. }
  768. if (isset($spec['not null'])) {
  769. if ($spec['not null']) {
  770. $nullaction = 'SET NOT NULL';
  771. }
  772. else {
  773. $nullaction = 'DROP NOT NULL';
  774. }
  775. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $nullaction);
  776. }
  777. if (in_array($spec['pgsql_type'], ['serial', 'bigserial'])) {
  778. // Type "serial" is known to PostgreSQL, but *only* during table creation,
  779. // not when altering. Because of that, the sequence needs to be created
  780. // and initialized by hand.
  781. $seq = "{" . $table . "}_" . $field_new . "_seq";
  782. $this->connection->query("CREATE SEQUENCE " . $seq);
  783. // Set sequence to maximal field value to not conflict with existing
  784. // entries.
  785. $this->connection->query("SELECT setval('" . $seq . "', MAX(\"" . $field . '")) FROM {' . $table . "}");
  786. $this->connection->query('ALTER TABLE {' . $table . '} ALTER ' . $field . ' SET DEFAULT nextval(' . $this->connection->quote($seq) . ')');
  787. }
  788. // Rename the column if necessary.
  789. if ($field != $field_new) {
  790. $this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"');
  791. }
  792. // Add unsigned check if necessary.
  793. if (!empty($spec['unsigned'])) {
  794. $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)');
  795. }
  796. // Add default if necessary.
  797. if (isset($spec['default'])) {
  798. $this->fieldSetDefault($table, $field_new, $spec['default']);
  799. }
  800. // Change description if necessary.
  801. if (!empty($spec['description'])) {
  802. $this->connection->query('COMMENT ON COLUMN {' . $table . '}."' . $field_new . '" IS ' . $this->prepareComment($spec['description']));
  803. }
  804. if (isset($new_keys)) {
  805. $this->_createKeys($table, $new_keys);
  806. }
  807. $this->resetTableInformation($table);
  808. }
  809. protected function _createIndexSql($table, $name, $fields) {
  810. $query = 'CREATE INDEX ' . $this->ensureIdentifiersLength($table, $name, 'idx') . ' ON {' . $table . '} (';
  811. $query .= $this->_createKeySql($fields) . ')';
  812. return $query;
  813. }
  814. protected function _createKeys($table, $new_keys) {
  815. if (isset($new_keys['primary key'])) {
  816. $this->addPrimaryKey($table, $new_keys['primary key']);
  817. }
  818. if (isset($new_keys['unique keys'])) {
  819. foreach ($new_keys['unique keys'] as $name => $fields) {
  820. $this->addUniqueKey($table, $name, $fields);
  821. }
  822. }
  823. if (isset($new_keys['indexes'])) {
  824. foreach ($new_keys['indexes'] as $name => $fields) {
  825. // Even though $new_keys is not a full schema it still has 'indexes' and
  826. // so is a partial schema. Technically addIndex() doesn't do anything
  827. // with it so passing an empty array would work as well.
  828. $this->addIndex($table, $name, $fields, $new_keys);
  829. }
  830. }
  831. }
  832. /**
  833. * Retrieve a table or column comment.
  834. */
  835. public function getComment($table, $column = NULL) {
  836. $info = $this->getPrefixInfo($table);
  837. // Don't use {} around pg_class, pg_attribute tables.
  838. if (isset($column)) {
  839. 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();
  840. }
  841. else {
  842. return $this->connection->query('SELECT obj_description(oid, ?) FROM pg_class WHERE relname = ?', ['pg_class', $info['table']])->fetchField();
  843. }
  844. }
  845. /**
  846. * Calculates a base-64 encoded, PostgreSQL-safe sha-256 hash per PostgreSQL
  847. * documentation: 4.1. Lexical Structure.
  848. *
  849. * @param $data
  850. * String to be hashed.
  851. * @return string
  852. * A base-64 encoded sha-256 hash, with + and / replaced with _ and any =
  853. * padding characters removed.
  854. */
  855. protected function hashBase64($data) {
  856. $hash = base64_encode(hash('sha256', $data, TRUE));
  857. // Modify the hash so it's safe to use in PostgreSQL identifiers.
  858. return strtr($hash, ['+' => '_', '/' => '_', '=' => '']);
  859. }
  860. }
  861. /**
  862. * @} End of "addtogroup schemaapi".
  863. */