Postgres.php 26 KB

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