schema.inc 32 KB

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