Postgres.php 25 KB

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