Postgres.php 26 KB

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