Postgres.php 27 KB

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