Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12345 anikendra 1
<?php
2
/**
3
 * PostgreSQL layer for DBO.
4
 *
5
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
6
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7
 *
8
 * Licensed under The MIT License
9
 * For full copyright and license information, please see the LICENSE.txt
10
 * Redistributions of files must retain the above copyright notice.
11
 *
12
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13
 * @link          http://cakephp.org CakePHP(tm) Project
14
 * @package       Cake.Model.Datasource.Database
15
 * @since         CakePHP(tm) v 0.9.1.114
16
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
17
 */
18
 
19
App::uses('DboSource', 'Model/Datasource');
20
 
21
/**
22
 * PostgreSQL layer for DBO.
23
 *
24
 * @package       Cake.Model.Datasource.Database
25
 */
26
class Postgres extends DboSource {
27
 
28
/**
29
 * Driver description
30
 *
31
 * @var string
32
 */
33
	public $description = "PostgreSQL DBO Driver";
34
 
35
/**
36
 * Base driver configuration settings. Merged with user settings.
37
 *
38
 * @var array
39
 */
40
	protected $_baseConfig = array(
41
		'persistent' => true,
42
		'host' => 'localhost',
43
		'login' => 'root',
44
		'password' => '',
45
		'database' => 'cake',
46
		'schema' => 'public',
47
		'port' => 5432,
48
		'encoding' => '',
49
		'flags' => array()
50
	);
51
 
52
/**
53
 * Columns
54
 *
55
 * @var array
56
 */
57
	public $columns = array(
58
		'primary_key' => array('name' => 'serial NOT NULL'),
59
		'string' => array('name' => 'varchar', 'limit' => '255'),
60
		'text' => array('name' => 'text'),
61
		'integer' => array('name' => 'integer', 'formatter' => 'intval'),
62
		'biginteger' => array('name' => 'bigint', 'limit' => '20'),
63
		'float' => array('name' => 'float', 'formatter' => 'floatval'),
64
		'decimal' => array('name' => 'decimal', 'formatter' => 'floatval'),
65
		'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
66
		'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
67
		'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
68
		'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
69
		'binary' => array('name' => 'bytea'),
70
		'boolean' => array('name' => 'boolean'),
71
		'number' => array('name' => 'numeric'),
72
		'inet' => array('name' => 'inet')
73
	);
74
 
75
/**
76
 * Starting Quote
77
 *
78
 * @var string
79
 */
80
	public $startQuote = '"';
81
 
82
/**
83
 * Ending Quote
84
 *
85
 * @var string
86
 */
87
	public $endQuote = '"';
88
 
89
/**
90
 * Contains mappings of custom auto-increment sequences, if a table uses a sequence name
91
 * other than what is dictated by convention.
92
 *
93
 * @var array
94
 */
95
	protected $_sequenceMap = array();
96
 
97
/**
98
 * The set of valid SQL operations usable in a WHERE statement
99
 *
100
 * @var array
101
 */
102
	protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', '~', '~*', '!~', '!~*', 'similar to');
103
 
104
/**
105
 * Connects to the database using options in the given configuration array.
106
 *
107
 * @return bool True if successfully connected.
108
 * @throws MissingConnectionException
109
 */
110
	public function connect() {
111
		$config = $this->config;
112
		$this->connected = false;
113
 
114
		$flags = $config['flags'] + array(
115
			PDO::ATTR_PERSISTENT => $config['persistent'],
116
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
117
		);
118
 
119
		try {
120
			$this->_connection = new PDO(
121
				"pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}",
122
				$config['login'],
123
				$config['password'],
124
				$flags
125
			);
126
 
127
			$this->connected = true;
128
			if (!empty($config['encoding'])) {
129
				$this->setEncoding($config['encoding']);
130
			}
131
			if (!empty($config['schema'])) {
132
				$this->_execute('SET search_path TO "' . $config['schema'] . '"');
133
			}
134
			if (!empty($config['settings'])) {
135
				foreach ($config['settings'] as $key => $value) {
136
					$this->_execute("SET $key TO $value");
137
				}
138
			}
139
		} catch (PDOException $e) {
140
			throw new MissingConnectionException(array(
141
				'class' => get_class($this),
142
				'message' => $e->getMessage()
143
			));
144
		}
145
 
146
		return $this->connected;
147
	}
148
 
149
/**
150
 * Check if PostgreSQL is enabled/loaded
151
 *
152
 * @return bool
153
 */
154
	public function enabled() {
155
		return in_array('pgsql', PDO::getAvailableDrivers());
156
	}
157
 
158
/**
159
 * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
160
 *
161
 * @param mixed $data The sources to list.
162
 * @return array Array of table names in the database
163
 */
164
	public function listSources($data = null) {
165
		$cache = parent::listSources();
166
 
167
		if ($cache) {
168
			return $cache;
169
		}
170
 
171
		$schema = $this->config['schema'];
172
		$sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = ?";
173
		$result = $this->_execute($sql, array($schema));
174
 
175
		if (!$result) {
176
			return array();
177
		}
178
 
179
		$tables = array();
180
 
181
		foreach ($result as $item) {
182
			$tables[] = $item->name;
183
		}
184
 
185
		$result->closeCursor();
186
		parent::listSources($tables);
187
		return $tables;
188
	}
189
 
190
/**
191
 * Returns an array of the fields in given table name.
192
 *
193
 * @param Model|string $model Name of database table to inspect
194
 * @return array Fields in table. Keys are name and type
195
 */
196
	public function describe($model) {
197
		$table = $this->fullTableName($model, false, false);
198
		$fields = parent::describe($table);
199
		$this->_sequenceMap[$table] = array();
200
		$cols = null;
201
 
202
		if ($fields === null) {
203
			$cols = $this->_execute(
204
				"SELECT DISTINCT table_schema AS schema, column_name AS name, data_type AS type, is_nullable AS null,
205
					column_default AS default, ordinal_position AS position, character_maximum_length AS char_length,
206
					character_octet_length AS oct_length FROM information_schema.columns
207
				WHERE table_name = ? AND table_schema = ?  ORDER BY position",
208
				array($table, $this->config['schema'])
209
			);
210
 
211
			// @codingStandardsIgnoreStart
212
			// Postgres columns don't match the coding standards.
213
			foreach ($cols as $c) {
214
				$type = $c->type;
215
				if (!empty($c->oct_length) && $c->char_length === null) {
216
					if ($c->type === 'character varying') {
217
						$length = null;
218
						$type = 'text';
219
					} elseif ($c->type === 'uuid') {
220
						$length = 36;
221
					} else {
222
						$length = intval($c->oct_length);
223
					}
224
				} elseif (!empty($c->char_length)) {
225
					$length = intval($c->char_length);
226
				} else {
227
					$length = $this->length($c->type);
228
				}
229
				if (empty($length)) {
230
					$length = null;
231
				}
232
				$fields[$c->name] = array(
233
					'type' => $this->column($type),
234
					'null' => ($c->null === 'NO' ? false : true),
235
					'default' => preg_replace(
236
						"/^'(.*)'$/",
237
						"$1",
238
						preg_replace('/::.*/', '', $c->default)
239
					),
240
					'length' => $length
241
				);
242
				if ($model instanceof Model) {
243
					if ($c->name === $model->primaryKey) {
244
						$fields[$c->name]['key'] = 'primary';
245
						if ($fields[$c->name]['type'] !== 'string') {
246
							$fields[$c->name]['length'] = 11;
247
						}
248
					}
249
				}
250
				if (
251
					$fields[$c->name]['default'] === 'NULL' ||
252
					preg_match('/nextval\([\'"]?([\w.]+)/', $c->default, $seq)
253
				) {
254
					$fields[$c->name]['default'] = null;
255
					if (!empty($seq) && isset($seq[1])) {
256
						if (strpos($seq[1], '.') === false) {
257
							$sequenceName = $c->schema . '.' . $seq[1];
258
						} else {
259
							$sequenceName = $seq[1];
260
						}
261
						$this->_sequenceMap[$table][$c->name] = $sequenceName;
262
					}
263
				}
264
				if ($fields[$c->name]['type'] === 'timestamp' && $fields[$c->name]['default'] === '') {
265
					$fields[$c->name]['default'] = null;
266
				}
267
				if ($fields[$c->name]['type'] === 'boolean' && !empty($fields[$c->name]['default'])) {
268
					$fields[$c->name]['default'] = constant($fields[$c->name]['default']);
269
				}
270
			}
271
			$this->_cacheDescription($table, $fields);
272
		}
273
		// @codingStandardsIgnoreEnd
274
 
275
		if (isset($model->sequence)) {
276
			$this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;
277
		}
278
 
279
		if ($cols) {
280
			$cols->closeCursor();
281
		}
282
		return $fields;
283
	}
284
 
285
/**
286
 * Returns the ID generated from the previous INSERT operation.
287
 *
288
 * @param string $source Name of the database table
289
 * @param string $field Name of the ID database field. Defaults to "id"
290
 * @return int
291
 */
292
	public function lastInsertId($source = null, $field = 'id') {
293
		$seq = $this->getSequence($source, $field);
294
		return $this->_connection->lastInsertId($seq);
295
	}
296
 
297
/**
298
 * Gets the associated sequence for the given table/field
299
 *
300
 * @param string|Model $table Either a full table name (with prefix) as a string, or a model object
301
 * @param string $field Name of the ID database field. Defaults to "id"
302
 * @return string The associated sequence name from the sequence map, defaults to "{$table}_{$field}_seq"
303
 */
304
	public function getSequence($table, $field = 'id') {
305
		if (is_object($table)) {
306
			$table = $this->fullTableName($table, false, false);
307
		}
308
		if (!isset($this->_sequenceMap[$table])) {
309
			$this->describe($table);
310
		}
311
		if (isset($this->_sequenceMap[$table][$field])) {
312
			return $this->_sequenceMap[$table][$field];
313
		}
314
		return "{$table}_{$field}_seq";
315
	}
316
 
317
/**
318
 * Reset a sequence based on the MAX() value of $column. Useful
319
 * for resetting sequences after using insertMulti().
320
 *
321
 * @param string $table The name of the table to update.
322
 * @param string $column The column to use when resetting the sequence value,
323
 *   the sequence name will be fetched using Postgres::getSequence();
324
 * @return bool success.
325
 */
326
	public function resetSequence($table, $column) {
327
		$tableName = $this->fullTableName($table, false, false);
328
		$fullTable = $this->fullTableName($table);
329
 
330
		$sequence = $this->value($this->getSequence($tableName, $column));
331
		$column = $this->name($column);
332
		$this->execute("SELECT setval($sequence, (SELECT MAX($column) FROM $fullTable))");
333
		return true;
334
	}
335
 
336
/**
337
 * Deletes all the records in a table and drops all associated auto-increment sequences
338
 *
339
 * @param string|Model $table A string or model class representing the table to be truncated
340
 * @param bool $reset true for resetting the sequence, false to leave it as is.
341
 *    and if 1, sequences are not modified
342
 * @return bool SQL TRUNCATE TABLE statement, false if not applicable.
343
 */
344
	public function truncate($table, $reset = false) {
345
		$table = $this->fullTableName($table, false, false);
346
		if (!isset($this->_sequenceMap[$table])) {
347
			$cache = $this->cacheSources;
348
			$this->cacheSources = false;
349
			$this->describe($table);
350
			$this->cacheSources = $cache;
351
		}
352
		if ($this->execute('DELETE FROM ' . $this->fullTableName($table))) {
353
			if (isset($this->_sequenceMap[$table]) && $reset != true) {
354
				foreach ($this->_sequenceMap[$table] as $sequence) {
355
					list($schema, $sequence) = explode('.', $sequence);
356
					$this->_execute("ALTER SEQUENCE \"{$schema}\".\"{$sequence}\" RESTART WITH 1");
357
				}
358
			}
359
			return true;
360
		}
361
		return false;
362
	}
363
 
364
/**
365
 * Prepares field names to be quoted by parent
366
 *
367
 * @param string $data The name to format.
368
 * @return string SQL field
369
 */
370
	public function name($data) {
371
		if (is_string($data)) {
372
			$data = str_replace('"__"', '__', $data);
373
		}
374
		return parent::name($data);
375
	}
376
 
377
/**
378
 * Generates the fields list of an SQL query.
379
 *
380
 * @param Model $model The model to get fields for.
381
 * @param string $alias Alias table name.
382
 * @param mixed $fields The list of fields to get.
383
 * @param bool $quote Whether or not to quote identifiers.
384
 * @return array
385
 */
386
	public function fields(Model $model, $alias = null, $fields = array(), $quote = true) {
387
		if (empty($alias)) {
388
			$alias = $model->alias;
389
		}
390
		$fields = parent::fields($model, $alias, $fields, false);
391
 
392
		if (!$quote) {
393
			return $fields;
394
		}
395
		$count = count($fields);
396
 
397
		if ($count >= 1 && !preg_match('/^\s*COUNT\(\*/', $fields[0])) {
398
			$result = array();
399
			for ($i = 0; $i < $count; $i++) {
400
				if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
401
					if (substr($fields[$i], -1) === '*') {
402
						if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
403
							$build = explode('.', $fields[$i]);
404
							$AssociatedModel = $model->{$build[0]};
405
						} else {
406
							$AssociatedModel = $model;
407
						}
408
 
409
						$_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
410
						$result = array_merge($result, $_fields);
411
						continue;
412
					}
413
 
414
					$prepend = '';
415
					if (strpos($fields[$i], 'DISTINCT') !== false) {
416
						$prepend = 'DISTINCT ';
417
						$fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
418
					}
419
 
420
					if (strrpos($fields[$i], '.') === false) {
421
						$fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
422
					} else {
423
						$build = explode('.', $fields[$i]);
424
						$fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
425
					}
426
				} else {
427
					$fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]);
428
				}
