schema.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. * A cache of information about blob columns and sequences of tables.
  13. *
  14. * This is collected by DatabaseConnection_pgsql->queryTableInformation(),
  15. * by introspecting the database.
  16. *
  17. * @see DatabaseConnection_pgsql->queryTableInformation()
  18. * @var array
  19. */
  20. protected $tableInformation = array();
  21. /**
  22. * Fetch the list of blobs and sequences used on a table.
  23. *
  24. * We introspect the database to collect the information required by insert
  25. * and update queries.
  26. *
  27. * @param $table_name
  28. * The non-prefixed name of the table.
  29. * @return
  30. * An object with two member variables:
  31. * - 'blob_fields' that lists all the blob fields in the table.
  32. * - 'sequences' that lists the sequences used in that table.
  33. */
  34. public function queryTableInformation($table) {
  35. // Generate a key to reference this table's information on.
  36. $key = $this->connection->prefixTables('{' . $table . '}');
  37. if (!strpos($key, '.')) {
  38. $key = 'public.' . $key;
  39. }
  40. if (!isset($this->tableInformation[$key])) {
  41. // Split the key into schema and table for querying.
  42. list($schema, $table_name) = explode('.', $key);
  43. $table_information = (object) array(
  44. 'blob_fields' => array(),
  45. 'sequences' => array(),
  46. );
  47. // Don't use {} around information_schema.columns table.
  48. $result = $this->connection->query("SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_schema = :schema AND table_name = :table AND (data_type = 'bytea' OR (numeric_precision IS NOT NULL AND column_default LIKE :default))", array(
  49. ':schema' => $schema,
  50. ':table' => $table_name,
  51. ':default' => '%nextval%',
  52. ));
  53. foreach ($result as $column) {
  54. if ($column->data_type == 'bytea') {
  55. $table_information->blob_fields[$column->column_name] = TRUE;
  56. }
  57. elseif (preg_match("/nextval\('([^']+)'/", $column->column_default, $matches)) {
  58. // We must know of any sequences in the table structure to help us
  59. // return the last insert id. If there is more than 1 sequences the
  60. // first one (index 0 of the sequences array) will be used.
  61. $table_information->sequences[] = $matches[1];
  62. $table_information->serial_fields[] = $column->column_name;
  63. }
  64. }
  65. $this->tableInformation[$key] = $table_information;
  66. }
  67. return $this->tableInformation[$key];
  68. }
  69. /**
  70. * Fetch the list of CHECK constraints used on a field.
  71. *
  72. * We introspect the database to collect the information required by field
  73. * alteration.
  74. *
  75. * @param $table
  76. * The non-prefixed name of the table.
  77. * @param $field
  78. * The name of the field.
  79. * @return
  80. * An array of all the checks for the field.
  81. */
  82. public function queryFieldInformation($table, $field) {
  83. $prefixInfo = $this->getPrefixInfo($table, TRUE);
  84. // Split the key into schema and table for querying.
  85. $schema = $prefixInfo['schema'];
  86. $table_name = $prefixInfo['table'];
  87. $field_information = (object) array(
  88. 'checks' => array(),
  89. );
  90. $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(
  91. ':schema' => $schema,
  92. ':table' => $table_name,
  93. ':column' => $field,
  94. ));
  95. $field_information = $checks->fetchCol();
  96. return $field_information;
  97. }
  98. /**
  99. * Generate SQL to create a new table from a Drupal schema definition.
  100. *
  101. * @param $name
  102. * The name of the table to create.
  103. * @param $table
  104. * A Schema API table definition array.
  105. * @return
  106. * An array of SQL statements to create the table.
  107. */
  108. protected function createTableSql($name, $table) {
  109. $sql_fields = array();
  110. foreach ($table['fields'] as $field_name => $field) {
  111. $sql_fields[] = $this->createFieldSql($field_name, $this->processField($field));
  112. }
  113. $sql_keys = array();
  114. if (isset($table['primary key']) && is_array($table['primary key'])) {
  115. $sql_keys[] = 'PRIMARY KEY (' . implode(', ', $table['primary key']) . ')';
  116. }
  117. if (isset($table['unique keys']) && is_array($table['unique keys'])) {
  118. foreach ($table['unique keys'] as $key_name => $key) {
  119. $sql_keys[] = 'CONSTRAINT ' . $this->prefixNonTable($name, $key_name, 'key') . ' UNIQUE (' . implode(', ', $key) . ')';
  120. }
  121. }
  122. $sql = "CREATE TABLE {" . $name . "} (\n\t";
  123. $sql .= implode(",\n\t", $sql_fields);
  124. if (count($sql_keys) > 0) {
  125. $sql .= ",\n\t";
  126. }
  127. $sql .= implode(",\n\t", $sql_keys);
  128. $sql .= "\n)";
  129. $statements[] = $sql;
  130. if (isset($table['indexes']) && is_array($table['indexes'])) {
  131. foreach ($table['indexes'] as $key_name => $key) {
  132. $statements[] = $this->_createIndexSql($name, $key_name, $key);
  133. }
  134. }
  135. // Add table comment.
  136. if (!empty($table['description'])) {
  137. $statements[] = 'COMMENT ON TABLE {' . $name . '} IS ' . $this->prepareComment($table['description']);
  138. }
  139. // Add column comments.
  140. foreach ($table['fields'] as $field_name => $field) {
  141. if (!empty($field['description'])) {
  142. $statements[] = 'COMMENT ON COLUMN {' . $name . '}.' . $field_name . ' IS ' . $this->prepareComment($field['description']);
  143. }
  144. }
  145. return $statements;
  146. }
  147. /**
  148. * Create an SQL string for a field to be used in table creation or
  149. * alteration.
  150. *
  151. * Before passing a field out of a schema definition into this
  152. * function it has to be processed by _db_process_field().
  153. *
  154. * @param $name
  155. * Name of the field.
  156. * @param $spec
  157. * The field specification, as per the schema data structure format.
  158. */
  159. protected function createFieldSql($name, $spec) {
  160. $sql = $name . ' ' . $spec['pgsql_type'];
  161. if (isset($spec['type']) && $spec['type'] == 'serial') {
  162. unset($spec['not null']);
  163. }
  164. if (in_array($spec['pgsql_type'], array('varchar', 'character', 'text')) && isset($spec['length'])) {
  165. $sql .= '(' . $spec['length'] . ')';
  166. }
  167. elseif (isset($spec['precision']) && isset($spec['scale'])) {
  168. $sql .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
  169. }
  170. if (!empty($spec['unsigned'])) {
  171. $sql .= " CHECK ($name >= 0)";
  172. }
  173. if (isset($spec['not null'])) {
  174. if ($spec['not null']) {
  175. $sql .= ' NOT NULL';
  176. }
  177. else {
  178. $sql .= ' NULL';
  179. }
  180. }
  181. if (isset($spec['default'])) {
  182. $default = is_string($spec['default']) ? "'" . $spec['default'] . "'" : $spec['default'];
  183. $sql .= " default $default";
  184. }
  185. return $sql;
  186. }
  187. /**
  188. * Set database-engine specific properties for a field.
  189. *
  190. * @param $field
  191. * A field description array, as specified in the schema documentation.
  192. */
  193. protected function processField($field) {
  194. if (!isset($field['size'])) {
  195. $field['size'] = 'normal';
  196. }
  197. // Set the correct database-engine specific datatype.
  198. // In case one is already provided, force it to lowercase.
  199. if (isset($field['pgsql_type'])) {
  200. $field['pgsql_type'] = drupal_strtolower($field['pgsql_type']);
  201. }
  202. else {
  203. $map = $this->getFieldTypeMap();
  204. $field['pgsql_type'] = $map[$field['type'] . ':' . $field['size']];
  205. }
  206. if (!empty($field['unsigned'])) {
  207. // Unsigned datatypes are not supported in PostgreSQL 8.3. In MySQL,
  208. // they are used to ensure a positive number is inserted and it also
  209. // doubles the maximum integer size that can be stored in a field.
  210. // The PostgreSQL schema in Drupal creates a check constraint
  211. // to ensure that a value inserted is >= 0. To provide the extra
  212. // integer capacity, here, we bump up the column field size.
  213. if (!isset($map)) {
  214. $map = $this->getFieldTypeMap();
  215. }
  216. switch ($field['pgsql_type']) {
  217. case 'smallint':
  218. $field['pgsql_type'] = $map['int:medium'];
  219. break;
  220. case 'int' :
  221. $field['pgsql_type'] = $map['int:big'];
  222. break;
  223. }
  224. }
  225. if (isset($field['type']) && $field['type'] == 'serial') {
  226. unset($field['not null']);
  227. }
  228. return $field;
  229. }
  230. /**
  231. * This maps a generic data type in combination with its data size
  232. * to the engine-specific data type.
  233. */
  234. function getFieldTypeMap() {
  235. // Put :normal last so it gets preserved by array_flip. This makes
  236. // it much easier for modules (such as schema.module) to map
  237. // database types back into schema types.
  238. // $map does not use drupal_static as its value never changes.
  239. static $map = array(
  240. 'varchar:normal' => 'varchar',
  241. 'char:normal' => 'character',
  242. 'text:tiny' => 'text',
  243. 'text:small' => 'text',
  244. 'text:medium' => 'text',
  245. 'text:big' => 'text',
  246. 'text:normal' => 'text',
  247. 'int:tiny' => 'smallint',
  248. 'int:small' => 'smallint',
  249. 'int:medium' => 'int',
  250. 'int:big' => 'bigint',
  251. 'int:normal' => 'int',
  252. 'float:tiny' => 'real',
  253. 'float:small' => 'real',
  254. 'float:medium' => 'real',
  255. 'float:big' => 'double precision',
  256. 'float:normal' => 'real',
  257. 'numeric:normal' => 'numeric',
  258. 'blob:big' => 'bytea',
  259. 'blob:normal' => 'bytea',
  260. 'serial:tiny' => 'serial',
  261. 'serial:small' => 'serial',
  262. 'serial:medium' => 'serial',
  263. 'serial:big' => 'bigserial',
  264. 'serial:normal' => 'serial',
  265. );
  266. return $map;
  267. }
  268. protected function _createKeySql($fields) {
  269. $return = array();
  270. foreach ($fields as $field) {
  271. if (is_array($field)) {
  272. $return[] = 'substr(' . $field[0] . ', 1, ' . $field[1] . ')';
  273. }
  274. else {
  275. $return[] = '"' . $field . '"';
  276. }
  277. }
  278. return implode(', ', $return);
  279. }
  280. function renameTable($table, $new_name) {
  281. if (!$this->tableExists($table)) {
  282. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot rename %table to %table_new: table %table doesn't exist.", array('%table' => $table, '%table_new' => $new_name)));
  283. }
  284. if ($this->tableExists($new_name)) {
  285. throw new DatabaseSchemaObjectExistsException(t("Cannot rename %table to %table_new: table %table_new already exists.", array('%table' => $table, '%table_new' => $new_name)));
  286. }
  287. // Get the schema and tablename for the old table.
  288. $old_full_name = $this->connection->prefixTables('{' . $table . '}');
  289. list($old_schema, $old_table_name) = strpos($old_full_name, '.') ? explode('.', $old_full_name) : array('public', $old_full_name);
  290. // Index names and constraint names are global in PostgreSQL, so we need to
  291. // rename them when renaming the table.
  292. $indexes = $this->connection->query('SELECT indexname FROM pg_indexes WHERE schemaname = :schema AND tablename = :table', array(':schema' => $old_schema, ':table' => $old_table_name));
  293. foreach ($indexes as $index) {
  294. if (preg_match('/^' . preg_quote($old_full_name) . '_(.*)$/', $index->indexname, $matches)) {
  295. $index_name = $matches[1];
  296. $this->connection->query('ALTER INDEX ' . $index->indexname . ' RENAME TO {' . $new_name . '}_' . $index_name);
  297. }
  298. }
  299. // Now rename the table.
  300. // Ensure the new table name does not include schema syntax.
  301. $prefixInfo = $this->getPrefixInfo($new_name);
  302. $this->connection->query('ALTER TABLE {' . $table . '} RENAME TO ' . $prefixInfo['table']);
  303. }
  304. public function dropTable($table) {
  305. if (!$this->tableExists($table)) {
  306. return FALSE;
  307. }
  308. $this->connection->query('DROP TABLE {' . $table . '}');
  309. return TRUE;
  310. }
  311. public function addField($table, $field, $spec, $new_keys = array()) {
  312. if (!$this->tableExists($table)) {
  313. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add field %table.%field: table doesn't exist.", array('%field' => $field, '%table' => $table)));
  314. }
  315. if ($this->fieldExists($table, $field)) {
  316. throw new DatabaseSchemaObjectExistsException(t("Cannot add field %table.%field: field already exists.", array('%field' => $field, '%table' => $table)));
  317. }
  318. $fixnull = FALSE;
  319. if (!empty($spec['not null']) && !isset($spec['default'])) {
  320. $fixnull = TRUE;
  321. $spec['not null'] = FALSE;
  322. }
  323. $query = 'ALTER TABLE {' . $table . '} ADD COLUMN ';
  324. $query .= $this->createFieldSql($field, $this->processField($spec));
  325. $this->connection->query($query);
  326. if (isset($spec['initial'])) {
  327. $this->connection->update($table)
  328. ->fields(array($field => $spec['initial']))
  329. ->execute();
  330. }
  331. if ($fixnull) {
  332. $this->connection->query("ALTER TABLE {" . $table . "} ALTER $field SET NOT NULL");
  333. }
  334. if (isset($new_keys)) {
  335. $this->_createKeys($table, $new_keys);
  336. }
  337. // Add column comment.
  338. if (!empty($spec['description'])) {
  339. $this->connection->query('COMMENT ON COLUMN {' . $table . '}.' . $field . ' IS ' . $this->prepareComment($spec['description']));
  340. }
  341. }
  342. public function dropField($table, $field) {
  343. if (!$this->fieldExists($table, $field)) {
  344. return FALSE;
  345. }
  346. $this->connection->query('ALTER TABLE {' . $table . '} DROP COLUMN "' . $field . '"');
  347. return TRUE;
  348. }
  349. public function fieldSetDefault($table, $field, $default) {
  350. if (!$this->fieldExists($table, $field)) {
  351. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot set default value of field %table.%field: field doesn't exist.", array('%table' => $table, '%field' => $field)));
  352. }
  353. if (!isset($default)) {
  354. $default = 'NULL';
  355. }
  356. else {
  357. $default = is_string($default) ? "'$default'" : $default;
  358. }
  359. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" SET DEFAULT ' . $default);
  360. }
  361. public function fieldSetNoDefault($table, $field) {
  362. if (!$this->fieldExists($table, $field)) {
  363. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot remove default value of field %table.%field: field doesn't exist.", array('%table' => $table, '%field' => $field)));
  364. }
  365. $this->connection->query('ALTER TABLE {' . $table . '} ALTER COLUMN "' . $field . '" DROP DEFAULT');
  366. }
  367. public function indexExists($table, $name) {
  368. // Details http://www.postgresql.org/docs/8.3/interactive/view-pg-indexes.html
  369. $index_name = '{' . $table . '}_' . $name . '_idx';
  370. return (bool) $this->connection->query("SELECT 1 FROM pg_indexes WHERE indexname = '$index_name'")->fetchField();
  371. }
  372. /**
  373. * Helper function: check if a constraint (PK, FK, UK) exists.
  374. *
  375. * @param $table
  376. * The name of the table.
  377. * @param $name
  378. * The name of the constraint (typically 'pkey' or '[constraint]_key').
  379. */
  380. protected function constraintExists($table, $name) {
  381. $constraint_name = '{' . $table . '}_' . $name;
  382. return (bool) $this->connection->query("SELECT 1 FROM pg_constraint WHERE conname = '$constraint_name'")->fetchField();
  383. }
  384. public function addPrimaryKey($table, $fields) {
  385. if (!$this->tableExists($table)) {
  386. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add primary key to table %table: table doesn't exist.", array('%table' => $table)));
  387. }
  388. if ($this->constraintExists($table, 'pkey')) {
  389. throw new DatabaseSchemaObjectExistsException(t("Cannot add primary key to table %table: primary key already exists.", array('%table' => $table)));
  390. }
  391. $this->connection->query('ALTER TABLE {' . $table . '} ADD PRIMARY KEY (' . implode(',', $fields) . ')');
  392. }
  393. public function dropPrimaryKey($table) {
  394. if (!$this->constraintExists($table, 'pkey')) {
  395. return FALSE;
  396. }
  397. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->prefixNonTable($table, 'pkey'));
  398. return TRUE;
  399. }
  400. function addUniqueKey($table, $name, $fields) {
  401. if (!$this->tableExists($table)) {
  402. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add unique key %name to table %table: table doesn't exist.", array('%table' => $table, '%name' => $name)));
  403. }
  404. if ($this->constraintExists($table, $name . '_key')) {
  405. throw new DatabaseSchemaObjectExistsException(t("Cannot add unique key %name to table %table: unique key already exists.", array('%table' => $table, '%name' => $name)));
  406. }
  407. $this->connection->query('ALTER TABLE {' . $table . '} ADD CONSTRAINT "' . $this->prefixNonTable($table, $name, 'key') . '" UNIQUE (' . implode(',', $fields) . ')');
  408. }
  409. public function dropUniqueKey($table, $name) {
  410. if (!$this->constraintExists($table, $name . '_key')) {
  411. return FALSE;
  412. }
  413. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $this->prefixNonTable($table, $name, 'key') . '"');
  414. return TRUE;
  415. }
  416. public function addIndex($table, $name, $fields) {
  417. if (!$this->tableExists($table)) {
  418. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot add index %name to table %table: table doesn't exist.", array('%table' => $table, '%name' => $name)));
  419. }
  420. if ($this->indexExists($table, $name)) {
  421. throw new DatabaseSchemaObjectExistsException(t("Cannot add index %name to table %table: index already exists.", array('%table' => $table, '%name' => $name)));
  422. }
  423. $this->connection->query($this->_createIndexSql($table, $name, $fields));
  424. }
  425. public function dropIndex($table, $name) {
  426. if (!$this->indexExists($table, $name)) {
  427. return FALSE;
  428. }
  429. $this->connection->query('DROP INDEX ' . $this->prefixNonTable($table, $name, 'idx'));
  430. return TRUE;
  431. }
  432. public function changeField($table, $field, $field_new, $spec, $new_keys = array()) {
  433. if (!$this->fieldExists($table, $field)) {
  434. throw new DatabaseSchemaObjectDoesNotExistException(t("Cannot change the definition of field %table.%name: field doesn't exist.", array('%table' => $table, '%name' => $field)));
  435. }
  436. if (($field != $field_new) && $this->fieldExists($table, $field_new)) {
  437. 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)));
  438. }
  439. $spec = $this->processField($spec);
  440. // We need to typecast the new column to best be able to transfer the data
  441. // Schema_pgsql::getFieldTypeMap() will return possibilities that are not
  442. // 'cast-able' such as 'serial' - so they need to be casted int instead.
  443. if (in_array($spec['pgsql_type'], array('serial', 'bigserial', 'numeric'))) {
  444. $typecast = 'int';
  445. }
  446. else {
  447. $typecast = $spec['pgsql_type'];
  448. }
  449. if (in_array($spec['pgsql_type'], array('varchar', 'character', 'text')) && isset($spec['length'])) {
  450. $typecast .= '(' . $spec['length'] . ')';
  451. }
  452. elseif (isset($spec['precision']) && isset($spec['scale'])) {
  453. $typecast .= '(' . $spec['precision'] . ', ' . $spec['scale'] . ')';
  454. }
  455. // Remove old check constraints.
  456. $field_info = $this->queryFieldInformation($table, $field);
  457. foreach ($field_info as $check) {
  458. $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $check . '"');
  459. }
  460. // Remove old default.
  461. $this->fieldSetNoDefault($table, $field);
  462. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" TYPE ' . $typecast . ' USING "' . $field . '"::' . $typecast);
  463. if (isset($spec['not null'])) {
  464. if ($spec['not null']) {
  465. $nullaction = 'SET NOT NULL';
  466. }
  467. else {
  468. $nullaction = 'DROP NOT NULL';
  469. }
  470. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" ' . $nullaction);
  471. }
  472. if (in_array($spec['pgsql_type'], array('serial', 'bigserial'))) {
  473. // Type "serial" is known to PostgreSQL, but *only* during table creation,
  474. // not when altering. Because of that, the sequence needs to be created
  475. // and initialized by hand.
  476. $seq = "{" . $table . "}_" . $field_new . "_seq";
  477. $this->connection->query("CREATE SEQUENCE " . $seq);
  478. // Set sequence to maximal field value to not conflict with existing
  479. // entries.
  480. $this->connection->query("SELECT setval('" . $seq . "', MAX(\"" . $field . '")) FROM {' . $table . "}");
  481. $this->connection->query('ALTER TABLE {' . $table . '} ALTER "' . $field . '" SET DEFAULT nextval(\'' . $seq . '\')');
  482. }
  483. // Rename the column if necessary.
  484. if ($field != $field_new) {
  485. $this->connection->query('ALTER TABLE {' . $table . '} RENAME "' . $field . '" TO "' . $field_new . '"');
  486. }
  487. // Add unsigned check if necessary.
  488. if (!empty($spec['unsigned'])) {
  489. $this->connection->query('ALTER TABLE {' . $table . '} ADD CHECK ("' . $field_new . '" >= 0)');
  490. }
  491. // Add default if necessary.
  492. if (isset($spec['default'])) {
  493. $this->fieldSetDefault($table, $field_new, $spec['default']);
  494. }
  495. // Change description if necessary.
  496. if (!empty($spec['description'])) {
  497. $this->connection->query('COMMENT ON COLUMN {' . $table . '}."' . $field_new . '" IS ' . $this->prepareComment($spec['description']));
  498. }
  499. if (isset($new_keys)) {
  500. $this->_createKeys($table, $new_keys);
  501. }
  502. }
  503. protected function _createIndexSql($table, $name, $fields) {
  504. $query = 'CREATE INDEX "' . $this->prefixNonTable($table, $name, 'idx') . '" ON {' . $table . '} (';
  505. $query .= $this->_createKeySql($fields) . ')';
  506. return $query;
  507. }
  508. protected function _createKeys($table, $new_keys) {
  509. if (isset($new_keys['primary key'])) {
  510. $this->addPrimaryKey($table, $new_keys['primary key']);
  511. }
  512. if (isset($new_keys['unique keys'])) {
  513. foreach ($new_keys['unique keys'] as $name => $fields) {
  514. $this->addUniqueKey($table, $name, $fields);
  515. }
  516. }
  517. if (isset($new_keys['indexes'])) {
  518. foreach ($new_keys['indexes'] as $name => $fields) {
  519. $this->addIndex($table, $name, $fields);
  520. }
  521. }
  522. }
  523. /**
  524. * Retrieve a table or column comment.
  525. */
  526. public function getComment($table, $column = NULL) {
  527. $info = $this->getPrefixInfo($table);
  528. // Don't use {} around pg_class, pg_attribute tables.
  529. if (isset($column)) {
  530. 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();
  531. }
  532. else {
  533. return $this->connection->query('SELECT obj_description(oid, ?) FROM pg_class WHERE relname = ?', array('pg_class', $info['table']))->fetchField();
  534. }
  535. }
  536. }