Postgres.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. }
  224. $this->__cacheDescription($table, $fields);
  225. }
  226. if (isset($model->sequence)) {
  227. $this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;
  228. }
  229. if ($cols) {
  230. $cols->closeCursor();
  231. }
  232. return $fields;
  233. }
  234. /**
  235. * Returns the ID generated from the previous INSERT operation.
  236. *
  237. * @param string $source Name of the database table
  238. * @param string $field Name of the ID database field. Defaults to "id"
  239. * @return integer
  240. */
  241. function lastInsertId($source, $field = 'id') {
  242. $seq = $this->getSequence($source, $field);
  243. return $this->_connection->lastInsertId($seq);
  244. }
  245. /**
  246. * Gets the associated sequence for the given table/field
  247. *
  248. * @param mixed $table Either a full table name (with prefix) as a string, or a model object
  249. * @param string $field Name of the ID database field. Defaults to "id"
  250. * @return string The associated sequence name from the sequence map, defaults to "{$table}_{$field}_seq"
  251. */
  252. function getSequence($table, $field = 'id') {
  253. if (is_object($table)) {
  254. $table = $this->fullTableName($table, false);
  255. }
  256. if (isset($this->_sequenceMap[$table]) && isset($this->_sequenceMap[$table][$field])) {
  257. return $this->_sequenceMap[$table][$field];
  258. } else {
  259. return "{$table}_{$field}_seq";
  260. }
  261. }
  262. /**
  263. * Deletes all the records in a table and drops all associated auto-increment sequences
  264. *
  265. * @param mixed $table A string or model class representing the table to be truncated
  266. * @param boolean $reset true for resseting the sequence, false to leave it as is.
  267. * and if 1, sequences are not modified
  268. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  269. */
  270. public function truncate($table, $reset = true) {
  271. $table = $this->fullTableName($table, false);
  272. if (!isset($this->_sequenceMap[$table])) {
  273. $cache = $this->cacheSources;
  274. $this->cacheSources = false;
  275. $this->describe($table);
  276. $this->cacheSources = $cache;
  277. }
  278. if (parent::truncate($table)) {
  279. if (isset($this->_sequenceMap[$table]) && $reset) {
  280. foreach ($this->_sequenceMap[$table] as $field => $sequence) {
  281. $this->_execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1");
  282. }
  283. }
  284. return true;
  285. }
  286. return false;
  287. }
  288. /**
  289. * Prepares field names to be quoted by parent
  290. *
  291. * @param string $data
  292. * @return string SQL field
  293. */
  294. function name($data) {
  295. if (is_string($data)) {
  296. $data = str_replace('"__"', '__', $data);
  297. }
  298. return parent::name($data);
  299. }
  300. /**
  301. * Generates the fields list of an SQL query.
  302. *
  303. * @param Model $model
  304. * @param string $alias Alias tablename
  305. * @param mixed $fields
  306. * @return array
  307. */
  308. function fields($model, $alias = null, $fields = array(), $quote = true) {
  309. if (empty($alias)) {
  310. $alias = $model->alias;
  311. }
  312. $fields = parent::fields($model, $alias, $fields, false);
  313. if (!$quote) {
  314. return $fields;
  315. }
  316. $count = count($fields);
  317. if ($count >= 1 && !preg_match('/^\s*COUNT\(\*/', $fields[0])) {
  318. $result = array();
  319. for ($i = 0; $i < $count; $i++) {
  320. if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
  321. if (substr($fields[$i], -1) == '*') {
  322. if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
  323. $build = explode('.', $fields[$i]);
  324. $AssociatedModel = $model->{$build[0]};
  325. } else {
  326. $AssociatedModel = $model;
  327. }
  328. $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
  329. $result = array_merge($result, $_fields);
  330. continue;
  331. }
  332. $prepend = '';
  333. if (strpos($fields[$i], 'DISTINCT') !== false) {
  334. $prepend = 'DISTINCT ';
  335. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  336. }
  337. if (strrpos($fields[$i], '.') === false) {
  338. $fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
  339. } else {
  340. $build = explode('.', $fields[$i]);
  341. $fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
  342. }
  343. } else {
  344. $fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '__quoteFunctionField'), $fields[$i]);
  345. }
  346. $result[] = $fields[$i];
  347. }
  348. return $result;
  349. }
  350. return $fields;
  351. }
  352. /**
  353. * Auxiliary function to quote matched `(Model.fields)` from a preg_replace_callback call
  354. *
  355. * @param string matched string
  356. * @return string quoted strig
  357. * @access private
  358. */
  359. function __quoteFunctionField($match) {
  360. $prepend = '';
  361. if (strpos($match[1], 'DISTINCT') !== false) {
  362. $prepend = 'DISTINCT ';
  363. $match[1] = trim(str_replace('DISTINCT', '', $match[1]));
  364. }
  365. if (strpos($match[1], '.') === false) {
  366. $match[1] = $this->name($match[1]);
  367. } else {
  368. $parts = explode('.', $match[1]);
  369. if (!Set::numeric($parts)) {
  370. $match[1] = $this->name($match[1]);
  371. }
  372. }
  373. return '(' . $prepend .$match[1] . ')';
  374. }
  375. /**
  376. * Returns an array of the indexes in given datasource name.
  377. *
  378. * @param string $model Name of model to inspect
  379. * @return array Fields in table. Keys are column and unique
  380. */
  381. function index($model) {
  382. $index = array();
  383. $table = $this->fullTableName($model, false);
  384. if ($table) {
  385. $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
  386. FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
  387. WHERE c.oid = (
  388. SELECT c.oid
  389. FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  390. WHERE c.relname ~ '^(" . $table . ")$'
  391. AND pg_catalog.pg_table_is_visible(c.oid)
  392. AND n.nspname ~ '^(" . $this->config['schema'] . ")$'
  393. )
  394. AND c.oid = i.indrelid AND i.indexrelid = c2.oid
  395. ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
  396. foreach ($indexes as $i => $info) {
  397. $key = array_pop($info);
  398. if ($key['indisprimary']) {
  399. $key['relname'] = 'PRIMARY';
  400. }
  401. $col = array();
  402. preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns);
  403. $parsedColumn = $indexColumns[1];
  404. if (strpos($indexColumns[1], ',') !== false) {
  405. $parsedColumn = explode(', ', $indexColumns[1]);
  406. }
  407. $index[$key['relname']]['unique'] = $key['indisunique'];
  408. $index[$key['relname']]['column'] = $parsedColumn;
  409. }
  410. }
  411. return $index;
  412. }
  413. /**
  414. * Alter the Schema of a table.
  415. *
  416. * @param array $compare Results of CakeSchema::compare()
  417. * @param string $table name of the table
  418. * @access public
  419. * @return array
  420. */
  421. 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 $new Indexes to add and drop
  501. * @return array Index alteration statements
  502. */
  503. 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. 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. 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. 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 unknown_type $results
  626. */
  627. function resultSet(&$results) {
  628. $this->map = array();
  629. $numFields = $results->columnCount();
  630. $index = 0;
  631. $j = 0;
  632. while ($j < $numFields) {
  633. $column = $results->getColumnMeta($j);
  634. if (strpos($column['name'], '__')) {
  635. list($table, $name) = explode('__', $column['name']);
  636. $this->map[$index++] = array($table, $name, $column['native_type']);
  637. } else {
  638. $this->map[$index++] = array(0, $column['name'], $column['native_type']);
  639. }
  640. $j++;
  641. }
  642. }
  643. /**
  644. * Fetches the next row from the current result set
  645. *
  646. * @return unknown
  647. */
  648. function fetchResult() {
  649. if ($row = $this->_result->fetch()) {
  650. $resultRow = array();
  651. foreach ($this->map as $index => $meta) {
  652. list($table, $column, $type) = $meta;
  653. switch ($type) {
  654. case 'bool':
  655. $resultRow[$table][$column] = is_null($row[$index]) ? null : $this->boolean($row[$index]);
  656. break;
  657. case 'binary':
  658. case 'bytea':
  659. $resultRow[$table][$column] = stream_get_contents($row[$index]);
  660. break;
  661. default:
  662. $resultRow[$table][$column] = $row[$index];
  663. break;
  664. }
  665. }
  666. return $resultRow;
  667. } else {
  668. $this->_result->closeCursor();
  669. return false;
  670. }
  671. }
  672. /**
  673. * Translates between PHP boolean values and PostgreSQL boolean values
  674. *
  675. * @param mixed $data Value to be translated
  676. * @param boolean $quote true to quote a boolean to be used in a query, flase to return the boolean value
  677. * @return boolean Converted boolean value
  678. */
  679. function boolean($data, $quote = false) {
  680. switch (true) {
  681. case ($data === true || $data === false):
  682. $result = $data;
  683. break;
  684. case ($data === 't' || $data === 'f'):
  685. $result = ($data === 't');
  686. break;
  687. case ($data === 'true' || $data === 'false'):
  688. $result = ($data === 'true');
  689. break;
  690. case ($data === 'TRUE' || $data === 'FALSE'):
  691. $result = ($data === 'TRUE');
  692. break;
  693. default:
  694. $result = (bool) $data;
  695. break;
  696. }
  697. if ($quote) {
  698. return ($result) ? 'TRUE' : 'FALSE';
  699. }
  700. return (bool) $result;
  701. }
  702. /**
  703. * Sets the database encoding
  704. *
  705. * @param mixed $enc Database encoding
  706. * @return boolean True on success, false on failure
  707. */
  708. function setEncoding($enc) {
  709. if ($this->_execute('SET NAMES ?', array($enc))) {
  710. return true;
  711. }
  712. return false;
  713. }
  714. /**
  715. * Gets the database encoding
  716. *
  717. * @return string The database encoding
  718. */
  719. function getEncoding() {
  720. $cosa = $this->_execute('SHOW client_encoding')->fetch();
  721. }
  722. /**
  723. * Generate a Postgres-native column schema string
  724. *
  725. * @param array $column An array structured like the following:
  726. * array('name'=>'value', 'type'=>'value'[, options]),
  727. * where options can be 'default', 'length', or 'key'.
  728. * @return string
  729. */
  730. function buildColumn($column) {
  731. $col = $this->columns[$column['type']];
  732. if (!isset($col['length']) && !isset($col['limit'])) {
  733. unset($column['length']);
  734. }
  735. $out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column));
  736. $out = str_replace('integer serial', 'serial', $out);
  737. if (strpos($out, 'timestamp DEFAULT')) {
  738. if (isset($column['null']) && $column['null']) {
  739. $out = str_replace('DEFAULT NULL', '', $out);
  740. } else {
  741. $out = str_replace('DEFAULT NOT NULL', '', $out);
  742. }
  743. }
  744. if (strpos($out, 'DEFAULT DEFAULT')) {
  745. if (isset($column['null']) && $column['null']) {
  746. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
  747. } elseif (in_array($column['type'], array('integer', 'float'))) {
  748. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
  749. } elseif ($column['type'] == 'boolean') {
  750. $out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
  751. }
  752. }
  753. return $out;
  754. }
  755. /**
  756. * Format indexes for create table
  757. *
  758. * @param array $indexes
  759. * @param string $table
  760. * @return string
  761. */
  762. function buildIndex($indexes, $table = null) {
  763. $join = array();
  764. if (!is_array($indexes)) {
  765. return array();
  766. }
  767. foreach ($indexes as $name => $value) {
  768. if ($name == 'PRIMARY') {
  769. $out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
  770. } else {
  771. $out = 'CREATE ';
  772. if (!empty($value['unique'])) {
  773. $out .= 'UNIQUE ';
  774. }
  775. if (is_array($value['column'])) {
  776. $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
  777. } else {
  778. $value['column'] = $this->name($value['column']);
  779. }
  780. $out .= "INDEX {$name} ON {$table}({$value['column']});";
  781. }
  782. $join[] = $out;
  783. }
  784. return $join;
  785. }
  786. /**
  787. * Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
  788. *
  789. * @param string $type
  790. * @param array $data
  791. * @return string
  792. */
  793. function renderStatement($type, $data) {
  794. switch (strtolower($type)) {
  795. case 'schema':
  796. extract($data);
  797. foreach ($indexes as $i => $index) {
  798. if (preg_match('/PRIMARY KEY/', $index)) {
  799. unset($indexes[$i]);
  800. $columns[] = $index;
  801. break;
  802. }
  803. }
  804. $join = array('columns' => ",\n\t", 'indexes' => "\n");
  805. foreach (array('columns', 'indexes') as $var) {
  806. if (is_array(${$var})) {
  807. ${$var} = implode($join[$var], array_filter(${$var}));
  808. }
  809. }
  810. return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
  811. break;
  812. default:
  813. return parent::renderStatement($type, $data);
  814. break;
  815. }
  816. }
  817. }