429
				$result[] = $fields[$i];
430
			}
431
			return $result;
432
		}
433
		return $fields;
434
	}
435
 
436
/**
437
 * Auxiliary function to quote matched `(Model.fields)` from a preg_replace_callback call
438
 * Quotes the fields in a function call.
439
 *
440
 * @param string $match matched string
441
 * @return string quoted string
442
 */
443
	protected function _quoteFunctionField($match) {
444
		$prepend = '';
445
		if (strpos($match[1], 'DISTINCT') !== false) {
446
			$prepend = 'DISTINCT ';
447
			$match[1] = trim(str_replace('DISTINCT', '', $match[1]));
448
		}
449
		$constant = preg_match('/^\d+|NULL|FALSE|TRUE$/i', $match[1]);
450
 
451
		if (!$constant && strpos($match[1], '.') === false) {
452
			$match[1] = $this->name($match[1]);
453
		} elseif (!$constant) {
454
			$parts = explode('.', $match[1]);
455
			if (!Hash::numeric($parts)) {
456
				$match[1] = $this->name($match[1]);
457
			}
458
		}
459
		return '(' . $prepend . $match[1] . ')';
460
	}
461
 
462
/**
463
 * Returns an array of the indexes in given datasource name.
464
 *
465
 * @param string $model Name of model to inspect
466
 * @return array Fields in table. Keys are column and unique
467
 */
