| 1 |
lars |
1 |
<?php
|
|
|
2 |
/* SVN FILE: $Id: dbo_postgres.php 7945 2008-12-19 02:16:01Z gwoo $ */
|
|
|
3 |
|
|
|
4 |
/**
|
|
|
5 |
* PostgreSQL layer for DBO.
|
|
|
6 |
*
|
|
|
7 |
* Long description for file
|
|
|
8 |
*
|
|
|
9 |
* PHP versions 4 and 5
|
|
|
10 |
*
|
|
|
11 |
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
|
|
|
12 |
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
|
|
|
13 |
*
|
|
|
14 |
* Licensed under The MIT License
|
|
|
15 |
* Redistributions of files must retain the above copyright notice.
|
|
|
16 |
*
|
|
|
17 |
* @filesource
|
|
|
18 |
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
|
|
|
19 |
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
|
|
|
20 |
* @package cake
|
|
|
21 |
* @subpackage cake.cake.libs.model.datasources.dbo
|
|
|
22 |
* @since CakePHP(tm) v 0.9.1.114
|
|
|
23 |
* @version $Revision: 7945 $
|
|
|
24 |
* @modifiedby $LastChangedBy: gwoo $
|
|
|
25 |
* @lastmodified $Date: 2008-12-18 18:16:01 -0800 (Thu, 18 Dec 2008) $
|
|
|
26 |
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
|
|
27 |
*/
|
|
|
28 |
/**
|
|
|
29 |
* PostgreSQL layer for DBO.
|
|
|
30 |
*
|
|
|
31 |
* Long description for class
|
|
|
32 |
*
|
|
|
33 |
* @package cake
|
|
|
34 |
* @subpackage cake.cake.libs.model.datasources.dbo
|
|
|
35 |
*/
|
|
|
36 |
class DboPostgres extends DboSource {
|
|
|
37 |
/**
|
|
|
38 |
* Driver description
|
|
|
39 |
*
|
|
|
40 |
* @var string
|
|
|
41 |
* @access public
|
|
|
42 |
*/
|
|
|
43 |
var $description = "PostgreSQL DBO Driver";
|
|
|
44 |
/**
|
|
|
45 |
* Index of basic SQL commands
|
|
|
46 |
*
|
|
|
47 |
* @var array
|
|
|
48 |
* @access protected
|
|
|
49 |
*/
|
|
|
50 |
var $_commands = array(
|
|
|
51 |
'begin' => 'BEGIN',
|
|
|
52 |
'commit' => 'COMMIT',
|
|
|
53 |
'rollback' => 'ROLLBACK'
|
|
|
54 |
);
|
|
|
55 |
/**
|
|
|
56 |
* Base driver configuration settings. Merged with user settings.
|
|
|
57 |
*
|
|
|
58 |
* @var array
|
|
|
59 |
* @access protected
|
|
|
60 |
*/
|
|
|
61 |
var $_baseConfig = array(
|
|
|
62 |
'connect' => 'pg_pconnect',
|
|
|
63 |
'persistent' => true,
|
|
|
64 |
'host' => 'localhost',
|
|
|
65 |
'login' => 'root',
|
|
|
66 |
'password' => '',
|
|
|
67 |
'database' => 'cake',
|
|
|
68 |
'schema' => 'public',
|
|
|
69 |
'port' => 5432,
|
|
|
70 |
'encoding' => ''
|
|
|
71 |
);
|
|
|
72 |
|
|
|
73 |
var $columns = array(
|
|
|
74 |
'primary_key' => array('name' => 'serial NOT NULL'),
|
|
|
75 |
'string' => array('name' => 'varchar', 'limit' => '255'),
|
|
|
76 |
'text' => array('name' => 'text'),
|
|
|
77 |
'integer' => array('name' => 'integer', 'formatter' => 'intval'),
|
|
|
78 |
'float' => array('name' => 'float', 'formatter' => 'floatval'),
|
|
|
79 |
'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
|
|
80 |
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
|
|
|
81 |
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
|
|
|
82 |
'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
|
|
|
83 |
'binary' => array('name' => 'bytea'),
|
|
|
84 |
'boolean' => array('name' => 'boolean'),
|
|
|
85 |
'number' => array('name' => 'numeric'),
|
|
|
86 |
'inet' => array('name' => 'inet')
|
|
|
87 |
);
|
|
|
88 |
|
|
|
89 |
var $startQuote = '"';
|
|
|
90 |
|
|
|
91 |
var $endQuote = '"';
|
|
|
92 |
/**
|
|
|
93 |
* Contains mappings of custom auto-increment sequences, if a table uses a sequence name
|
|
|
94 |
* other than what is dictated by convention.
|
|
|
95 |
*
|
|
|
96 |
* @var array
|
|
|
97 |
*/
|
|
|
98 |
var $_sequenceMap = array();
|
|
|
99 |
/**
|
|
|
100 |
* Connects to the database using options in the given configuration array.
|
|
|
101 |
*
|
|
|
102 |
* @return True if successfully connected.
|
|
|
103 |
*/
|
|
|
104 |
function connect() {
|
|
|
105 |
$config = $this->config;
|
|
|
106 |
$conn = "host='{$config['host']}' port='{$config['port']}' dbname='{$config['database']}' ";
|
|
|
107 |
$conn .= "user='{$config['login']}' password='{$config['password']}'";
|
|
|
108 |
|
|
|
109 |
if (!$config['persistent']) {
|
|
|
110 |
$this->connection = pg_connect($conn, PGSQL_CONNECT_FORCE_NEW);
|
|
|
111 |
} else {
|
|
|
112 |
$this->connection = pg_pconnect($conn);
|
|
|
113 |
}
|
|
|
114 |
$this->connected = false;
|
|
|
115 |
|
|
|
116 |
if ($this->connection) {
|
|
|
117 |
$this->connected = true;
|
|
|
118 |
$this->_execute("SET search_path TO " . $config['schema']);
|
|
|
119 |
}
|
|
|
120 |
if (!empty($config['encoding'])) {
|
|
|
121 |
$this->setEncoding($config['encoding']);
|
|
|
122 |
}
|
|
|
123 |
return $this->connected;
|
|
|
124 |
}
|
|
|
125 |
/**
|
|
|
126 |
* Disconnects from database.
|
|
|
127 |
*
|
|
|
128 |
* @return boolean True if the database could be disconnected, else false
|
|
|
129 |
*/
|
|
|
130 |
function disconnect() {
|
|
|
131 |
if ($this->hasResult()) {
|
|
|
132 |
pg_free_result($this->_result);
|
|
|
133 |
}
|
|
|
134 |
if (is_resource($this->connection)) {
|
|
|
135 |
$this->connected = !pg_close($this->connection);
|
|
|
136 |
} else {
|
|
|
137 |
$this->connected = false;
|
|
|
138 |
}
|
|
|
139 |
return !$this->connected;
|
|
|
140 |
}
|
|
|
141 |
/**
|
|
|
142 |
* Executes given SQL statement.
|
|
|
143 |
*
|
|
|
144 |
* @param string $sql SQL statement
|
|
|
145 |
* @return resource Result resource identifier
|
|
|
146 |
*/
|
|
|
147 |
function _execute($sql) {
|
|
|
148 |
return pg_query($this->connection, $sql);
|
|
|
149 |
}
|
|
|
150 |
/**
|
|
|
151 |
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
|
|
|
152 |
*
|
|
|
153 |
* @return array Array of tablenames in the database
|
|
|
154 |
*/
|
|
|
155 |
function listSources() {
|
|
|
156 |
$cache = parent::listSources();
|
|
|
157 |
|
|
|
158 |
if ($cache != null) {
|
|
|
159 |
return $cache;
|
|
|
160 |
}
|
|
|
161 |
|
|
|
162 |
$schema = $this->config['schema'];
|
|
|
163 |
$sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = '{$schema}';";
|
|
|
164 |
$result = $this->fetchAll($sql, false);
|
|
|
165 |
|
|
|
166 |
if (!$result) {
|
|
|
167 |
return array();
|
|
|
168 |
} else {
|
|
|
169 |
$tables = array();
|
|
|
170 |
|
|
|
171 |
foreach ($result as $item) {
|
|
|
172 |
$tables[] = $item[0]['name'];
|
|
|
173 |
}
|
|
|
174 |
|
|
|
175 |
parent::listSources($tables);
|
|
|
176 |
return $tables;
|
|
|
177 |
}
|
|
|
178 |
}
|
|
|
179 |
/**
|
|
|
180 |
* Returns an array of the fields in given table name.
|
|
|
181 |
*
|
|
|
182 |
* @param string $tableName Name of database table to inspect
|
|
|
183 |
* @return array Fields in table. Keys are name and type
|
|
|
184 |
*/
|
|
|
185 |
function &describe(&$model) {
|
|
|
186 |
$fields = parent::describe($model);
|
|
|
187 |
$table = $this->fullTableName($model, false);
|
|
|
188 |
$this->_sequenceMap[$table] = array();
|
|
|
189 |
|
|
|
190 |
if ($fields === null) {
|
|
|
191 |
$cols = $this->fetchAll(
|
|
|
192 |
"SELECT DISTINCT column_name AS name, data_type AS type, is_nullable AS null,
|
|
|
193 |
column_default AS default, ordinal_position AS position, character_maximum_length AS char_length,
|
|
|
194 |
character_octet_length AS oct_length FROM information_schema.columns
|
|
|
195 |
WHERE table_name = " . $this->value($table) . " AND table_schema = " .
|
|
|
196 |
$this->value($this->config['schema'])." ORDER BY position",
|
|
|
197 |
false
|
|
|
198 |
);
|
|
|
199 |
|
|
|
200 |
foreach ($cols as $column) {
|
|
|
201 |
$colKey = array_keys($column);
|
|
|
202 |
|
|
|
203 |
if (isset($column[$colKey[0]]) && !isset($column[0])) {
|
|
|
204 |
$column[0] = $column[$colKey[0]];
|
|
|
205 |
}
|
|
|
206 |
|
|
|
207 |
if (isset($column[0])) {
|
|
|
208 |
$c = $column[0];
|
|
|
209 |
|
|
|
210 |
if (!empty($c['char_length'])) {
|
|
|
211 |
$length = intval($c['char_length']);
|
|
|
212 |
} elseif (!empty($c['oct_length'])) {
|
|
|
213 |
$length = intval($c['oct_length']);
|
|
|
214 |
} else {
|
|
|
215 |
$length = $this->length($c['type']);
|
|
|
216 |
}
|
|
|
217 |
$fields[$c['name']] = array(
|
|
|
218 |
'type' => $this->column($c['type']),
|
|
|
219 |
'null' => ($c['null'] == 'NO' ? false : true),
|
|
|
220 |
'default' => preg_replace(
|
|
|
221 |
"/^'(.*)'$/",
|
|
|
222 |
"$1",
|
|
|
223 |
preg_replace('/::.*/', '', $c['default'])
|
|
|
224 |
),
|
|
|
225 |
'length' => $length
|
|
|
226 |
);
|
|
|
227 |
if ($c['name'] == $model->primaryKey) {
|
|
|
228 |
$fields[$c['name']]['key'] = 'primary';
|
|
|
229 |
if ($fields[$c['name']]['type'] !== 'string') {
|
|
|
230 |
$fields[$c['name']]['length'] = 11;
|
|
|
231 |
}
|
|
|
232 |
}
|
|
|
233 |
if (
|
|
|
234 |
$fields[$c['name']]['default'] == 'NULL' ||
|
|
|
235 |
preg_match('/nextval\([\'"]?([\w.]+)/', $c['default'], $seq)
|
|
|
236 |
) {
|
|
|
237 |
$fields[$c['name']]['default'] = null;
|
|
|
238 |
if (!empty($seq) && isset($seq[1])) {
|
|
|
239 |
$this->_sequenceMap[$table][$c['name']] = $seq[1];
|
|
|
240 |
}
|
|
|
241 |
}
|
|
|
242 |
}
|
|
|
243 |
}
|
|
|
244 |
$this->__cacheDescription($table, $fields);
|
|
|
245 |
}
|
|
|
246 |
if (isset($model->sequence)) {
|
|
|
247 |
$this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;
|
|
|
248 |
}
|
|
|
249 |
return $fields;
|
|
|
250 |
}
|
|
|
251 |
/**
|
|
|
252 |
* Returns a quoted and escaped string of $data for use in an SQL statement.
|
|
|
253 |
*
|
|
|
254 |
* @param string $data String to be prepared for use in an SQL statement
|
|
|
255 |
* @param string $column The column into which this data will be inserted
|
|
|
256 |
* @param boolean $read Value to be used in READ or WRITE context
|
|
|
257 |
* @return string Quoted and escaped
|
|
|
258 |
* @todo Add logic that formats/escapes data based on column type
|
|
|
259 |
*/
|
|
|
260 |
function value($data, $column = null, $read = true) {
|
|
|
261 |
|
|
|
262 |
$parent = parent::value($data, $column);
|
|
|
263 |
if ($parent != null) {
|
|
|
264 |
return $parent;
|
|
|
265 |
}
|
|
|
266 |
|
|
|
267 |
if ($data === null) {
|
|
|
268 |
return 'NULL';
|
|
|
269 |
}
|
|
|
270 |
if (empty($column)) {
|
|
|
271 |
$column = $this->introspectType($data);
|
|
|
272 |
}
|
|
|
273 |
|
|
|
274 |
switch($column) {
|
|
|
275 |
case 'inet':
|
|
|
276 |
case 'float':
|
|
|
277 |
case 'integer':
|
|
|
278 |
if ($data === '') {
|
|
|
279 |
return $read ? 'NULL' : 'DEFAULT';
|
|
|
280 |
}
|
|
|
281 |
case 'binary':
|
|
|
282 |
$data = pg_escape_bytea($data);
|
|
|
283 |
break;
|
|
|
284 |
case 'boolean':
|
|
|
285 |
if ($data === true || $data === 't' || $data === 'true') {
|
|
|
286 |
return 'TRUE';
|
|
|
287 |
} elseif ($data === false || $data === 'f' || $data === 'false') {
|
|
|
288 |
return 'FALSE';
|
|
|
289 |
}
|
|
|
290 |
return (!empty($data) ? 'TRUE' : 'FALSE');
|
|
|
291 |
break;
|
|
|
292 |
default:
|
|
|
293 |
$data = pg_escape_string($data);
|
|
|
294 |
break;
|
|
|
295 |
}
|
|
|
296 |
return "'" . $data . "'";
|
|
|
297 |
}
|
|
|
298 |
/**
|
|
|
299 |
* Returns a formatted error message from previous database operation.
|
|
|
300 |
*
|
|
|
301 |
* @return string Error message
|
|
|
302 |
*/
|
|
|
303 |
function lastError() {
|
|
|
304 |
$error = pg_last_error($this->connection);
|
|
|
305 |
return ($error) ? $error : null;
|
|
|
306 |
}
|
|
|
307 |
/**
|
|
|
308 |
* Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
|
|
|
309 |
*
|
|
|
310 |
* @return integer Number of affected rows
|
|
|
311 |
*/
|
|
|
312 |
function lastAffected() {
|
|
|
313 |
return ($this->_result) ? pg_affected_rows($this->_result) : false;
|
|
|
314 |
}
|
|
|
315 |
/**
|
|
|
316 |
* Returns number of rows in previous resultset. If no previous resultset exists,
|
|
|
317 |
* this returns false.
|
|
|
318 |
*
|
|
|
319 |
* @return integer Number of rows in resultset
|
|
|
320 |
*/
|
|
|
321 |
function lastNumRows() {
|
|
|
322 |
return ($this->_result) ? pg_num_rows($this->_result) : false;
|
|
|
323 |
}
|
|
|
324 |
/**
|
|
|
325 |
* Returns the ID generated from the previous INSERT operation.
|
|
|
326 |
*
|
|
|
327 |
* @param string $source Name of the database table
|
|
|
328 |
* @param string $field Name of the ID database field. Defaults to "id"
|
|
|
329 |
* @return integer
|
|
|
330 |
*/
|
|
|
331 |
function lastInsertId($source, $field = 'id') {
|
|
|
332 |
$seq = $this->getSequence($source, $field);
|
|
|
333 |
$data = $this->fetchRow("SELECT currval('{$seq}') as max");
|
|
|
334 |
return $data[0]['max'];
|
|
|
335 |
}
|
|
|
336 |
/**
|
|
|
337 |
* Gets the associated sequence for the given table/field
|
|
|
338 |
*
|
|
|
339 |
* @param mixed $table Either a full table name (with prefix) as a string, or a model object
|
|
|
340 |
* @param string $field Name of the ID database field. Defaults to "id"
|
|
|
341 |
* @return string The associated sequence name from the sequence map, defaults to "{$table}_{$field}_seq"
|
|
|
342 |
*/
|
|
|
343 |
function getSequence($table, $field = 'id') {
|
|
|
344 |
if (is_object($table)) {
|
|
|
345 |
$table = $this->fullTableName($table, false);
|
|
|
346 |
}
|
|
|
347 |
if (isset($this->_sequenceMap[$table]) && isset($this->_sequenceMap[$table][$field])) {
|
|
|
348 |
return $this->_sequenceMap[$table][$field];
|
|
|
349 |
} else {
|
|
|
350 |
return "{$table}_{$field}_seq";
|
|
|
351 |
}
|
|
|
352 |
}
|
|
|
353 |
/**
|
|
|
354 |
* Deletes all the records in a table and drops all associated auto-increment sequences
|
|
|
355 |
*
|
|
|
356 |
* @param mixed $table A string or model class representing the table to be truncated
|
|
|
357 |
* @param integer $reset If -1, sequences are dropped, if 0 (default), sequences are reset,
|
|
|
358 |
* and if 1, sequences are not modified
|
|
|
359 |
* @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
|
|
|
360 |
* @access public
|
|
|
361 |
*/
|
|
|
362 |
function truncate($table, $reset = 0) {
|
|
|
363 |
if (parent::truncate($table)) {
|
|
|
364 |
$table = $this->fullTableName($table, false);
|
|
|
365 |
if (isset($this->_sequenceMap[$table]) && $reset !== 1) {
|
|
|
366 |
foreach ($this->_sequenceMap[$table] as $field => $sequence) {
|
|
|
367 |
if ($reset === 0) {
|
|
|
368 |
$this->execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1");
|
|
|
369 |
} elseif ($reset === -1) {
|
|
|
370 |
$this->execute("DROP SEQUENCE IF EXISTS \"{$sequence}\"");
|
|
|
371 |
}
|
|
|
372 |
}
|
|
|
373 |
}
|
|
|
374 |
return true;
|
|
|
375 |
}
|
|
|
376 |
return false;
|
|
|
377 |
}
|
|
|
378 |
/**
|
|
|
379 |
* Prepares field names to be quoted by parent
|
|
|
380 |
*
|
|
|
381 |
* @param string $data
|
|
|
382 |
* @return string SQL field
|
|
|
383 |
*/
|
|
|
384 |
function name($data) {
|
|
|
385 |
if (is_string($data)) {
|
|
|
386 |
$data = str_replace('"__"', '__', $data);
|
|
|
387 |
}
|
|
|
388 |
return parent::name($data);
|
|
|
389 |
}
|
|
|
390 |
/**
|
|
|
391 |
* Generates the fields list of an SQL query.
|
|
|
392 |
*
|
|
|
393 |
* @param Model $model
|
|
|
394 |
* @param string $alias Alias tablename
|
|
|
395 |
* @param mixed $fields
|
|
|
396 |
* @return array
|
|
|
397 |
*/
|
|
|
398 |
function fields(&$model, $alias = null, $fields = array(), $quote = true) {
|
|
|
399 |
if (empty($alias)) {
|
|
|
400 |
$alias = $model->alias;
|
|
|
401 |
}
|
|
|
402 |
$fields = parent::fields($model, $alias, $fields, false);
|
|
|
403 |
|
|
|
404 |
if (!$quote) {
|
|
|
405 |
return $fields;
|
|
|
406 |
}
|
|
|
407 |
$count = count($fields);
|
|
|
408 |
|
|
|
409 |
if ($count >= 1 && $fields[0] != '*' && strpos($fields[0], 'COUNT(*)') === false) {
|
|
|
410 |
for ($i = 0; $i < $count; $i++) {
|
|
|
411 |
if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
|
|
|
412 |
$prepend = '';
|
|
|
413 |
if (strpos($fields[$i], 'DISTINCT') !== false) {
|
|
|
414 |
$prepend = 'DISTINCT ';
|
|
|
415 |
$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
|
|
|
416 |
}
|
|
|
417 |
|
|
|
418 |
if (strrpos($fields[$i], '.') === false) {
|
|
|
419 |
$fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
|
|
|
420 |
} else {
|
|
|
421 |
$build = explode('.', $fields[$i]);
|
|
|
422 |
$fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
|
|
|
423 |
}
|
|
|
424 |
}
|
|
|
425 |
}
|
|
|
426 |
}
|
|
|
427 |
return $fields;
|
|
|
428 |
}
|
|
|
429 |
/**
|
|
|
430 |
* Returns an array of the indexes in given datasource name.
|
|
|
431 |
*
|
|
|
432 |
* @param string $model Name of model to inspect
|
|
|
433 |
* @return array Fields in table. Keys are column and unique
|
|
|
434 |
*/
|
|
|
435 |
function index($model) {
|
|
|
436 |
$index = array();
|
|
|
437 |
$table = $this->fullTableName($model, false);
|
|
|
438 |
if ($table) {
|
|
|
439 |
$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
|
|
|
440 |
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
|
|
|
441 |
WHERE c.oid = (
|
|
|
442 |
SELECT c.oid
|
|
|
443 |
FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
|
444 |
WHERE c.relname ~ '^(" . $table . ")$'
|
|
|
445 |
AND pg_catalog.pg_table_is_visible(c.oid)
|
|
|
446 |
AND n.nspname ~ '^(" . $this->config['schema'] . ")$'
|
|
|
447 |
)
|
|
|
448 |
AND c.oid = i.indrelid AND i.indexrelid = c2.oid
|
|
|
449 |
ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
|
|
|
450 |
foreach ($indexes as $i => $info) {
|
|
|
451 |
$key = array_pop($info);
|
|
|
452 |
if ($key['indisprimary']) {
|
|
|
453 |
$key['relname'] = 'PRIMARY';
|
|
|
454 |
}
|
|
|
455 |
$col = array();
|
|
|
456 |
preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns);
|
|
|
457 |
$parsedColumn = $indexColumns[1];
|
|
|
458 |
if (strpos($indexColumns[1], ',') !== false) {
|
|
|
459 |
$parsedColumn = explode(', ', $indexColumns[1]);
|
|
|
460 |
}
|
|
|
461 |
$index[$key['relname']]['unique'] = $key['indisunique'];
|
|
|
462 |
$index[$key['relname']]['column'] = $parsedColumn;
|
|
|
463 |
}
|
|
|
464 |
}
|
|
|
465 |
return $index;
|
|
|
466 |
}
|
|
|
467 |
/**
|
|
|
468 |
* Alter the Schema of a table.
|
|
|
469 |
*
|
|
|
470 |
* @param array $compare Results of CakeSchema::compare()
|
|
|
471 |
* @param string $table name of the table
|
|
|
472 |
* @access public
|
|
|
473 |
* @return array
|
|
|
474 |
*/
|
|
|
475 |
function alterSchema($compare, $table = null) {
|
|
|
476 |
if (!is_array($compare)) {
|
|
|
477 |
return false;
|
|
|
478 |
}
|
|
|
479 |
$out = '';
|
|
|
480 |
$colList = array();
|
|
|
481 |
foreach ($compare as $curTable => $types) {
|
|
|
482 |
$indexes = array();
|
|
|
483 |
if (!$table || $table == $curTable) {
|
|
|
484 |
$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
|
|
|
485 |
foreach ($types as $type => $column) {
|
|
|
486 |
if (isset($column['indexes'])) {
|
|
|
487 |
$indexes[$type] = $column['indexes'];
|
|
|
488 |
unset($column['indexes']);
|
|
|
489 |
}
|
|
|
490 |
switch ($type) {
|
|
|
491 |
case 'add':
|
|
|
492 |
foreach ($column as $field => $col) {
|
|
|
493 |
$col['name'] = $field;
|
|
|
494 |
$alter = 'ADD COLUMN '.$this->buildColumn($col);
|
|
|
495 |
if (isset($col['after'])) {
|
|
|
496 |
$alter .= ' AFTER '. $this->name($col['after']);
|
|
|
497 |
}
|
|
|
498 |
$colList[] = $alter;
|
|
|
499 |
}
|
|
|
500 |
break;
|
|
|
501 |
case 'drop':
|
|
|
502 |
foreach ($column as $field => $col) {
|
|
|
503 |
$col['name'] = $field;
|
|
|
504 |
$colList[] = 'DROP COLUMN '.$this->name($field);
|
|
|
505 |
}
|
|
|
506 |
break;
|
|
|
507 |
case 'change':
|
|
|
508 |
foreach ($column as $field => $col) {
|
|
|
509 |
if (!isset($col['name'])) {
|
|
|
510 |
$col['name'] = $field;
|
|
|
511 |
}
|
|
|
512 |
$fieldName = $this->name($field);
|
|
|
513 |
$colList[] = 'ALTER COLUMN '. $fieldName .' TYPE ' . str_replace($fieldName, '', $this->buildColumn($col));
|
|
|
514 |
}
|
|
|
515 |
break;
|
|
|
516 |
}
|
|
|
517 |
}
|
|
|
518 |
if (isset($indexes['drop']['PRIMARY'])) {
|
|
|
519 |
$colList[] = 'DROP CONSTRAINT ' . $curTable . '_pkey';
|
|
|
520 |
}
|
|
|
521 |
if (isset($indexes['add']['PRIMARY'])) {
|
|
|
522 |
$cols = $indexes['add']['PRIMARY']['column'];
|
|
|
523 |
if (is_array($cols)) {
|
|
|
524 |
$cols = implode(', ', $cols);
|
|
|
525 |
}
|
|
|
526 |
$colList[] = 'ADD PRIMARY KEY (' . $cols . ')';
|
|
|
527 |
}
|
|
|
528 |
|
|
|
529 |
if (!empty($colList)) {
|
|
|
530 |
$out .= "\t" . join(",\n\t", $colList) . ";\n\n";
|
|
|
531 |
} else {
|
|
|
532 |
$out = '';
|
|
|
533 |
}
|
|
|
534 |
$out .= join(";\n\t", $this->_alterIndexes($curTable, $indexes)) . ";";
|
|
|
535 |
}
|
|
|
536 |
}
|
|
|
537 |
return $out;
|
|
|
538 |
}
|
|
|
539 |
/**
|
|
|
540 |
* Generate PostgreSQL index alteration statements for a table.
|
|
|
541 |
*
|
|
|
542 |
* @param string $table Table to alter indexes for
|
|
|
543 |
* @param array $new Indexes to add and drop
|
|
|
544 |
* @return array Index alteration statements
|
|
|
545 |
*/
|
|
|
546 |
function _alterIndexes($table, $indexes) {
|
|
|
547 |
$alter = array();
|
|
|
548 |
if (isset($indexes['drop'])) {
|
|
|
549 |
foreach($indexes['drop'] as $name => $value) {
|
|
|
550 |
$out = 'DROP ';
|
|
|
551 |
if ($name == 'PRIMARY') {
|
|
|
552 |
continue;
|
|
|
553 |
} else {
|
|
|
554 |
$out .= 'INDEX ' . $name;
|
|
|
555 |
}
|
|
|
556 |
$alter[] = $out;
|
|
|
557 |
}
|
|
|
558 |
}
|
|
|
559 |
if (isset($indexes['add'])) {
|
|
|
560 |
foreach ($indexes['add'] as $name => $value) {
|
|
|
561 |
$out = 'CREATE ';
|
|
|
562 |
if ($name == 'PRIMARY') {
|
|
|
563 |
continue;
|
|
|
564 |
} else {
|
|
|
565 |
if (!empty($value['unique'])) {
|
|
|
566 |
$out .= 'UNIQUE ';
|
|
|
567 |
}
|
|
|
568 |
$out .= 'INDEX ';
|
|
|
569 |
}
|
|
|
570 |
if (is_array($value['column'])) {
|
|
|
571 |
$out .= $name . ' ON ' . $table . ' (' . join(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
|
|
|
572 |
} else {
|
|
|
573 |
$out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')';
|
|
|
574 |
}
|
|
|
575 |
$alter[] = $out;
|
|
|
576 |
}
|
|
|
577 |
}
|
|
|
578 |
return $alter;
|
|
|
579 |
}
|
|
|
580 |
/**
|
|
|
581 |
* Returns a limit statement in the correct format for the particular database.
|
|
|
582 |
*
|
|
|
583 |
* @param integer $limit Limit of results returned
|
|
|
584 |
* @param integer $offset Offset from which to start results
|
|
|
585 |
* @return string SQL limit/offset statement
|
|
|
586 |
*/
|
|
|
587 |
function limit($limit, $offset = null) {
|
|
|
588 |
if ($limit) {
|
|
|
589 |
$rt = '';
|
|
|
590 |
if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
|
|
|
591 |
$rt = ' LIMIT';
|
|
|
592 |
}
|
|
|
593 |
|
|
|
594 |
$rt .= ' ' . $limit;
|
|
|
595 |
if ($offset) {
|
|
|
596 |
$rt .= ' OFFSET ' . $offset;
|
|
|
597 |
}
|
|
|
598 |
|
|
|
599 |
return $rt;
|
|
|
600 |
}
|
|
|
601 |
return null;
|
|
|
602 |
}
|
|
|
603 |
/**
|
|
|
604 |
* Converts database-layer column types to basic types
|
|
|
605 |
*
|
|
|
606 |
* @param string $real Real database-layer column type (i.e. "varchar(255)")
|
|
|
607 |
* @return string Abstract column type (i.e. "string")
|
|
|
608 |
*/
|
|
|
609 |
function column($real) {
|
|
|
610 |
if (is_array($real)) {
|
|
|
611 |
$col = $real['name'];
|
|
|
612 |
if (isset($real['limit'])) {
|
|
|
613 |
$col .= '(' . $real['limit'] . ')';
|
|
|
614 |
}
|
|
|
615 |
return $col;
|
|
|
616 |
}
|
|
|
617 |
|
|
|
618 |
$col = str_replace(')', '', $real);
|
|
|
619 |
$limit = null;
|
|
|
620 |
|
|
|
621 |
if (strpos($col, '(') !== false) {
|
|
|
622 |
list($col, $limit) = explode('(', $col);
|
|
|
623 |
}
|
|
|
624 |
|
|
|
625 |
$floats = array(
|
|
|
626 |
'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'real', 'numeric'
|
|
|
627 |
);
|
|
|
628 |
|
|
|
629 |
switch (true) {
|
|
|
630 |
case (in_array($col, array('date', 'time', 'inet', 'boolean'))):
|
|
|
631 |
return $col;
|
|
|
632 |
case (strpos($col, 'timestamp') !== false):
|
|
|
633 |
return 'datetime';
|
|
|
634 |
case (strpos($col, 'time') === 0):
|
|
|
635 |
return 'time';
|
|
|
636 |
case (strpos($col, 'int') !== false && $col != 'interval'):
|
|
|
637 |
return 'integer';
|
|
|
638 |
case (strpos($col, 'char') !== false || $col == 'uuid'):
|
|
|
639 |
return 'string';
|
|
|
640 |
case (strpos($col, 'text') !== false):
|
|
|
641 |
return 'text';
|
|
|
642 |
case (strpos($col, 'bytea') !== false):
|
|
|
643 |
return 'binary';
|
|
|
644 |
case (in_array($col, $floats)):
|
|
|
645 |
return 'float';
|
|
|
646 |
default:
|
|
|
647 |
return 'text';
|
|
|
648 |
break;
|
|
|
649 |
}
|
|
|
650 |
}
|
|
|
651 |
/**
|
|
|
652 |
* Gets the length of a database-native column description, or null if no length
|
|
|
653 |
*
|
|
|
654 |
* @param string $real Real database-layer column type (i.e. "varchar(255)")
|
|
|
655 |
* @return int An integer representing the length of the column
|
|
|
656 |
*/
|
|
|
657 |
function length($real) {
|
|
|
658 |
$col = str_replace(array(')', 'unsigned'), '', $real);
|
|
|
659 |
$limit = null;
|
|
|
660 |
|
|
|
661 |
if (strpos($col, '(') !== false) {
|
|
|
662 |
list($col, $limit) = explode('(', $col);
|
|
|
663 |
}
|
|
|
664 |
if ($col == 'uuid') {
|
|
|
665 |
return 36;
|
|
|
666 |
}
|
|
|
667 |
if ($limit != null) {
|
|
|
668 |
return intval($limit);
|
|
|
669 |
}
|
|
|
670 |
return null;
|
|
|
671 |
}
|
|
|
672 |
/**
|
|
|
673 |
* Enter description here...
|
|
|
674 |
*
|
|
|
675 |
* @param unknown_type $results
|
|
|
676 |
*/
|
|
|
677 |
function resultSet(&$results) {
|
|
|
678 |
$this->results =& $results;
|
|
|
679 |
$this->map = array();
|
|
|
680 |
$num_fields = pg_num_fields($results);
|
|
|
681 |
$index = 0;
|
|
|
682 |
$j = 0;
|
|
|
683 |
|
|
|
684 |
while ($j < $num_fields) {
|
|
|
685 |
$columnName = pg_field_name($results, $j);
|
|
|
686 |
|
|
|
687 |
if (strpos($columnName, '__')) {
|
|
|
688 |
$parts = explode('__', $columnName);
|
|
|
689 |
$this->map[$index++] = array($parts[0], $parts[1]);
|
|
|
690 |
} else {
|
|
|
691 |
$this->map[$index++] = array(0, $columnName);
|
|
|
692 |
}
|
|
|
693 |
$j++;
|
|
|
694 |
}
|
|
|
695 |
}
|
|
|
696 |
/**
|
|
|
697 |
* Fetches the next row from the current result set
|
|
|
698 |
*
|
|
|
699 |
* @return unknown
|
|
|
700 |
*/
|
|
|
701 |
function fetchResult() {
|
|
|
702 |
if ($row = pg_fetch_row($this->results)) {
|
|
|
703 |
$resultRow = array();
|
|
|
704 |
|
|
|
705 |
foreach ($row as $index => $field) {
|
|
|
706 |
list($table, $column) = $this->map[$index];
|
|
|
707 |
$type = pg_field_type($this->results, $index);
|
|
|
708 |
|
|
|
709 |
switch ($type) {
|
|
|
710 |
case 'bool':
|
|
|
711 |
$resultRow[$table][$column] = $this->boolean($row[$index], false);
|
|
|
712 |
break;
|
|
|
713 |
case 'binary':
|
|
|
714 |
case 'bytea':
|
|
|
715 |
$resultRow[$table][$column] = pg_unescape_bytea($row[$index]);
|
|
|
716 |
break;
|
|
|
717 |
default:
|
|
|
718 |
$resultRow[$table][$column] = $row[$index];
|
|
|
719 |
break;
|
|
|
720 |
}
|
|
|
721 |
}
|
|
|
722 |
return $resultRow;
|
|
|
723 |
} else {
|
|
|
724 |
return false;
|
|
|
725 |
}
|
|
|
726 |
}
|
|
|
727 |
/**
|
|
|
728 |
* Translates between PHP boolean values and PostgreSQL boolean values
|
|
|
729 |
*
|
|
|
730 |
* @param mixed $data Value to be translated
|
|
|
731 |
* @param boolean $quote True to quote value, false otherwise
|
|
|
732 |
* @return mixed Converted boolean value
|
|
|
733 |
*/
|
|
|
734 |
function boolean($data, $quote = true) {
|
|
|
735 |
switch (true) {
|
|
|
736 |
case ($data === true || $data === false):
|
|
|
737 |
return $data;
|
|
|
738 |
case ($data === 't' || $data === 'f'):
|
|
|
739 |
return ($data === 't');
|
|
|
740 |
case ($data === 'true' || $data === 'false'):
|
|
|
741 |
return ($data === 'true');
|
|
|
742 |
case ($data === 'TRUE' || $data === 'FALSE'):
|
|
|
743 |
return ($data === 'TRUE');
|
|
|
744 |
default:
|
|
|
745 |
return (bool)$data;
|
|
|
746 |
break;
|
|
|
747 |
}
|
|
|
748 |
}
|
|
|
749 |
/**
|
|
|
750 |
* Sets the database encoding
|
|
|
751 |
*
|
|
|
752 |
* @param mixed $enc Database encoding
|
|
|
753 |
* @return boolean True on success, false on failure
|
|
|
754 |
*/
|
|
|
755 |
function setEncoding($enc) {
|
|
|
756 |
return pg_set_client_encoding($this->connection, $enc) == 0;
|
|
|
757 |
}
|
|
|
758 |
/**
|
|
|
759 |
* Gets the database encoding
|
|
|
760 |
*
|
|
|
761 |
* @return string The database encoding
|
|
|
762 |
*/
|
|
|
763 |
function getEncoding() {
|
|
|
764 |
return pg_client_encoding($this->connection);
|
|
|
765 |
}
|
|
|
766 |
/**
|
|
|
767 |
* Generate a Postgres-native column schema string
|
|
|
768 |
*
|
|
|
769 |
* @param array $column An array structured like the following:
|
|
|
770 |
* array('name'=>'value', 'type'=>'value'[, options]),
|
|
|
771 |
* where options can be 'default', 'length', or 'key'.
|
|
|
772 |
* @return string
|
|
|
773 |
*/
|
|
|
774 |
function buildColumn($column) {
|
|
|
775 |
$col = $this->columns[$column['type']];
|
|
|
776 |
if (!isset($col['length']) && !isset($col['limit'])) {
|
|
|
777 |
unset($column['length']);
|
|
|
778 |
}
|
|
|
779 |
$out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column));
|
|
|
780 |
$out = str_replace('integer serial', 'serial', $out);
|
|
|
781 |
if (strpos($out, 'timestamp DEFAULT')) {
|
|
|
782 |
if (isset($column['null']) && $column['null']) {
|
|
|
783 |
$out = str_replace('DEFAULT NULL', '', $out);
|
|
|
784 |
} else {
|
|
|
785 |
$out = str_replace('DEFAULT NOT NULL', '', $out);
|
|
|
786 |
}
|
|
|
787 |
}
|
|
|
788 |
if (strpos($out, 'DEFAULT DEFAULT')) {
|
|
|
789 |
if (isset($column['null']) && $column['null']) {
|
|
|
790 |
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
|
|
|
791 |
} elseif (in_array($column['type'], array('integer', 'float'))) {
|
|
|
792 |
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
|
|
|
793 |
} elseif ($column['type'] == 'boolean') {
|
|
|
794 |
$out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
|
|
|
795 |
}
|
|
|
796 |
}
|
|
|
797 |
return $out;
|
|
|
798 |
}
|
|
|
799 |
/**
|
|
|
800 |
* Format indexes for create table
|
|
|
801 |
*
|
|
|
802 |
* @param array $indexes
|
|
|
803 |
* @param string $table
|
|
|
804 |
* @return string
|
|
|
805 |
*/
|
|
|
806 |
function buildIndex($indexes, $table = null) {
|
|
|
807 |
$join = array();
|
|
|
808 |
if (!is_array($indexes)) {
|
|
|
809 |
return array();
|
|
|
810 |
}
|
|
|
811 |
foreach ($indexes as $name => $value) {
|
|
|
812 |
if ($name == 'PRIMARY') {
|
|
|
813 |
$out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
|
|
|
814 |
} else {
|
|
|
815 |
$out = 'CREATE ';
|
|
|
816 |
if (!empty($value['unique'])) {
|
|
|
817 |
$out .= 'UNIQUE ';
|
|
|
818 |
}
|
|
|
819 |
if (is_array($value['column'])) {
|
|
|
820 |
$value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
|
|
|
821 |
} else {
|
|
|
822 |
$value['column'] = $this->name($value['column']);
|
|
|
823 |
}
|
|
|
824 |
$out .= "INDEX {$name} ON {$table}({$value['column']});";
|
|
|
825 |
}
|
|
|
826 |
$join[] = $out;
|
|
|
827 |
}
|
|
|
828 |
return $join;
|
|
|
829 |
}
|
|
|
830 |
/**
|
|
|
831 |
* Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
|
|
|
832 |
*
|
|
|
833 |
* @param string $type
|
|
|
834 |
* @param array $data
|
|
|
835 |
* @return string
|
|
|
836 |
*/
|
|
|
837 |
function renderStatement($type, $data) {
|
|
|
838 |
switch (strtolower($type)) {
|
|
|
839 |
case 'schema':
|
|
|
840 |
extract($data);
|
|
|
841 |
|
|
|
842 |
foreach ($indexes as $i => $index) {
|
|
|
843 |
if (preg_match('/PRIMARY KEY/', $index)) {
|
|
|
844 |
unset($indexes[$i]);
|
|
|
845 |
$columns[] = $index;
|
|
|
846 |
break;
|
|
|
847 |
}
|
|
|
848 |
}
|
|
|
849 |
$join = array('columns' => ",\n\t", 'indexes' => "\n");
|
|
|
850 |
|
|
|
851 |
foreach (array('columns', 'indexes') as $var) {
|
|
|
852 |
if (is_array(${$var})) {
|
|
|
853 |
${$var} = join($join[$var], array_filter(${$var}));
|
|
|
854 |
}
|
|
|
855 |
}
|
|
|
856 |
return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
|
|
|
857 |
break;
|
|
|
858 |
default:
|
|
|
859 |
return parent::renderStatement($type, $data);
|
|
|
860 |
break;
|
|
|
861 |
}
|
|
|
862 |
}
|
|
|
863 |
}
|
|
|
864 |
?>
|