Postgres.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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. * @access public
  33. */
  34. public $description = "PostgreSQL DBO Driver";
  35. /**
  36. * Index of basic SQL commands
  37. *
  38. * @var array
  39. * @access protected
  40. */
  41. protected $_commands = array(
  42. 'begin' => 'BEGIN',
  43. 'commit' => 'COMMIT',
  44. 'rollback' => 'ROLLBACK'
  45. );
  46. /**
  47. * Base driver configuration settings. Merged with user settings.
  48. *
  49. * @var array
  50. * @access protected
  51. */
  52. protected $_baseConfig = array(
  53. 'persistent' => true,
  54. 'host' => 'localhost',
  55. 'login' => 'root',
  56. 'password' => '',
  57. 'database' => 'cake',
  58. 'schema' => 'public',
  59. 'port' => 5432,
  60. 'encoding' => ''
  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. * @access public
  82. */
  83. public $startQuote = '"';
  84. /**
  85. * Ending Quote
  86. *
  87. * @var string
  88. * @access public
  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 True if successfully connected.
  102. */
  103. public function connect() {
  104. $config = $this->config;
  105. $this->connected = false;
  106. try {
  107. $flags = array(
  108. PDO::ATTR_PERSISTENT => $config['persistent']
  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 tablenames 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 $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, $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 resseting 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 = true) {
  276. $table = $this->fullTableName($table, false);
  277. if (!isset($this->_sequenceMap[$table])) {
  278. $cache = $this->cacheSources;
  279. $this->cacheSources = false;
  280. $this->describe($table);
  281. $this->cacheSources = $cache;
  282. }
  283. if (parent::truncate($table)) {
  284. if (isset($this->_sequenceMap[$table]) && $reset) {
  285. foreach ($this->_sequenceMap[$table] 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 tablename
  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. *
  361. * @param string $match matched string
  362. * @return string quoted strig
  363. */
  364. private function __quoteFunctionField($match) {
  365. $prepend = '';
  366. if (strpos($match[1], 'DISTINCT') !== false) {
  367. $prepend = 'DISTINCT ';
  368. $match[1] = trim(str_replace('DISTINCT', '', $match[1]));
  369. }
  370. if (strpos($match[1], '.') === false) {
  371. $match[1] = $this->name($match[1]);
  372. } else {
  373. $parts = explode('.', $match[1]);
  374. if (!Set::numeric($parts)) {
  375. $match[1] = $this->name($match[1]);
  376. }
  377. }
  378. return '(' . $prepend .$match[1] . ')';
  379. }
  380. /**
  381. * Returns an array of the indexes in given datasource name.
  382. *
  383. * @param string $model Name of model to inspect
  384. * @return array Fields in table. Keys are column and unique
  385. */
  386. public function index($model) {
  387. $index = array();
  388. $table = $this->fullTableName($model, false);
  389. if ($table) {
  390. $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
  391. FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
  392. WHERE c.oid = (
  393. SELECT c.oid
  394. FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  395. WHERE c.relname ~ '^(" . $table . ")$'
  396. AND pg_catalog.pg_table_is_visible(c.oid)
  397. AND n.nspname ~ '^(" . $this->config['schema'] . ")$'
  398. )
  399. AND c.oid = i.indrelid AND i.indexrelid = c2.oid
  400. ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
  401. foreach ($indexes as $i => $info) {
  402. $key = array_pop($info);
  403. if ($key['indisprimary']) {
  404. $key['relname'] = 'PRIMARY';
  405. }
  406. $col = array();
  407. preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns);
  408. $parsedColumn = $indexColumns[1];
  409. if (strpos($indexColumns[1], ',') !== false) {
  410. $parsedColumn = explode(', ', $indexColumns[1]);
  411. }
  412. $index[$key['relname']]['unique'] = $key['indisunique'];
  413. $index[$key['relname']]['column'] = $parsedColumn;
  414. }
  415. }
  416. return $index;
  417. }
  418. /**
  419. * Alter the Schema of a table.
  420. *
  421. * @param array $compare Results of CakeSchema::compare()
  422. * @param string $table name of the table
  423. * @access public
  424. * @return array
  425. */
  426. public function alterSchema($compare, $table = null) {
  427. if (!is_array($compare)) {
  428. return false;
  429. }
  430. $out = '';
  431. $colList = array();
  432. foreach ($compare as $curTable => $types) {
  433. $indexes = $colList = array();
  434. if (!$table || $table == $curTable) {
  435. $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
  436. foreach ($types as $type => $column) {
  437. if (isset($column['indexes'])) {
  438. $indexes[$type] = $column['indexes'];
  439. unset($column['indexes']);
  440. }
  441. switch ($type) {
  442. case 'add':
  443. foreach ($column as $field => $col) {
  444. $col['name'] = $field;
  445. $alter = 'ADD COLUMN '.$this->buildColumn($col);
  446. if (isset($col['after'])) {
  447. $alter .= ' AFTER '. $this->name($col['after']);
  448. }
  449. $colList[] = $alter;
  450. }
  451. break;
  452. case 'drop':
  453. foreach ($column as $field => $col) {
  454. $col['name'] = $field;
  455. $colList[] = 'DROP COLUMN '.$this->name($field);
  456. }
  457. break;
  458. case 'change':
  459. foreach ($column as $field => $col) {
  460. if (!isset($col['name'])) {
  461. $col['name'] = $field;
  462. }
  463. $fieldName = $this->name($field);
  464. $default = isset($col['default']) ? $col['default'] : null;
  465. $nullable = isset($col['null']) ? $col['null'] : null;
  466. unset($col['default'], $col['null']);
  467. $colList[] = 'ALTER COLUMN '. $fieldName .' TYPE ' . str_replace($fieldName, '', $this->buildColumn($col));
  468. if (isset($nullable)) {
  469. $nullable = ($nullable) ? 'DROP NOT NULL' : 'SET NOT NULL';
  470. $colList[] = 'ALTER COLUMN '. $fieldName .' ' . $nullable;
  471. }
  472. if (isset($default)) {
  473. $colList[] = 'ALTER COLUMN '. $fieldName .' SET DEFAULT ' . $this->value($default, $col['type']);
  474. } else {
  475. $colList[] = 'ALTER COLUMN '. $fieldName .' DROP DEFAULT';
  476. }
  477. }
  478. break;
  479. }
  480. }
  481. if (isset($indexes['drop']['PRIMARY'])) {
  482. $colList[] = 'DROP CONSTRAINT ' . $curTable . '_pkey';
  483. }
  484. if (isset($indexes['add']['PRIMARY'])) {
  485. $cols = $indexes['add']['PRIMARY']['column'];
  486. if (is_array($cols)) {
  487. $cols = implode(', ', $cols);
  488. }
  489. $colList[] = 'ADD PRIMARY KEY (' . $cols . ')';
  490. }
  491. if (!empty($colList)) {
  492. $out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
  493. } else {
  494. $out = '';
  495. }
  496. $out .= implode(";\n\t", $this->_alterIndexes($curTable, $indexes));
  497. }
  498. }
  499. return $out;
  500. }
  501. /**
  502. * Generate PostgreSQL index alteration statements for a table.
  503. *
  504. * @param string $table Table to alter indexes for
  505. * @param array $indexes Indexes to add and drop
  506. * @return array Index alteration statements
  507. */
  508. protected function _alterIndexes($table, $indexes) {
  509. $alter = array();
  510. if (isset($indexes['drop'])) {
  511. foreach($indexes['drop'] as $name => $value) {
  512. $out = 'DROP ';
  513. if ($name == 'PRIMARY') {
  514. continue;
  515. } else {
  516. $out .= 'INDEX ' . $name;
  517. }
  518. $alter[] = $out;
  519. }
  520. }
  521. if (isset($indexes['add'])) {
  522. foreach ($indexes['add'] as $name => $value) {
  523. $out = 'CREATE ';
  524. if ($name == 'PRIMARY') {
  525. continue;
  526. } else {
  527. if (!empty($value['unique'])) {
  528. $out .= 'UNIQUE ';
  529. }
  530. $out .= 'INDEX ';
  531. }
  532. if (is_array($value['column'])) {
  533. $out .= $name . ' ON ' . $table . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
  534. } else {
  535. $out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')';
  536. }
  537. $alter[] = $out;
  538. }
  539. }
  540. return $alter;
  541. }
  542. /**
  543. * Returns a limit statement in the correct format for the particular database.
  544. *
  545. * @param integer $limit Limit of results returned
  546. * @param integer $offset Offset from which to start results
  547. * @return string SQL limit/offset statement
  548. */
  549. public function limit($limit, $offset = null) {
  550. if ($limit) {
  551. $rt = '';
  552. if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
  553. $rt = ' LIMIT';
  554. }
  555. $rt .= ' ' . $limit;
  556. if ($offset) {
  557. $rt .= ' OFFSET ' . $offset;
  558. }
  559. return $rt;
  560. }
  561. return null;
  562. }
  563. /**
  564. * Converts database-layer column types to basic types
  565. *
  566. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  567. * @return string Abstract column type (i.e. "string")
  568. */
  569. public function column($real) {
  570. if (is_array($real)) {
  571. $col = $real['name'];
  572. if (isset($real['limit'])) {
  573. $col .= '(' . $real['limit'] . ')';
  574. }
  575. return $col;
  576. }
  577. $col = str_replace(')', '', $real);
  578. $limit = null;
  579. if (strpos($col, '(') !== false) {
  580. list($col, $limit) = explode('(', $col);
  581. }
  582. $floats = array(
  583. 'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'real', 'numeric'
  584. );
  585. switch (true) {
  586. case (in_array($col, array('date', 'time', 'inet', 'boolean'))):
  587. return $col;
  588. case (strpos($col, 'timestamp') !== false):
  589. return 'datetime';
  590. case (strpos($col, 'time') === 0):
  591. return 'time';
  592. case (strpos($col, 'int') !== false && $col != 'interval'):
  593. return 'integer';
  594. case (strpos($col, 'char') !== false || $col == 'uuid'):
  595. return 'string';
  596. case (strpos($col, 'text') !== false):
  597. return 'text';
  598. case (strpos($col, 'bytea') !== false):
  599. return 'binary';
  600. case (in_array($col, $floats)):
  601. return 'float';
  602. default:
  603. return 'text';
  604. break;
  605. }
  606. }
  607. /**
  608. * Gets the length of a database-native column description, or null if no length
  609. *
  610. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  611. * @return int An integer representing the length of the column
  612. */
  613. public function length($real) {
  614. $col = str_replace(array(')', 'unsigned'), '', $real);
  615. $limit = null;
  616. if (strpos($col, '(') !== false) {
  617. list($col, $limit) = explode('(', $col);
  618. }
  619. if ($col == 'uuid') {
  620. return 36;
  621. }
  622. if ($limit != null) {
  623. return intval($limit);
  624. }
  625. return null;
  626. }
  627. /**
  628. * Enter description here...
  629. *
  630. * @param array $results
  631. * @return void
  632. */
  633. public function resultSet(&$results) {
  634. $this->map = array();
  635. $numFields = $results->columnCount();
  636. $index = 0;
  637. $j = 0;
  638. while ($j < $numFields) {
  639. $column = $results->getColumnMeta($j);
  640. if (strpos($column['name'], '__')) {
  641. list($table, $name) = explode('__', $column['name']);
  642. $this->map[$index++] = array($table, $name, $column['native_type']);
  643. } else {
  644. $this->map[$index++] = array(0, $column['name'], $column['native_type']);
  645. }
  646. $j++;
  647. }
  648. }
  649. /**
  650. * Fetches the next row from the current result set
  651. *
  652. * @return unknown
  653. */
  654. public function fetchResult() {
  655. if ($row = $this->_result->fetch()) {
  656. $resultRow = array();
  657. foreach ($this->map as $index => $meta) {
  658. list($table, $column, $type) = $meta;
  659. switch ($type) {
  660. case 'bool':
  661. $resultRow[$table][$column] = is_null($row[$index]) ? null : $this->boolean($row[$index]);
  662. break;
  663. case 'binary':
  664. case 'bytea':
  665. $resultRow[$table][$column] = stream_get_contents($row[$index]);
  666. break;
  667. default:
  668. $resultRow[$table][$column] = $row[$index];
  669. break;
  670. }
  671. }
  672. return $resultRow;
  673. } else {
  674. $this->_result->closeCursor();
  675. return false;
  676. }
  677. }
  678. /**
  679. * Translates between PHP boolean values and PostgreSQL boolean values
  680. *
  681. * @param mixed $data Value to be translated
  682. * @param boolean $quote true to quote a boolean to be used in a query, flase to return the boolean value
  683. * @return boolean Converted boolean value
  684. */
  685. public function boolean($data, $quote = false) {
  686. switch (true) {
  687. case ($data === true || $data === false):
  688. $result = $data;
  689. break;
  690. case ($data === 't' || $data === 'f'):
  691. $result = ($data === 't');
  692. break;
  693. case ($data === 'true' || $data === 'false'):
  694. $result = ($data === 'true');
  695. break;
  696. case ($data === 'TRUE' || $data === 'FALSE'):
  697. $result = ($data === 'TRUE');
  698. break;
  699. default:
  700. $result = (bool) $data;
  701. break;
  702. }
  703. if ($quote) {
  704. return ($result) ? 'TRUE' : 'FALSE';
  705. }
  706. return (bool) $result;
  707. }
  708. /**
  709. * Sets the database encoding
  710. *
  711. * @param mixed $enc Database encoding
  712. * @return boolean True on success, false on failure
  713. */
  714. public function setEncoding($enc) {
  715. if ($this->_execute('SET NAMES ?', array($enc))) {
  716. return true;
  717. }
  718. return false;
  719. }
  720. /**
  721. * Gets the database encoding
  722. *
  723. * @return string The database encoding
  724. */
  725. public function getEncoding() {
  726. $cosa = $this->_execute('SHOW client_encoding')->fetch();
  727. }
  728. /**
  729. * Generate a Postgres-native column schema string
  730. *
  731. * @param array $column An array structured like the following:
  732. * array('name'=>'value', 'type'=>'value'[, options]),
  733. * where options can be 'default', 'length', or 'key'.
  734. * @return string
  735. */
  736. public function buildColumn($column) {
  737. $col = $this->columns[$column['type']];
  738. if (!isset($col['length']) && !isset($col['limit'])) {
  739. unset($column['length']);
  740. }
  741. $out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column));
  742. $out = str_replace('integer serial', 'serial', $out);
  743. if (strpos($out, 'timestamp DEFAULT')) {
  744. if (isset($column['null']) && $column['null']) {
  745. $out = str_replace('DEFAULT NULL', '', $out);
  746. } else {
  747. $out = str_replace('DEFAULT NOT NULL', '', $out);
  748. }
  749. }
  750. if (strpos($out, 'DEFAULT DEFAULT')) {
  751. if (isset($column['null']) && $column['null']) {
  752. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
  753. } elseif (in_array($column['type'], array('integer', 'float'))) {
  754. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
  755. } elseif ($column['type'] == 'boolean') {
  756. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
  757. }
  758. }
  759. return $out;
  760. }
  761. /**
  762. * Format indexes for create table
  763. *
  764. * @param array $indexes
  765. * @param string $table
  766. * @return string
  767. */
  768. public function buildIndex($indexes, $table = null) {
  769. $join = array();
  770. if (!is_array($indexes)) {
  771. return array();
  772. }
  773. foreach ($indexes as $name => $value) {
  774. if ($name == 'PRIMARY') {
  775. $out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
  776. } else {
  777. $out = 'CREATE ';
  778. if (!empty($value['unique'])) {
  779. $out .= 'UNIQUE ';
  780. }
  781. if (is_array($value['column'])) {
  782. $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
  783. } else {
  784. $value['column'] = $this->name($value['column']);
  785. }
  786. $out .= "INDEX {$name} ON {$table}({$value['column']});";
  787. }
  788. $join[] = $out;
  789. }
  790. return $join;
  791. }
  792. /**
  793. * Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
  794. *
  795. * @param string $type
  796. * @param array $data
  797. * @return string
  798. */
  799. public function renderStatement($type, $data) {
  800. switch (strtolower($type)) {
  801. case 'schema':
  802. extract($data);
  803. foreach ($indexes as $i => $index) {
  804. if (preg_match('/PRIMARY KEY/', $index)) {
  805. unset($indexes[$i]);
  806. $columns[] = $index;
  807. break;
  808. }
  809. }
  810. $join = array('columns' => ",\n\t", 'indexes' => "\n");
  811. foreach (array('columns', 'indexes') as $var) {
  812. if (is_array(${$var})) {
  813. ${$var} = implode($join[$var], array_filter(${$var}));
  814. }
  815. }
  816. return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
  817. break;
  818. default:
  819. return parent::renderStatement($type, $data);
  820. break;
  821. }
  822. }
  823. }