Postgres.php 24 KB

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