Postgres.php 26 KB

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