468
	public function index($model) {
469
		$index = array();
470
		$table = $this->fullTableName($model, false, false);
471
		if ($table) {
472
			$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
473
			FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
474
			WHERE c.oid  = (
475
				SELECT c.oid
476
				FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
477
				WHERE c.relname ~ '^(" . $table . ")$'
478
					AND pg_catalog.pg_table_is_visible(c.oid)
479
					AND n.nspname ~ '^(" . $this->config['schema'] . ")$'
480
			)
481
			AND c.oid = i.indrelid AND i.indexrelid = c2.oid
482
			ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
483
			foreach ($indexes as $info) {
484
				$key = array_pop($info);
485
				if ($key['indisprimary']) {
486
					$key['relname'] = 'PRIMARY';
487
				}
488
				preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns);
489
				$parsedColumn = $indexColumns[1];
490
				if (strpos($indexColumns[1], ',') !== false) {
491
					$parsedColumn = explode(', ', $indexColumns[1]);
492
				}
493
				$index[$key['relname']]['unique'] = $key['indisunique'];
494
				$index[$key['relname']]['column'] = $parsedColumn;
495
			}
496
		}
497
		return $index;
498
	}
499
 
500
/**
501
 * Alter the Schema of a table.
502
 *
503
 * @param array $compare Results of CakeSchema::compare()
504
 * @param string $table name of the table
505
 * @return array
506
 */
