Postgres.php 26 KB

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