Postgres.php 25 KB

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