Postgres.php 27 KB

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