507
	public function alterSchema($compare, $table = null) {
508
		if (!is_array($compare)) {
509
			return false;
510
		}
511
		$out = '';
512
		$colList = array();
513
		foreach ($compare as $curTable => $types) {
514
			$indexes = $colList = array();
515
			if (!$table || $table === $curTable) {
516
				$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
517
				foreach ($types as $type => $column) {
518
					if (isset($column['indexes'])) {
519
						$indexes[$type] = $column['indexes'];
520
						unset($column['indexes']);
521
					}
522
					switch ($type) {
523
						case 'add':
524
							foreach ($column as $field => $col) {
525
								$col['name'] = $field;
526
								$colList[] = 'ADD COLUMN ' . $this->buildColumn($col);
527
							}
528
							break;
529
						case 'drop':
530
							foreach ($column as $field => $col) {
531
								$col['name'] = $field;
532
								$colList[] = 'DROP COLUMN ' . $this->name($field);
533
							}
534
							break;
535
						case 'change':
536
							$schema = $this->describe($curTable);
537
							foreach ($column as $field => $col) {
538
								if (!isset($col['name'])) {
539
									$col['name'] = $field;
540
								}
541
								$original = $schema[$field];
542
								$fieldName = $this->name($field);
543
 
544
								$default = isset($col['default']) ? $col['default'] : null;
545
								$nullable = isset($col['null']) ? $col['null'] : null;
546
								$boolToInt = $original['type'] === 'boolean' && $col['type'] === 'integer';
547
								unset($col['default'], $col['null']);
548
								if ($field !== $col['name']) {
549
									$newName = $this->name($col['name']);
550
									$out .= "\tRENAME {$fieldName} TO {$newName};\n";
551
									$out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
552
									$fieldName = $newName;
553
								}
554
 
555
								if ($boolToInt) {
556
									$colList[] = 'ALTER COLUMN ' . $fieldName . '  SET DEFAULT NULL';
557
									$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)) . ' USING CASE WHEN TRUE THEN 1 ELSE 0 END';
558
								} else {
559
									$colList[] = 'ALTER COLUMN ' . $fieldName . ' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col));
560
								}
561
 
562
								if (isset($nullable)) {
563
									$nullable = ($nullable) ? 'DROP NOT NULL' : 'SET NOT NULL';
564
									$colList[] = 'ALTER COLUMN ' . $fieldName . '  ' . $nullable;
565
								}
566
 
567
								if (isset($default)) {
568
									if (!$boolToInt) {
569
										$colList[] = 'ALTER COLUMN ' . $fieldName . '  SET DEFAULT ' . $this->value($default, $col['type']);
570
									}
571
								} else {
572
									$colList[] = 'ALTER COLUMN ' . $fieldName . '  DROP DEFAULT';
573
								}
574
 
575
							}
576
							break;
577
					}
578
				}
579
				if (isset($indexes['drop']['PRIMARY'])) {
580
					$colList[] = 'DROP CONSTRAINT ' . $curTable . '_pkey';
581
				}
582
				if (isset($indexes['add']['PRIMARY'])) {
583
					$cols = $indexes['add']['PRIMARY']['column'];
584
					if (is_array($cols)) {
585
						$cols = implode(', ', $cols);
586
					}
587
					$colList[] = 'ADD PRIMARY KEY (' . $cols . ')';
588
				}
589
 
590
				if (!empty($colList)) {
591
					$out .= "\t" . implode(",\n\t", $colList) . ";\n\n";
592
				} else {
593
					$out = '';
594
				}
595
				$out .= implode(";\n\t", $this->_alterIndexes($curTable, $indexes));
596
			}
