Postgres.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. <?php
  2. /**
  3. * PostgreSQL layer for DBO.
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Model.Datasource.Database
  15. * @since CakePHP(tm) v 0.9.1.114
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('DboSource', 'Model/Datasource');
  19. /**
  20. * PostgreSQL layer for DBO.
  21. *
  22. * @package Cake.Model.Datasource.Database
  23. */
  24. class Postgres extends DboSource {
  25. /**
  26. * Driver description
  27. *
  28. * @var string
  29. */
  30. public $description = "PostgreSQL DBO Driver";
  31. /**
  32. * Base driver configuration settings. Merged with user settings.
  33. *
  34. * @var array
  35. */
  36. protected $_baseConfig = array(
  37. 'persistent' => true,
  38. 'host' => 'localhost',
  39. 'login' => 'root',
  40. 'password' => '',
  41. 'database' => 'cake',
  42. 'schema' => 'public',
  43. 'port' => 5432,
  44. 'encoding' => '',
  45. 'flags' => array()
  46. );
  47. /**
  48. * Columns
  49. *
  50. * @var array
  51. */
  52. public $columns = array(
  53. 'primary_key' => array('name' => 'serial NOT NULL'),
  54. 'string' => array('name' => 'varchar', 'limit' => '255'),
  55. 'text' => array('name' => 'text'),
  56. 'integer' => array('name' => 'integer', 'formatter' => 'intval'),
  57. 'biginteger' => array('name' => 'bigint', 'limit' => '20'),
  58. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  59. 'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
  60. 'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  61. 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  62. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  63. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  64. 'binary' => array('name' => 'bytea'),
  65. 'boolean' => array('name' => 'boolean'),
  66. 'number' => array('name' => 'numeric'),
  67. 'inet' => array('name' => 'inet')
  68. );
  69. /**
  70. * Starting Quote
  71. *
  72. * @var string
  73. */
  74. public $startQuote = '"';
  75. /**
  76. * Ending Quote
  77. *
  78. * @var string
  79. */
  80. public $endQuote = '"';
  81. /**
  82. * Contains mappings of custom auto-increment sequences, if a table uses a sequence name
  83. * other than what is dictated by convention.
  84. *
  85. * @var array
  86. */
  87. protected $_sequenceMap = array();
  88. /**
  89. * The set of valid SQL operations usable in a WHERE statement
  90. *
  91. * @var array
  92. */
  93. protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', '~', '~*', '!~', '!~*', 'similar to');
  94. /**
  95. * Connects to the database using options in the given configuration array.
  96. *
  97. * @return bool True if successfully connected.
  98. * @throws MissingConnectionException
  99. */
  100. public function connect() {
  101. $config = $this->config;
  102. $this->connected = false;
  103. $flags = $config['flags'] + array(
  104. PDO::ATTR_PERSISTENT => $config['persistent'],
  105. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  106. );
  107. try {
  108. $this->_connection = new PDO(
  109. "pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}",
  110. $config['login'],
  111. $config['password'],
  112. $flags
  113. );
  114. $this->connected = true;
  115. if (!empty($config['encoding'])) {
  116. $this->setEncoding($config['encoding']);
  117. }
  118. if (!empty($config['schema'])) {
  119. $this->_execute('SET search_path TO "' . $config['schema'] . '"');
  120. }
  121. if (!empty($config['settings'])) {
  122. foreach ($config['settings'] as $key => $value) {
  123. $this->_execute("SET $key TO $value");
  124. }
  125. }
  126. } catch (PDOException $e) {
  127. throw new MissingConnectionException(array(
  128. 'class' => get_class($this),
  129. 'message' => $e->getMessage()
  130. ));
  131. }
  132. return $this->connected;
  133. }
  134. /**
  135. * Check if PostgreSQL is enabled/loaded
  136. *
  137. * @return bool
  138. */
  139. public function enabled() {
  140. return in_array('pgsql', PDO::getAvailableDrivers());
  141. }
  142. /**
  143. * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
  144. *
  145. * @param mixed $data The sources to list.
  146. * @return array Array of table names in the database
  147. */
  148. public function listSources($data = null) {
  149. $cache = parent::listSources();
  150. if ($cache) {
  151. return $cache;
  152. }
  153. $schema = $this->config['schema'];
  154. $sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = ?";
  155. $result = $this->_execute($sql, array($schema));
  156. if (!$result) {
  157. return array();
  158. }
  159. $tables = array();
  160. foreach ($result as $item) {
  161. $tables[] = $item->name;
  162. }
  163. $result->closeCursor();
  164. parent::listSources($tables);
  165. return $tables;
  166. }
  167. /**
  168. * Returns an array of the fields in given table name.
  169. *
  170. * @param Model|string $model Name of database table to inspect
  171. * @return array Fields in table. Keys are name and type
  172. */
  173. public function describe($model) {
  174. $table = $this->fullTableName($model, false, false);
  175. $fields = parent::describe($table);
  176. $this->_sequenceMap[$table] = array();
  177. $cols = null;
  178. if ($fields === null) {
  179. $cols = $this->_execute(
  180. "SELECT DISTINCT table_schema AS schema, column_name AS name, data_type AS type, is_nullable AS null,
  181. column_default AS default, ordinal_position AS position, character_maximum_length AS char_length,
  182. character_octet_length AS oct_length FROM information_schema.columns
  183. WHERE table_name = ? AND table_schema = ? ORDER BY position",
  184. array($table, $this->config['schema'])
  185. );
  186. // @codingStandardsIgnoreStart
  187. // Postgres columns don't match the coding standards.
  188. foreach ($cols as $c) {
  189. $type = $c->type;
  190. if (!empty($c->oct_length) && $c->char_length === null) {
  191. if ($c->type === 'character varying') {
  192. $length = null;
  193. $type = 'text';
  194. } elseif ($c->type === 'uuid') {
  195. $length = 36;
  196. } else {
  197. $length = intval($c->oct_length);
  198. }
  199. } elseif (!empty($c->char_length)) {
  200. $length = intval($c->char_length);
  201. } else {
  202. $length = $this->length($c->type);
  203. }
  204. if (empty($length)) {
  205. $length = null;
  206. }
  207. $fields[$c->name] = array(
  208. 'type' => $this->column($type),
  209. 'null' => ($c->null === 'NO' ? false : true),
  210. 'default' => preg_replace(
  211. "/^'(.*)'$/",
  212. "$1",
  213. preg_replace('/::.*/', '', $c->default)
  214. ),
  215. 'length' => $length
  216. );
  217. if ($model instanceof Model) {
  218. if ($c->name === $model->primaryKey) {
  219. $fields[$c->name]['key'] = 'primary';
  220. if ($fields[$c->name]['type'] !== 'string') {
  221. $fields[$c->name]['length'] = 11;
  222. }
  223. }
  224. }
  225. if (
  226. $fields[$c->name]['default'] === 'NULL' ||
  227. preg_match('/nextval\([\'"]?([\w.]+)/', $c->default, $seq)
  228. ) {
  229. $fields[$c->name]['default'] = null;
  230. if (!empty($seq) && isset($seq[1])) {
  231. if (strpos($seq[1], '.') === false) {
  232. $sequenceName = $c->schema . '.' . $seq[1];
  233. } else {
  234. $sequenceName = $seq[1];
  235. }
  236. $this->_sequenceMap[$table][$c->name] = $sequenceName;
  237. }
  238. }
  239. if ($fields[$c->name]['type'] === 'timestamp' && $fields[$c->name]['default'] === '') {
  240. $fields[$c->name]['default'] = null;
  241. }
  242. if ($fields[$c->name]['type'] === 'boolean' && !empty($fields[$c->name]['default'])) {
  243. $fields[$c->name]['default'] = constant($fields[$c->name]['default']);
  244. }
  245. }
  246. $this->_cacheDescription($table, $fields);
  247. }
  248. // @codingStandardsIgnoreEnd
  249. if (isset($model->sequence)) {
  250. $this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;
  251. }
  252. if ($cols) {
  253. $cols->closeCursor();
  254. }
  255. return $fields;
  256. }
  257. /**
  258. * Returns the ID generated from the previous INSERT operation.
  259. *
  260. * @param string $source Name of the database table
  261. * @param string $field Name of the ID database field. Defaults to "id"
  262. * @return int
  263. */
  264. public function lastInsertId($source = null, $field = 'id') {
  265. $seq = $this->getSequence($source, $field);
  266. return $this->_connection->lastInsertId($seq);
  267. }
  268. /**
  269. * Gets the associated sequence for the given table/field
  270. *
  271. * @param string|Model $table Either a full table name (with prefix) as a string, or a model object
  272. * @param string $field Name of the ID database field. Defaults to "id"
  273. * @return string The associated sequence name from the sequence map, defaults to "{$table}_{$field}_seq"
  274. */
  275. public function getSequence($table, $field = 'id') {
  276. if (is_object($table)) {
  277. $table = $this->fullTableName($table, false, false);
  278. }
  279. if (!isset($this->_sequenceMap[$table])) {
  280. $this->describe($table);
  281. }
  282. if (isset($this->_sequenceMap[$table][$field])) {
  283. return $this->_sequenceMap[$table][$field];
  284. }
  285. return "{$table}_{$field}_seq";
  286. }
  287. /**
  288. * Reset a sequence based on the MAX() value of $column. Useful
  289. * for resetting sequences after using insertMulti().
  290. *
  291. * @param string $table The name of the table to update.
  292. * @param string $column The column to use when resetting the sequence value,
  293. * the sequence name will be fetched using Postgres::getSequence();
  294. * @return bool success.
  295. */
  296. public function resetSequence($table, $column) {
  297. $tableName = $this->fullTableName($table, false, false);
  298. $fullTable = $this->fullTableName($table);
  299. $sequence = $this->value($this->getSequence($tableName, $column));
  300. $column = $this->name($column);
  301. $this->execute("SELECT setval($sequence, (SELECT MAX($column) FROM $fullTable))");
  302. return true;
  303. }
  304. /**
  305. * Deletes all the records in a table and drops all associated auto-increment sequences
  306. *
  307. * @param string|Model $table A string or model class representing the table to be truncated
  308. * @param bool $reset true for resetting the sequence, false to leave it as is.
  309. * and if 1, sequences are not modified
  310. * @return bool SQL TRUNCATE TABLE statement, false if not applicable.
  311. */
  312. public function truncate($table, $reset = false) {
  313. $table = $this->fullTableName($table, false, false);
  314. if (!isset($this->_sequenceMap[$table])) {
  315. $cache = $this->cacheSources;
  316. $this->cacheSources = false;
  317. $this->describe($table);
  318. $this->cacheSources = $cache;
  319. }
  320. if ($this->execute('DELETE FROM ' . $this->fullTableName($table))) {
  321. if (isset($this->_sequenceMap[$table]) && $reset != true) {
  322. foreach ($this->_sequenceMap[$table] as $sequence) {
  323. list($schema, $sequence) = explode('.', $sequence);
  324. $this->_execute("ALTER SEQUENCE \"{$schema}\".\"{$sequence}\" RESTART WITH 1");
  325. }
  326. }
  327. return true;
  328. }
  329. return false;
  330. }
  331. /**
  332. * Prepares field names to be quoted by parent
  333. *
  334. * @param string $data The name to format.
  335. * @return string SQL field
  336. */
  337. public function name($data) {
  338. if (is_string($data)) {
  339. $data = str_replace('"__"', '__', $data);
  340. }
  341. return parent::name($data);
  342. }
  343. /**
  344. * Generates the fields list of an SQL query.
  345. *
  346. * @param Model $model The model to get fields for.
  347. * @param string $alias Alias table name.
  348. * @param mixed $fields The list of fields to get.
  349. * @param bool $quote Whether or not to quote identifiers.
  350. * @return array
  351. */
  352. public function fields(Model $model, $alias = null, $fields = array(), $quote = true) {
  353. if (empty($alias)) {
  354. $alias = $model->alias;
  355. }
  356. $fields = parent::fields($model, $alias, $fields, false);
  357. if (!$quote) {
  358. return $fields;
  359. }
  360. $count = count($fields);
  361. if ($count >= 1 && !preg_match('/^\s*COUNT\(\*/', $fields[0])) {
  362. $result = array();
  363. for ($i = 0; $i < $count; $i++) {
  364. if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
  365. if (substr($fields[$i], -1) === '*') {
  366. if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
  367. $build = explode('.', $fields[$i]);
  368. $AssociatedModel = $model->{$build[0]};
  369. } else {
  370. $AssociatedModel = $model;
  371. }
  372. $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
  373. $result = array_merge($result, $_fields);
  374. continue;
  375. }
  376. $prepend = '';
  377. if (strpos($fields[$i], 'DISTINCT') !== false) {
  378. $prepend = 'DISTINCT ';
  379. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  380. }
  381. if (strrpos($fields[$i], '.') === false) {
  382. $fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
  383. } else {
  384. $build = explode('.', $fields[$i]);
  385. $fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
  386. }
  387. } else {
  388. $fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]);
  389. }
  390. $result[] = $fields[$i];
  391. }
  392. return $result;
  393. }
  394. return $fields;
  395. }
  396. /**
  397. * Auxiliary function to quote matched `(Model.fields)` from a preg_replace_callback call
  398. * Quotes the fields in a function call.
  399. *
  400. * @param string $match matched string
  401. * @return string quoted string
  402. */
  403. protected function _quoteFunctionField($match) {
  404. $prepend = '';
  405. if (strpos($match[1], 'DISTINCT') !== false) {
  406. $prepend = 'DISTINCT ';
  407. $match[1] = trim(str_replace('DISTINCT', '', $match[1]));
  408. }
  409. $constant = preg_match('/^\d+|NULL|FALSE|TRUE$/i', $match[1]);
  410. if (!$constant && strpos($match[1], '.') === false) {
  411. $match[1] = $this->name($match[1]);
  412. } elseif (!$constant) {
  413. $parts = explode('.', $match[1]);
  414. if (!Hash::numeric($parts)) {
  415. $match[1] = $this->name($match[1]);
  416. }
  417. }
  418. return '(' . $prepend . $match[1] . ')';
  419. }
  420. /**
  421. * Returns an array of the indexes in given datasource name.
  422. *
  423. * @param string $model Name of model to inspect
  424. * @return array Fields in table. Keys are column and unique
  425. */
  426. public function index($model) {
  427. $index = array();
  428. $table = $this->fullTableName($model, false, false);
  429. if ($table) {
  430. $indexes = $this->query("SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) as statement, c2.reltablespace
  431. FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
  432. WHERE c.oid = (
  433. SELECT c.oid
  434. FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  435. WHERE c.relname ~ '^(" . $table . ")$'
  436. AND pg_catalog.pg_table_is_visible(c.oid)
  437. AND n.nspname ~ '^(" . $this->config['schema'] . ")$'
  438. )
  439. AND c.oid = i.indrelid AND i.indexrelid = c2.oid
  440. ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
  441. foreach ($indexes as $info) {
  442. $key = array_pop($info);
  443. if ($key['indisprimary']) {
  444. $key['relname'] = 'PRIMARY';
  445. }
  446. preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns);
  447. $parsedColumn = $indexColumns[1];
  448. if (strpos($indexColumns[1], ',') !== false) {
  449. $parsedColumn = explode(', ', $indexColumns[1]);
  450. }
  451. $index[$key['relname']]['unique'] = $key['indisunique'];
  452. $index[$key['relname']]['column'] = $parsedColumn;
  453. }
  454. }
  455. return $index;
  456. }
  457. /**
  458. * Alter the Schema of a table.
  459. *
  460. * @param array $compare Results of CakeSchema::compare()
  461. * @param string $table name of the table
  462. * @return array
  463. */
  464. public function alterSchema($compare, $table = null) {
  465. if (!is_array($compare)) {
  466. return false;
  467. }
  468. $out = '';
  469. $colList = array();
  470. foreach ($compare as $curTable => $types) {
  471. $indexes = $colList = array();
  472. if (!$table || $table === $curTable) {
  473. $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
  474. foreach ($types as $type => $column) {
  475. if (isset($column['indexes'])) {
  476. $indexes[$type] = $column['indexes'];
  477. unset($column['indexes']);
  478. }
  479. switch ($type) {
  480. case 'add':
  481. foreach ($column as $field => $col) {
  482. $col['name'] = $field;
  483. $colList[] = 'ADD COLUMN ' . $this->buildColumn($col);
  484. }
  485. break;
  486. case 'drop':
  487. foreach ($column as $field => $col) {
  488. $col['name'] = $field;
  489. $colList[] = 'DROP COLUMN ' . $this->name($field);
  490. }
  491. break;
  492. case 'change':
  493. $schema = $this->describe($curTable);
  494. foreach ($column as $field => $col) {
  495. if (!isset($col['name'])) {
  496. $col['name'] = $field;
  497. }
  498. $original = $schema[$field];
  499. $fieldName = $this->name($field);
  500. $default = isset($col['default']) ? $col['default'] : null;
  501. $nullable = isset($col['null']) ? $col['null'] : null;
  502. $boolToInt = $original['type'] === 'boolean' && $col['type'] === 'integer';
  503. unset($col['default'], $col['null']);
  504. if ($field !== $col['name']) {
  505. $newName = $this->name($col['name']);
  506. $out .= "\tRENAME {$fieldName} TO {$newName};\n";
  507. $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
  508. $fieldName = $newName;
  509. }
  510. if ($boolToInt) {
  511. $colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT NULL';
  512. $colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)) . ' USING CASE WHEN TRUE THEN 1 ELSE 0 END';
  513. } else {
  514. $colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
  515. }
  516. if (isset($nullable)) {
  517. $nullable = ($nullable) ? 'DROP NOT NULL' : 'SET NOT NULL';
  518. $colList[] = 'ALTER COLUMN ' . $fieldName . ' ' . $nullable;
  519. }
  520. if (isset($default)) {
  521. if (!$boolToInt) {
  522. $colList[] = 'ALTER COLUMN ' . $fieldName . ' SET DEFAULT ' . $this->value($default, $col['type']);
  523. }
  524. } else {
  525. $colList[] = 'ALTER COLUMN ' . $fieldName . ' DROP DEFAULT';
  526. }
  527. }
  528. break;
  529. }
  530. }
  531. if (isset($indexes['drop']['PRIMARY'])) {
  532. $colList[] = 'DROP CONSTRAINT ' . $curTable . '_pkey';
  533. }
  534. if (isset($indexes['add']['PRIMARY'])) {
  535. $cols = $indexes['add']['PRIMARY']['column'];
  536. if (is_array($cols)) {
  537. $cols = implode(', ', $cols);
  538. }
  539. $colList[] = 'ADD PRIMARY KEY (' . $cols . ')';
  540. }
  541. if (!empty($colList)) {
  542. $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
  543. } else {
  544. $out = '';
  545. }
  546. $out .= implode(";\n\t", $this->_alterIndexes($curTable, $indexes));
  547. }
  548. }
  549. return $out;
  550. }
  551. /**
  552. * Generate PostgreSQL index alteration statements for a table.
  553. *
  554. * @param string $table Table to alter indexes for
  555. * @param array $indexes Indexes to add and drop
  556. * @return array Index alteration statements
  557. */
  558. protected function _alterIndexes($table, $indexes) {
  559. $alter = array();
  560. if (isset($indexes['drop'])) {
  561. foreach ($indexes['drop'] as $name => $value) {
  562. $out = 'DROP ';
  563. if ($name === 'PRIMARY') {
  564. continue;
  565. } else {
  566. $out .= 'INDEX ' . $name;
  567. }
  568. $alter[] = $out;
  569. }
  570. }
  571. if (isset($indexes['add'])) {
  572. foreach ($indexes['add'] as $name => $value) {
  573. $out = 'CREATE ';
  574. if ($name === 'PRIMARY') {
  575. continue;
  576. } else {
  577. if (!empty($value['unique'])) {
  578. $out .= 'UNIQUE ';
  579. }
  580. $out .= 'INDEX ';
  581. }
  582. if (is_array($value['column'])) {
  583. $out .= $name . ' ON ' . $table . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  584. } else {
  585. $out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')';
  586. }
  587. $alter[] = $out;
  588. }
  589. }
  590. return $alter;
  591. }
  592. /**
  593. * Returns a limit statement in the correct format for the particular database.
  594. *
  595. * @param int $limit Limit of results returned
  596. * @param int $offset Offset from which to start results
  597. * @return string SQL limit/offset statement
  598. */
  599. public function limit($limit, $offset = null) {
  600. if ($limit) {
  601. $rt = sprintf(' LIMIT %u', $limit);
  602. if ($offset) {
  603. $rt .= sprintf(' OFFSET %u', $offset);
  604. }
  605. return $rt;
  606. }
  607. return null;
  608. }
  609. /**
  610. * Converts database-layer column types to basic types
  611. *
  612. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  613. * @return string Abstract column type (i.e. "string")
  614. */
  615. public function column($real) {
  616. if (is_array($real)) {
  617. $col = $real['name'];
  618. if (isset($real['limit'])) {
  619. $col .= '(' . $real['limit'] . ')';
  620. }
  621. return $col;
  622. }
  623. $col = str_replace(')', '', $real);
  624. if (strpos($col, '(') !== false) {
  625. list($col, $limit) = explode('(', $col);
  626. }
  627. $floats = array(
  628. 'float', 'float4', 'float8', 'double', 'double precision', 'real'
  629. );
  630. switch (true) {
  631. case (in_array($col, array('date', 'time', 'inet', 'boolean'))):
  632. return $col;
  633. case (strpos($col, 'timestamp') !== false):
  634. return 'datetime';
  635. case (strpos($col, 'time') === 0):
  636. return 'time';
  637. case ($col === 'bigint'):
  638. return 'biginteger';
  639. case (strpos($col, 'int') !== false && $col !== 'interval'):
  640. return 'integer';
  641. case (strpos($col, 'char') !== false || $col === 'uuid'):
  642. return 'string';
  643. case (strpos($col, 'text') !== false):
  644. return 'text';
  645. case (strpos($col, 'bytea') !== false):
  646. return 'binary';
  647. case ($col === 'decimal' || $col === 'numeric'):
  648. return 'decimal';
  649. case (in_array($col, $floats)):
  650. return 'float';
  651. default:
  652. return 'text';
  653. }
  654. }
  655. /**
  656. * Gets the length of a database-native column description, or null if no length
  657. *
  658. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  659. * @return int An integer representing the length of the column
  660. */
  661. public function length($real) {
  662. $col = str_replace(array(')', 'unsigned'), '', $real);
  663. $limit = null;
  664. if (strpos($col, '(') !== false) {
  665. list($col, $limit) = explode('(', $col);
  666. }
  667. if ($col === 'uuid') {
  668. return 36;
  669. }
  670. if ($limit) {
  671. return intval($limit);
  672. }
  673. return null;
  674. }
  675. /**
  676. * resultSet method
  677. *
  678. * @param array &$results The results
  679. * @return void
  680. */
  681. public function resultSet(&$results) {
  682. $this->map = array();
  683. $numFields = $results->columnCount();
  684. $index = 0;
  685. $j = 0;
  686. while ($j < $numFields) {
  687. $column = $results->getColumnMeta($j);
  688. if (strpos($column['name'], '__')) {
  689. list($table, $name) = explode('__', $column['name']);
  690. $this->map[$index++] = array($table, $name, $column['native_type']);
  691. } else {
  692. $this->map[$index++] = array(0, $column['name'], $column['native_type']);
  693. }
  694. $j++;
  695. }
  696. }
  697. /**
  698. * Fetches the next row from the current result set
  699. *
  700. * @return array
  701. */
  702. public function fetchResult() {
  703. if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
  704. $resultRow = array();
  705. foreach ($this->map as $index => $meta) {
  706. list($table, $column, $type) = $meta;
  707. switch ($type) {
  708. case 'bool':
  709. $resultRow[$table][$column] = $row[$index] === null ? null : $this->boolean($row[$index]);
  710. break;
  711. case 'binary':
  712. case 'bytea':
  713. $resultRow[$table][$column] = $row[$index] === null ? null : stream_get_contents($row[$index]);
  714. break;
  715. default:
  716. $resultRow[$table][$column] = $row[$index];
  717. }
  718. }
  719. return $resultRow;
  720. }
  721. $this->_result->closeCursor();
  722. return false;
  723. }
  724. /**
  725. * Translates between PHP boolean values and PostgreSQL boolean values
  726. *
  727. * @param mixed $data Value to be translated
  728. * @param bool $quote true to quote a boolean to be used in a query, false to return the boolean value
  729. * @return bool Converted boolean value
  730. */
  731. public function boolean($data, $quote = false) {
  732. switch (true) {
  733. case ($data === true || $data === false):
  734. $result = $data;
  735. break;
  736. case ($data === 't' || $data === 'f'):
  737. $result = ($data === 't');
  738. break;
  739. case ($data === 'true' || $data === 'false'):
  740. $result = ($data === 'true');
  741. break;
  742. case ($data === 'TRUE' || $data === 'FALSE'):
  743. $result = ($data === 'TRUE');
  744. break;
  745. default:
  746. $result = (bool)$data;
  747. }
  748. if ($quote) {
  749. return ($result) ? 'TRUE' : 'FALSE';
  750. }
  751. return (bool)$result;
  752. }
  753. /**
  754. * Sets the database encoding
  755. *
  756. * @param mixed $enc Database encoding
  757. * @return bool True on success, false on failure
  758. */
  759. public function setEncoding($enc) {
  760. return $this->_execute('SET NAMES ' . $this->value($enc)) !== false;
  761. }
  762. /**
  763. * Gets the database encoding
  764. *
  765. * @return string The database encoding
  766. */
  767. public function getEncoding() {
  768. $result = $this->_execute('SHOW client_encoding')->fetch();
  769. if ($result === false) {
  770. return false;
  771. }
  772. return (isset($result['client_encoding'])) ? $result['client_encoding'] : false;
  773. }
  774. /**
  775. * Generate a Postgres-native column schema string
  776. *
  777. * @param array $column An array structured like the following:
  778. * array('name'=>'value', 'type'=>'value'[, options]),
  779. * where options can be 'default', 'length', or 'key'.
  780. * @return string
  781. */
  782. public function buildColumn($column) {
  783. $col = $this->columns[$column['type']];
  784. if (!isset($col['length']) && !isset($col['limit'])) {
  785. unset($column['length']);
  786. }
  787. $out = parent::buildColumn($column);
  788. $out = preg_replace(
  789. '/integer\([0-9]+\)/',
  790. 'integer',
  791. $out
  792. );
  793. $out = preg_replace(
  794. '/bigint\([0-9]+\)/',
  795. 'bigint',
  796. $out
  797. );
  798. $out = str_replace('integer serial', 'serial', $out);
  799. $out = str_replace('bigint serial', 'bigserial', $out);
  800. if (strpos($out, 'timestamp DEFAULT')) {
  801. if (isset($column['null']) && $column['null']) {
  802. $out = str_replace('DEFAULT NULL', '', $out);
  803. } else {
  804. $out = str_replace('DEFAULT NOT NULL', '', $out);
  805. }
  806. }
  807. if (strpos($out, 'DEFAULT DEFAULT')) {
  808. if (isset($column['null']) && $column['null']) {
  809. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
  810. } elseif (in_array($column['type'], array('integer', 'float'))) {
  811. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
  812. } elseif ($column['type'] === 'boolean') {
  813. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
  814. }
  815. }
  816. return $out;
  817. }
  818. /**
  819. * Format indexes for create table
  820. *
  821. * @param array $indexes The index to build
  822. * @param string $table The table name.
  823. * @return string
  824. */
  825. public function buildIndex($indexes, $table = null) {
  826. $join = array();
  827. if (!is_array($indexes)) {
  828. return array();
  829. }
  830. foreach ($indexes as $name => $value) {
  831. if ($name === 'PRIMARY') {
  832. $out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
  833. } else {
  834. $out = 'CREATE ';
  835. if (!empty($value['unique'])) {
  836. $out .= 'UNIQUE ';
  837. }
  838. if (is_array($value['column'])) {
  839. $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
  840. } else {
  841. $value['column'] = $this->name($value['column']);
  842. }
  843. $out .= "INDEX {$name} ON {$table}({$value['column']});";
  844. }
  845. $join[] = $out;
  846. }
  847. return $join;
  848. }
  849. /**
  850. * Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
  851. *
  852. * @param string $type The query type.
  853. * @param array $data The array of data to render.
  854. * @return string
  855. */
  856. public function renderStatement($type, $data) {
  857. switch (strtolower($type)) {
  858. case 'schema':
  859. extract($data);
  860. foreach ($indexes as $i => $index) {
  861. if (preg_match('/PRIMARY KEY/', $index)) {
  862. unset($indexes[$i]);
  863. $columns[] = $index;
  864. break;
  865. }
  866. }
  867. $join = array('columns' => ",\n\t", 'indexes' => "\n");
  868. foreach (array('columns', 'indexes') as $var) {
  869. if (is_array(${$var})) {
  870. ${$var} = implode($join[$var], array_filter(${$var}));
  871. }
  872. }
  873. return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
  874. default:
  875. return parent::renderStatement($type, $data);
  876. }
  877. }
  878. /**
  879. * Gets the schema name
  880. *
  881. * @return string The schema name
  882. */
  883. public function getSchemaName() {
  884. return $this->config['schema'];
  885. }
  886. /**
  887. * Check if the server support nested transactions
  888. *
  889. * @return bool
  890. */
  891. public function nestedTransactionSupported() {
  892. return $this->useNestedTransactions && version_compare($this->getVersion(), '8.0', '>=');
  893. }
  894. }