Postgres.php 24 KB

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