597
		}
598
		return $out;
599
	}
600
 
601
/**
602
 * Generate PostgreSQL index alteration statements for a table.
603
 *
604
 * @param string $table Table to alter indexes for
605
 * @param array $indexes Indexes to add and drop
606
 * @return array Index alteration statements
607
 */
608
	protected function _alterIndexes($table, $indexes) {
609
		$alter = array();
610
		if (isset($indexes['drop'])) {
611
			foreach ($indexes['drop'] as $name => $value) {
612
				$out = 'DROP ';
613
				if ($name === 'PRIMARY') {
614
					continue;
615
				} else {
616
					$out .= 'INDEX ' . $name;
617
				}
618
				$alter[] = $out;
619
			}
620
		}
621
		if (isset($indexes['add'])) {
622
			foreach ($indexes['add'] as $name => $value) {
623
				$out = 'CREATE ';
624
				if ($name === 'PRIMARY') {
625
					continue;
626
				} else {
627
					if (!empty($value['unique'])) {
628
						$out .= 'UNIQUE ';
629
					}
630
					$out .= 'INDEX ';
631
				}
632
				if (is_array($value['column'])) {
633
					$out .= $name . ' ON ' . $table . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
634
				} else {
635
					$out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')';
636
				}
637
				$alter[] = $out;
638
			}
639
		}
640
		return $alter;
641
	}
