Postgres.php 24 KB

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