Postgres.php 24 KB

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