642
 
643
/**
644
 * Returns a limit statement in the correct format for the particular database.
645
 *
646
 * @param int $limit Limit of results returned
647
 * @param int $offset Offset from which to start results
648
 * @return string SQL limit/offset statement
649
 */
650
	public function limit($limit, $offset = null) {
651
		if ($limit) {
652
			$rt = sprintf(' LIMIT %u', $limit);
653
			if ($offset) {
654
				$rt .= sprintf(' OFFSET %u', $offset);
655
			}
656
			return $rt;
657
		}
658
		return null;
659
	}
660
 
661
/**
662
 * Converts database-layer column types to basic types
663
 *
664
 * @param string $real Real database-layer column type (i.e. "varchar(255)")
665
 * @return string Abstract column type (i.e. "string")
666
 */
667
	public function column($real) {
668
		if (is_array($real)) {
669
			$col = $real['name'];
670
			if (isset($real['limit'])) {
671
				$col .= '(' . $real['limit'] . ')';
672
			}
673
			return $col;
674
		}
675
 
676
		$col = str_replace(')', '', $real);
677
 
678
		if (strpos($col, '(') !== false) {
679
			list($col, $limit) = explode('(', $col);
680
		}
681
 
682
		$floats = array(
683
			'float', 'float4', 'float8', 'double', 'double precision', 'real'
684
		);
685
 
686
		switch (true) {
687
			case (in_array($col, array('date', 'time', 'inet', 'boolean'))):
688
				return $col;
689
			case (strpos($col, 'timestamp') !== false):
690
				return 'datetime';
691
			case (strpos($col, 'time') === 0):
692
				return 'time';
693
			case ($col === 'bigint'):
694
				return 'biginteger';
695
			case (strpos($col, 'int') !== false && $col !== 'interval'):
696
				return 'integer';
697
			case (strpos($col, 'char') !== false || $col === 'uuid'):
698
				return 'string';
699
			case (strpos($col, 'text') !== false):
700
				return 'text';
701
			case (strpos($col, 'bytea') !== false):
702
				return 'binary';
703
			case ($col === 'decimal' || $col === 'numeric'):
704
				return 'decimal';
705
			case (in_array($col, $floats)):
706
				return 'float';
707
			default:
708
				return 'text';
709
		}
710
	}
