00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036 class DboPostgres extends DboSource {
00037
00038
00039
00040
00041
00042
00043 var $description = "PostgreSQL DBO Driver";
00044
00045
00046
00047
00048
00049
00050 var $_commands = array(
00051 'begin' => 'BEGIN',
00052 'commit' => 'COMMIT',
00053 'rollback' => 'ROLLBACK'
00054 );
00055
00056
00057
00058
00059
00060
00061 var $_baseConfig = array(
00062 'connect' => 'pg_pconnect',
00063 'persistent' => true,
00064 'host' => 'localhost',
00065 'login' => 'root',
00066 'password' => '',
00067 'database' => 'cake',
00068 'schema' => 'public',
00069 'port' => 5432,
00070 'encoding' => ''
00071 );
00072
00073 var $columns = array(
00074 'primary_key' => array('name' => 'serial NOT NULL'),
00075 'string' => array('name' => 'varchar', 'limit' => '255'),
00076 'text' => array('name' => 'text'),
00077 'integer' => array('name' => 'integer', 'formatter' => 'intval'),
00078 'float' => array('name' => 'float', 'formatter' => 'floatval'),
00079 'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00080 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
00081 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
00082 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
00083 'binary' => array('name' => 'bytea'),
00084 'boolean' => array('name' => 'boolean'),
00085 'number' => array('name' => 'numeric'),
00086 'inet' => array('name' => 'inet')
00087 );
00088
00089 var $startQuote = '"';
00090
00091 var $endQuote = '"';
00092
00093
00094
00095
00096
00097
00098 var $_sequenceMap = array();
00099
00100
00101
00102
00103
00104 function connect() {
00105 $config = $this->config;
00106 $conn = "host='{$config['host']}' port='{$config['port']}' dbname='{$config['database']}' ";
00107 $conn .= "user='{$config['login']}' password='{$config['password']}'";
00108
00109 if (!$config['persistent']) {
00110 $this->connection = pg_connect($conn, PGSQL_CONNECT_FORCE_NEW);
00111 } else {
00112 $this->connection = pg_pconnect($conn);
00113 }
00114 $this->connected = false;
00115
00116 if ($this->connection) {
00117 $this->connected = true;
00118 $this->_execute("SET search_path TO " . $config['schema']);
00119 }
00120 if (!empty($config['encoding'])) {
00121 $this->setEncoding($config['encoding']);
00122 }
00123 return $this->connected;
00124 }
00125
00126
00127
00128
00129
00130 function disconnect() {
00131 if ($this->hasResult()) {
00132 pg_free_result($this->_result);
00133 }
00134 if (is_resource($this->connection)) {
00135 $this->connected = !pg_close($this->connection);
00136 } else {
00137 $this->connected = false;
00138 }
00139 return !$this->connected;
00140 }
00141
00142
00143
00144
00145
00146
00147 function _execute($sql) {
00148 return pg_query($this->connection, $sql);
00149 }
00150
00151
00152
00153
00154
00155 function listSources() {
00156 $cache = parent::listSources();
00157
00158 if ($cache != null) {
00159 return $cache;
00160 }
00161
00162 $schema = $this->config['schema'];
00163 $sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = '{$schema}';";
00164 $result = $this->fetchAll($sql, false);
00165
00166 if (!$result) {
00167 return array();
00168 } else {
00169 $tables = array();
00170
00171 foreach ($result as $item) {
00172 $tables[] = $item[0]['name'];
00173 }
00174
00175 parent::listSources($tables);
00176 return $tables;
00177 }
00178 }
00179
00180
00181
00182
00183
00184
00185 function &describe(&$model) {
00186 $fields = parent::describe($model);
00187 $table = $this->fullTableName($model, false);
00188 $this->_sequenceMap[$table] = array();
00189
00190 if ($fields === null) {
00191 $cols = $this->fetchAll(
00192 "SELECT DISTINCT column_name AS name, data_type AS type, is_nullable AS null,
00193 column_default AS default, ordinal_position AS position, character_maximum_length AS char_length,
00194 character_octet_length AS oct_length FROM information_schema.columns
00195 WHERE table_name = " . $this->value($table) . " AND table_schema = " .
00196 $this->value($this->config['schema'])." ORDER BY position",
00197 false
00198 );
00199
00200 foreach ($cols as $column) {
00201 $colKey = array_keys($column);
00202
00203 if (isset($column[$colKey[0]]) && !isset($column[0])) {
00204 $column[0] = $column[$colKey[0]];
00205 }
00206
00207 if (isset($column[0])) {
00208 $c = $column[0];
00209
00210 if (!empty($c['char_length'])) {
00211 $length = intval($c['char_length']);
00212 } elseif (!empty($c['oct_length'])) {
00213 $length = intval($c['oct_length']);
00214 } else {
00215 $length = $this->length($c['type']);
00216 }
00217 $fields[$c['name']] = array(
00218 'type' => $this->column($c['type']),
00219 'null' => ($c['null'] == 'NO' ? false : true),
00220 'default' => preg_replace(
00221 "/^'(.*)'$/",
00222 "$1",
00223 preg_replace('/::.*/', '', $c['default'])
00224 ),
00225 'length' => $length
00226 );
00227 if ($c['name'] == $model->primaryKey) {
00228 $fields[$c['name']]['key'] = 'primary';
00229 if ($fields[$c['name']]['type'] !== 'string') {
00230 $fields[$c['name']]['length'] = 11;
00231 }
00232 }
00233 if (
00234 $fields[$c['name']]['default'] == 'NULL' ||
00235 preg_match('/nextval\([\'"]?([\w.]+)/', $c['default'], $seq)
00236 ) {
00237 $fields[$c['name']]['default'] = null;
00238 if (!empty($seq) && isset($seq[1])) {
00239 $this->_sequenceMap[$table][$c['name']] = $seq[1];
00240 }
00241 }
00242 }
00243 }
00244 $this->__cacheDescription($table, $fields);
00245 }
00246 if (isset($model->sequence)) {
00247 $this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;
00248 }
00249 return $fields;
00250 }
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260 function value($data, $column = null, $read = true) {
00261
00262 $parent = parent::value($data, $column);
00263 if ($parent != null) {
00264 return $parent;
00265 }
00266
00267 if ($data === null) {
00268 return 'NULL';
00269 }
00270 if (empty($column)) {
00271 $column = $this->introspectType($data);
00272 }
00273
00274 switch($column) {
00275 case 'inet':
00276 case 'float':
00277 case 'integer':
00278 case 'date':
00279 case 'datetime':
00280 case 'timestamp':
00281 if ($data === '') {
00282 return $read ? 'NULL' : 'DEFAULT';
00283 }
00284 case 'binary':
00285 $data = pg_escape_bytea($data);
00286 break;
00287 case 'boolean':
00288 if ($data === true || $data === 't' || $data === 'true') {
00289 return 'TRUE';
00290 } elseif ($data === false || $data === 'f' || $data === 'false') {
00291 return 'FALSE';
00292 }
00293 return (!empty($data) ? 'TRUE' : 'FALSE');
00294 break;
00295 default:
00296 $data = pg_escape_string($data);
00297 break;
00298 }
00299 return "'" . $data . "'";
00300 }
00301
00302
00303
00304
00305
00306 function lastError() {
00307 $error = pg_last_error($this->connection);
00308 return ($error) ? $error : null;
00309 }
00310
00311
00312
00313
00314
00315 function lastAffected() {
00316 return ($this->_result) ? pg_affected_rows($this->_result) : false;
00317 }
00318
00319
00320
00321
00322
00323
00324 function lastNumRows() {
00325 return ($this->_result) ? pg_num_rows($this->_result) : false;
00326 }
00327
00328
00329
00330
00331
00332
00333
00334 function lastInsertId($source, $field = 'id') {
00335 $seq = $this->getSequence($source, $field);
00336 $data = $this->fetchRow("SELECT currval('{$seq}') as max");
00337 return $data[0]['max'];
00338 }
00339
00340
00341
00342
00343
00344
00345
00346 function getSequence($table, $field = 'id') {
00347 if (is_object($table)) {
00348 $table = $this->fullTableName($table, false);
00349 }
00350 if (isset($this->_sequenceMap[$table]) && isset($this->_sequenceMap[$table][$field])) {
00351 return $this->_sequenceMap[$table][$field];
00352 } else {
00353 return "{$table}_{$field}_seq";
00354 }
00355 }
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365 function truncate($table, $reset = 0) {
00366 if (parent::truncate($table)) {
00367 $table = $this->fullTableName($table, false);
00368 if (isset($this->_sequenceMap[$table]) && $reset !== 1) {
00369 foreach ($this->_sequenceMap[$table] as $field => $sequence) {
00370 if ($reset === 0) {
00371 $this->execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1");
00372 } elseif ($reset === -1) {
00373 $this->execute("DROP SEQUENCE IF EXISTS \"{$sequence}\"");
00374 }
00375 }
00376 }
00377 return true;
00378 }
00379 return false;
00380 }
00381
00382
00383
00384
00385
00386
00387 function name($data) {
00388 if (is_string($data)) {
00389 $data = str_replace('"__"', '__', $data);
00390 }
00391 return parent::name($data);
00392 }
00393
00394
00395
00396
00397
00398
00399
00400
00401 function fields(&$model, $alias = null, $fields = array(), $quote = true) {
00402 if (empty($alias)) {
00403 $alias = $model->alias;
00404 }
00405 $fields = parent::fields($model, $alias, $fields, false);
00406
00407 if (!$quote) {
00408 return $fields;
00409 }
00410 $count = count($fields);
00411
00412 if ($count >= 1 && $fields[0] != '*' && strpos($fields[0], 'COUNT(*)') === false) {
00413 for ($i = 0; $i < $count; $i++) {
00414 if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) {
00415 $prepend = '';
00416 if (strpos($fields[$i], 'DISTINCT') !== false) {
00417 $prepend = 'DISTINCT ';
00418 $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
00419 }
00420
00421 if (strrpos($fields[$i], '.') === false) {
00422 $fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
00423 } else {
00424 $build = explode('.', $fields[$i]);
00425 $fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
00426 }
00427 }
00428 }
00429 }
00430 return $fields;
00431 }
00432
00433
00434
00435
00436
00437
00438 function index($model) {
00439 $index = array();
00440 $table = $this->fullTableName($model, false);
00441 if ($table) {
00442 $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
00443 FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
00444 WHERE c.oid = (
00445 SELECT c.oid
00446 FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
00447 WHERE c.relname ~ '^(" . $table . ")$'
00448 AND pg_catalog.pg_table_is_visible(c.oid)
00449 AND n.nspname ~ '^(" . $this->config['schema'] . ")$'
00450 )
00451 AND c.oid = i.indrelid AND i.indexrelid = c2.oid
00452 ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false);
00453 foreach ($indexes as $i => $info) {
00454 $key = array_pop($info);
00455 if ($key['indisprimary']) {
00456 $key['relname'] = 'PRIMARY';
00457 }
00458 $col = array();
00459 preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns);
00460 $parsedColumn = $indexColumns[1];
00461 if (strpos($indexColumns[1], ',') !== false) {
00462 $parsedColumn = explode(', ', $indexColumns[1]);
00463 }
00464 $index[$key['relname']]['unique'] = $key['indisunique'];
00465 $index[$key['relname']]['column'] = $parsedColumn;
00466 }
00467 }
00468 return $index;
00469 }
00470
00471
00472
00473
00474
00475
00476
00477
00478 function alterSchema($compare, $table = null) {
00479 if (!is_array($compare)) {
00480 return false;
00481 }
00482 $out = '';
00483 $colList = array();
00484 foreach ($compare as $curTable => $types) {
00485 $indexes = array();
00486 if (!$table || $table == $curTable) {
00487 $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n";
00488 foreach ($types as $type => $column) {
00489 if (isset($column['indexes'])) {
00490 $indexes[$type] = $column['indexes'];
00491 unset($column['indexes']);
00492 }
00493 switch ($type) {
00494 case 'add':
00495 foreach ($column as $field => $col) {
00496 $col['name'] = $field;
00497 $alter = 'ADD COLUMN '.$this->buildColumn($col);
00498 if (isset($col['after'])) {
00499 $alter .= ' AFTER '. $this->name($col['after']);
00500 }
00501 $colList[] = $alter;
00502 }
00503 break;
00504 case 'drop':
00505 foreach ($column as $field => $col) {
00506 $col['name'] = $field;
00507 $colList[] = 'DROP COLUMN '.$this->name($field);
00508 }
00509 break;
00510 case 'change':
00511 foreach ($column as $field => $col) {
00512 if (!isset($col['name'])) {
00513 $col['name'] = $field;
00514 }
00515 $fieldName = $this->name($field);
00516 $colList[] = 'ALTER COLUMN '. $fieldName .' TYPE ' . str_replace($fieldName, '', $this->buildColumn($col));
00517 }
00518 break;
00519 }
00520 }
00521 if (isset($indexes['drop']['PRIMARY'])) {
00522 $colList[] = 'DROP CONSTRAINT ' . $curTable . '_pkey';
00523 }
00524 if (isset($indexes['add']['PRIMARY'])) {
00525 $cols = $indexes['add']['PRIMARY']['column'];
00526 if (is_array($cols)) {
00527 $cols = implode(', ', $cols);
00528 }
00529 $colList[] = 'ADD PRIMARY KEY (' . $cols . ')';
00530 }
00531
00532 if (!empty($colList)) {
00533 $out .= "\t" . join(",\n\t", $colList) . ";\n\n";
00534 } else {
00535 $out = '';
00536 }
00537 $out .= join(";\n\t", $this->_alterIndexes($curTable, $indexes)) . ";";
00538 }
00539 }
00540 return $out;
00541 }
00542
00543
00544
00545
00546
00547
00548
00549 function _alterIndexes($table, $indexes) {
00550 $alter = array();
00551 if (isset($indexes['drop'])) {
00552 foreach($indexes['drop'] as $name => $value) {
00553 $out = 'DROP ';
00554 if ($name == 'PRIMARY') {
00555 continue;
00556 } else {
00557 $out .= 'INDEX ' . $name;
00558 }
00559 $alter[] = $out;
00560 }
00561 }
00562 if (isset($indexes['add'])) {
00563 foreach ($indexes['add'] as $name => $value) {
00564 $out = 'CREATE ';
00565 if ($name == 'PRIMARY') {
00566 continue;
00567 } else {
00568 if (!empty($value['unique'])) {
00569 $out .= 'UNIQUE ';
00570 }
00571 $out .= 'INDEX ';
00572 }
00573 if (is_array($value['column'])) {
00574 $out .= $name . ' ON ' . $table . ' (' . join(', ', array_map(array(&$this, 'name'), $value['column'])) . ')';
00575 } else {
00576 $out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')';
00577 }
00578 $alter[] = $out;
00579 }
00580 }
00581 return $alter;
00582 }
00583
00584
00585
00586
00587
00588
00589
00590 function limit($limit, $offset = null) {
00591 if ($limit) {
00592 $rt = '';
00593 if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
00594 $rt = ' LIMIT';
00595 }
00596
00597 $rt .= ' ' . $limit;
00598 if ($offset) {
00599 $rt .= ' OFFSET ' . $offset;
00600 }
00601
00602 return $rt;
00603 }
00604 return null;
00605 }
00606
00607
00608
00609
00610
00611
00612 function column($real) {
00613 if (is_array($real)) {
00614 $col = $real['name'];
00615 if (isset($real['limit'])) {
00616 $col .= '(' . $real['limit'] . ')';
00617 }
00618 return $col;
00619 }
00620
00621 $col = str_replace(')', '', $real);
00622 $limit = null;
00623
00624 if (strpos($col, '(') !== false) {
00625 list($col, $limit) = explode('(', $col);
00626 }
00627
00628 $floats = array(
00629 'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'real', 'numeric'
00630 );
00631
00632 switch (true) {
00633 case (in_array($col, array('date', 'time', 'inet', 'boolean'))):
00634 return $col;
00635 case (strpos($col, 'timestamp') !== false):
00636 return 'datetime';
00637 case (strpos($col, 'time') === 0):
00638 return 'time';
00639 case (strpos($col, 'int') !== false && $col != 'interval'):
00640 return 'integer';
00641 case (strpos($col, 'char') !== false || $col == 'uuid'):
00642 return 'string';
00643 case (strpos($col, 'text') !== false):
00644 return 'text';
00645 case (strpos($col, 'bytea') !== false):
00646 return 'binary';
00647 case (in_array($col, $floats)):
00648 return 'float';
00649 default:
00650 return 'text';
00651 break;
00652 }
00653 }
00654
00655
00656
00657
00658
00659
00660 function length($real) {
00661 $col = str_replace(array(')', 'unsigned'), '', $real);
00662 $limit = null;
00663
00664 if (strpos($col, '(') !== false) {
00665 list($col, $limit) = explode('(', $col);
00666 }
00667 if ($col == 'uuid') {
00668 return 36;
00669 }
00670 if ($limit != null) {
00671 return intval($limit);
00672 }
00673 return null;
00674 }
00675
00676
00677
00678
00679
00680 function resultSet(&$results) {
00681 $this->results =& $results;
00682 $this->map = array();
00683 $num_fields = pg_num_fields($results);
00684 $index = 0;
00685 $j = 0;
00686
00687 while ($j < $num_fields) {
00688 $columnName = pg_field_name($results, $j);
00689
00690 if (strpos($columnName, '__')) {
00691 $parts = explode('__', $columnName);
00692 $this->map[$index++] = array($parts[0], $parts[1]);
00693 } else {
00694 $this->map[$index++] = array(0, $columnName);
00695 }
00696 $j++;
00697 }
00698 }
00699
00700
00701
00702
00703
00704 function fetchResult() {
00705 if ($row = pg_fetch_row($this->results)) {
00706 $resultRow = array();
00707
00708 foreach ($row as $index => $field) {
00709 list($table, $column) = $this->map[$index];
00710 $type = pg_field_type($this->results, $index);
00711
00712 switch ($type) {
00713 case 'bool':
00714 $resultRow[$table][$column] = $this->boolean($row[$index], false);
00715 break;
00716 case 'binary':
00717 case 'bytea':
00718 $resultRow[$table][$column] = pg_unescape_bytea($row[$index]);
00719 break;
00720 default:
00721 $resultRow[$table][$column] = $row[$index];
00722 break;
00723 }
00724 }
00725 return $resultRow;
00726 } else {
00727 return false;
00728 }
00729 }
00730
00731
00732
00733
00734
00735
00736
00737 function boolean($data, $quote = true) {
00738 switch (true) {
00739 case ($data === true || $data === false):
00740 return $data;
00741 case ($data === 't' || $data === 'f'):
00742 return ($data === 't');
00743 case ($data === 'true' || $data === 'false'):
00744 return ($data === 'true');
00745 case ($data === 'TRUE' || $data === 'FALSE'):
00746 return ($data === 'TRUE');
00747 default:
00748 return (bool)$data;
00749 break;
00750 }
00751 }
00752
00753
00754
00755
00756
00757
00758 function setEncoding($enc) {
00759 return pg_set_client_encoding($this->connection, $enc) == 0;
00760 }
00761
00762
00763
00764
00765
00766 function getEncoding() {
00767 return pg_client_encoding($this->connection);
00768 }
00769
00770
00771
00772
00773
00774
00775
00776
00777 function buildColumn($column) {
00778 $col = $this->columns[$column['type']];
00779 if (!isset($col['length']) && !isset($col['limit'])) {
00780 unset($column['length']);
00781 }
00782 $out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column));
00783 $out = str_replace('integer serial', 'serial', $out);
00784 if (strpos($out, 'timestamp DEFAULT')) {
00785 if (isset($column['null']) && $column['null']) {
00786 $out = str_replace('DEFAULT NULL', '', $out);
00787 } else {
00788 $out = str_replace('DEFAULT NOT NULL', '', $out);
00789 }
00790 }
00791 if (strpos($out, 'DEFAULT DEFAULT')) {
00792 if (isset($column['null']) && $column['null']) {
00793 $out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out);
00794 } elseif (in_array($column['type'], array('integer', 'float'))) {
00795 $out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out);
00796 } elseif ($column['type'] == 'boolean') {
00797 $out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out);
00798 }
00799 }
00800 return $out;
00801 }
00802
00803
00804
00805
00806
00807
00808
00809 function buildIndex($indexes, $table = null) {
00810 $join = array();
00811 if (!is_array($indexes)) {
00812 return array();
00813 }
00814 foreach ($indexes as $name => $value) {
00815 if ($name == 'PRIMARY') {
00816 $out = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
00817 } else {
00818 $out = 'CREATE ';
00819 if (!empty($value['unique'])) {
00820 $out .= 'UNIQUE ';
00821 }
00822 if (is_array($value['column'])) {
00823 $value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
00824 } else {
00825 $value['column'] = $this->name($value['column']);
00826 }
00827 $out .= "INDEX {$name} ON {$table}({$value['column']});";
00828 }
00829 $join[] = $out;
00830 }
00831 return $join;
00832 }
00833
00834
00835
00836
00837
00838
00839
00840 function renderStatement($type, $data) {
00841 switch (strtolower($type)) {
00842 case 'schema':
00843 extract($data);
00844
00845 foreach ($indexes as $i => $index) {
00846 if (preg_match('/PRIMARY KEY/', $index)) {
00847 unset($indexes[$i]);
00848 $columns[] = $index;
00849 break;
00850 }
00851 }
00852 $join = array('columns' => ",\n\t", 'indexes' => "\n");
00853
00854 foreach (array('columns', 'indexes') as $var) {
00855 if (is_array(${$var})) {
00856 ${$var} = join($join[$var], array_filter(${$var}));
00857 }
00858 }
00859 return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}";
00860 break;
00861 default:
00862 return parent::renderStatement($type, $data);
00863 break;
00864 }
00865 }
00866 }
00867 ?>