Postgres.php 27 KB

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