711
 
712
/**
713
 * Gets the length of a database-native column description, or null if no length
714
 *
715
 * @param string $real Real database-layer column type (i.e. "varchar(255)")
716
 * @return int An integer representing the length of the column
717
 */
718
	public function length($real) {
719
		$col = str_replace(array(')', 'unsigned'), '', $real);
720
		$limit = null;
721
 
722
		if (strpos($col, '(') !== false) {
723
			list($col, $limit) = explode('(', $col);
724
		}
725
		if ($col === 'uuid') {
726
			return 36;
727
		}
728
		if ($limit) {
729
			return intval($limit);
730
		}
731
		return null;
732
	}
733
 
734
/**
735
 * resultSet method
736
 *
737
 * @param array &$results The results
738
 * @return void
739
 */
740
	public function resultSet(&$results) {
741
		$this->map = array();
742
		$numFields = $results->columnCount();
743
		$index = 0;
744
		$j = 0;
745
 
746
		while ($j < $numFields) {
747
			$column = $results->getColumnMeta($j);
748
			if (strpos($column['name'], '__')) {
749
				list($table, $name) = explode('__', $column['name']);
750
				$this->map[$index++] = array($table, $name, $column['native_type']);
751
			} else {
752
				$this->map[$index++] = array(0, $column['name'], $column['native_type']);
753
			}
754
			$j++;
755
		}
756
	}
757
 
758
/**
759
 * Fetches the next row from the current result set
760
 *
761
 * @return array
762
 */
763
	public function fetchResult() {
764
		if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
765
			$resultRow = array();
766
 
767
			foreach ($this->map as $index => $meta) {
768
				list($table, $column, $type) = $meta;
769
 
770
				switch ($type) {
771
					case 'bool':
772
						$resultRow[$table][$column] = $row[$index] === null ? null : $this->boolean($row[$index]);
773
						break;
774
					case 'binary':
775
					case 'bytea':
776
						$resultRow[$table][$column] = $row[$index] === null ? null : stream_get_contents($row[$index]);
777
						break;
778
					default:
779
						$resultRow[$table][$column] = $row[$index];
780
				}
781
			}
782
			return $resultRow;
783
		}
784
		$this->_result->closeCursor();
785
		return false;
786
	}
787
 
788
/**
789
 * Translates between PHP boolean values and PostgreSQL boolean values
790
 *
791
 * @param mixed $data Value to be translated
792
 * @param bool $quote true to quote a boolean to be used in a query, false to return the boolean value
793
 * @return bool Converted boolean value
794
 */
795
	public function boolean($data, $quote = false) {
796
		switch (true) {
797
			case ($data === true || $data === false):
798
				$result = $data;
799
				break;
800
			case ($data === 't' || $data === 'f'):
801
				$result = ($data === 't');
802
				break;
803
			case ($data === 'true' || $data === 'false'):
804
				$result = ($data === 'true');
805
				break;
806
			case ($data === 'TRUE' || $data === 'FALSE'):
807
				$result = ($data === 'TRUE');
808
				break;
809
			default:
810
				$result = (bool)$data;
811
		}
812
 
813
		if ($quote) {
814
			return ($result) ? 'TRUE' : 'FALSE';
815
		}
816
		return (bool)$result;
817
	}
818
 
819
/**
820
 * Sets the database encoding
821
 *
822
 * @param mixed $enc Database encoding
823
 * @return bool True on success, false on failure
824
 */
825
	public function setEncoding($enc) {
826
		return $this->_execute('SET NAMES ' . $this->value($enc)) !== false;
827
	}
828
 
829
/**
830
 * Gets the database encoding
831
 *
832
 * @return string The database encoding
833
 */
834
	public function getEncoding() {
835
		$result = $this->_execute('SHOW client_encoding')->fetch();
836
		if ($result === false) {
837
			return false;
838
		}
839
		return (isset($result['client_encoding'])) ? $result['client_encoding'] : false;
840
	}
841
 
