PageRenderTime 69ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Model/Datasource/Database/Postgres.php

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