Postgres.php 26 KB

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