842
/**
843
 * Generate a Postgres-native column schema string
844
 *
845
 * @param array $column An array structured like the following:
846
 *                      array('name'=>'value', 'type'=>'value'[, options]),
847
 *                      where options can be 'default', 'length', or 'key'.
848
 * @return string
849
 */
850
	public function buildColumn($column) {
851
		$col = $this->columns[$column['type']];
852
		if (!isset($col['length']) && !isset($col['limit'])) {
853
			unset($column['length']);
854
		}
855
		$out = parent::buildColumn($column);
856
 
857
		$out = preg_replace(
858
			'/integer\([0-9]+\)/',
859
			'integer',
860
			$out
861
		);
862
		$out = preg_replace(
863
			'/bigint\([0-9]+\)/',
864
			'bigint',
865
			$out
866
		);
867
 
868
		$out = str_replace('integer serial', 'serial', $out);
869
		$out = str_replace('bigint serial', 'bigserial', $out);
870
		if (strpos($out, 'timestamp DEFAULT')) {
871
			if (isset($column['null']) && $column['null']) {
872
				$out = str_replace('DEFAULT NULL', '', $out);
873
			} else {
874
				$out = str_replace('DEFAULT NOT NULL', '', $out);
875
			}
876
		}
877
		if (strpos($out, 'DEFAULT DEFAULT')) {
878
			if (isset($column['null']) && $column['null']) {
879
				$out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
880
			} elseif (in_array($column['type'], array('integer', 'float'))) {
881
				$out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
882
			} elseif ($column['type'] === 'boolean') {
883
				$out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
884
			}
885
		}
886
		return $out;
887
	}
888
 
889
/**
890
 * Format indexes for create table
891
 *
892
 * @param array $indexes The index to build
893
 * @param string $table The table name.
894
 * @return string
895
 */
896
	public function buildIndex($indexes, $table = null) {
897
		$join = array();
898
		if (!is_array($indexes)) {
899
			return array();
900
		}
901
		foreach ($indexes as $name => $value) {
902
			if ($name === 'PRIMARY') {
903
				$out = 'PRIMARY KEY  (' . $this->name($value['column']) . ')';
904
			} else {
905
				$out = 'CREATE ';
906
				if (!empty($value['unique'])) {
907
					$out .= 'UNIQUE ';
908
				}
909
				if (is_array($value['column'])) {
910
					$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
911
				} else {
912
					$value['column'] = $this->name($value['column']);
913
				}
914
				$out .= "INDEX {$name} ON {$table}({$value['column']});";
915
			}
916
			$join[] = $out;
917
		}
918
		return $join;
919
	}
920
 
921
/**
922
 * Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes
923
 *
924
 * @param string $type The query type.
925
 * @param array $data The array of data to render.
926
 * @return string
927
 */
928
	public function renderStatement($type, $data) {
929
		switch (strtolower($type)) {
930
			case 'schema':
931
				extract($data);
932
 
933
				foreach ($indexes as $i => $index) {
934
					if (preg_match('/PRIMARY KEY/', $index)) {
935
						unset($indexes[$i]);
936
						$columns[] = $index;
937
						break;
938
					}
939
				}
940
				$join = array('columns' => ",\n\t", 'indexes' => "\n");
941
 
942
				foreach (array('columns', 'indexes') as $var) {
943
					if (is_array(${$var})) {
944
						${$var} = implode($join[$var], array_filter(${$var}));
945
					}
946
				}
947
				return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
948
			default:
949
				return parent::renderStatement($type, $data);
950
		}
951
	}
952
 
953
/**
954
 * Gets the schema name
955
 *
956
 * @return string The schema name
957
 */
958
	public function getSchemaName() {
959
		return $this->config['schema'];
960
	}
961
 
962
/**
963
 * Check if the server support nested transactions
964
 *
965
 * @return bool
966
 */
967
	public function nestedTransactionSupported() {
968
		return $this->useNestedTransactions && version_compare($this->getVersion(), '8.0', '>=');
969
	}
970
 
971
}