MDB2
[ class tree: MDB2 ] [ index: MDB2 ] [ all elements ]

Source for file pgsql.php

Documentation is available at pgsql.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP versions 4 and 5                                                 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox,                 |
  6. // | Stig. S. Bakken, Lukas Smith                                         |
  7. // | All rights reserved.                                                 |
  8. // +----------------------------------------------------------------------+
  9. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
  10. // | API as well as database abstraction for PHP applications.            |
  11. // | This LICENSE is in the BSD license style.                            |
  12. // |                                                                      |
  13. // | Redistribution and use in source and binary forms, with or without   |
  14. // | modification, are permitted provided that the following conditions   |
  15. // | are met:                                                             |
  16. // |                                                                      |
  17. // | Redistributions of source code must retain the above copyright       |
  18. // | notice, this list of conditions and the following disclaimer.        |
  19. // |                                                                      |
  20. // | Redistributions in binary form must reproduce the above copyright    |
  21. // | notice, this list of conditions and the following disclaimer in the  |
  22. // | documentation and/or other materials provided with the distribution. |
  23. // |                                                                      |
  24. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  25. // | Lukas Smith nor the names of his contributors may be used to endorse |
  26. // | or promote products derived from this software without specific prior|
  27. // | written permission.                                                  |
  28. // |                                                                      |
  29. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  30. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  31. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  32. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  33. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  34. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  35. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  36. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  37. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  38. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  39. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  40. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  41. // +----------------------------------------------------------------------+
  42. // | Author: Paul Cooper <pgc@ucecom.com>                                 |
  43. // +----------------------------------------------------------------------+
  44. //
  45. // $Id: pgsql.php,v 1.19 2005/04/19 12:53:42 lsmith Exp $
  46.  
  47. require_once 'MDB2/Driver/Reverse/Common.php';
  48.  
  49. /**
  50.  * MDB2 PostGreSQL driver for the schema reverse engineering module
  51.  *
  52.  * @package MDB2
  53.  * @category Database
  54.  * @author  Paul Cooper <pgc@ucecom.com>
  55.  */
  56. class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_common
  57. {
  58.     // {{{ getTableFieldDefinition()
  59.  
  60.     /**
  61.      * get the stucture of a field into an array
  62.      *
  63.      * @param string    $table         name of table that should be used in method
  64.      * @param string    $field_name     name of field that should be used in method
  65.      * @return mixed data array on success, a MDB2 error on failure
  66.      * @access public
  67.      */
  68.     function getTableFieldDefinition($table$field_name)
  69.     {
  70.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  71.         $result $db->loadModule('Datatype');
  72.         if (PEAR::isError($result)) {
  73.             return $result;
  74.         }
  75.  
  76.         $column $db->queryRow("SELECT
  77.                     attnum,attname,typname,attlen,attnotnull,
  78.                     atttypmod,usename,usesysid,pg_class.oid,relpages,
  79.                     reltuples,relhaspkey,relhasrules,relacl,adsrc
  80.                     FROM pg_class,pg_user,pg_type,
  81.                          pg_attribute left outer join pg_attrdef on
  82.                          pg_attribute.attrelid=pg_attrdef.adrelid
  83.                     WHERE (pg_class.relname='$table')
  84.                         and (pg_class.oid=pg_attribute.attrelid)
  85.                         and (pg_class.relowner=pg_user.usesysid)
  86.                         and (pg_attribute.atttypid=pg_type.oid)
  87.                         and attnum > 0
  88.                         and attname = '$field_name'
  89.                         ORDER BY attnum
  90.                         "nullMDB2_FETCHMODE_ASSOC);
  91.         if (PEAR::isError($column)) {
  92.             return $column;
  93.         }
  94.  
  95.         list($types$length$db->datatype->mapNativeDatatype($column);
  96.         if ($column['attnotnull'== 't'{
  97.             $notnull = true;
  98.         }
  99.         // todo .. check how default look like
  100.         if (!preg_match("/nextval\('([^']+)'/"$column['adsrc'])
  101.             && strlen($column['adsrc']> 2
  102.         {
  103.             $default substr($column['adsrc']1-1);
  104.         }
  105.         $definition = array();
  106.         foreach ($types as $key => $type{
  107.             $definition[0][$key= array('type' => $type);
  108.             if (isset($notnull)) {
  109.                 $definition[0][$key]['notnull'= true;
  110.             }
  111.             if (isset($default)) {
  112.                 $definition[0][$key]['default'$default;
  113.             }
  114.             if (isset($length)) {
  115.                 $definition[0][$key]['length'$length;
  116.             }
  117.         }
  118.         if (preg_match("/nextval\('([^']+)'/"$column['adsrc']$nextvals)) {
  119.             $implicit_sequence = array();
  120.             $implicit_sequence['on'= array();
  121.             $implicit_sequence['on']['table'$table;
  122.             $implicit_sequence['on']['field'$field_name;
  123.             $definition[1]['name'$nextvals[1];
  124.             $definition[1]['definition'$implicit_sequence;
  125.         }
  126.  
  127.         // check that its not just a unique field
  128.         $query = "SELECT oid,indexrelid,indrelid,indkey,indisunique,indisprimary
  129.                 FROM pg_index, pg_class
  130.                 WHERE (pg_class.relname='$table') AND (pg_class.oid=pg_index.indrelid)";
  131.         if (PEAR::isError($indexes $db->queryRow($querynullMDB2_FETCHMODE_ASSOC))) {
  132.             return $indexes;
  133.         }
  134.         $indkeys explode(' '$indexes['indkey']);
  135.         if (in_array($column['attnum']$indkeys)
  136.             && $indexes['indisprimary'== 't'
  137.             && $indexes['indisunique'!= 't'
  138.         {
  139.             $query = "SELECT relname FROM pg_class WHERE oid={$indexes['indexrelid']}";
  140.             $index_name $db->queryOne($query);
  141.             if (PEAR::isError($index_name)) {
  142.                 return $index_name;
  143.             }
  144.             $implicit_index = array();
  145.             $implicit_index['unique'= true;
  146.             $implicit_index['fields'][$field_name$index_name;
  147.             $definition[2]['name'$field_name;
  148.             $definition[2]['definition'$implicit_index;
  149.         }
  150.         return $definition;
  151.     }
  152.  
  153.  
  154.     // }}}
  155.     // {{{ getTableIndexDefinition()
  156.     /**
  157.      * get the stucture of an index into an array
  158.      *
  159.      * @param string    $table      name of table that should be used in method
  160.      * @param string    $index_name name of index that should be used in method
  161.      * @return mixed data array on success, a MDB2 error on failure
  162.      * @access public
  163.      */
  164.     function getTableIndexDefinition($table$index_name)
  165.     {
  166.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  167.         $query = "SELECT * FROM pg_index, pg_class
  168.             WHERE (pg_class.relname='$index_name') AND (pg_class.oid=pg_index.indexrelid)";
  169.         $row $db->queryRow($querynullMDB2_FETCHMODE_ASSOC);
  170.         if (PEAR::isError($row)) {
  171.             return $row;
  172.         }
  173.         if ($row['relname'!= $index_name{
  174.             return $db->raiseError(MDB2_ERRORnullnull,
  175.                 'getTableIndexDefinition: it was not specified an existing table index');
  176.         }
  177.  
  178.         $db->loadModule('Manager');
  179.         $columns $db->manager->listTableFields($table);
  180.  
  181.         $definition = array();
  182.         if ($row['indisunique'== 't'{
  183.             $definition['unique'= true;
  184.         }
  185.  
  186.         $index_column_numbers explode(' '$row['indkey']);
  187.  
  188.         foreach ($index_column_numbers as $number{
  189.             $definition['fields'][$columns[($number - 1)]] = array('sorting' => 'ascending');
  190.         }
  191.         return $definition;
  192.     }
  193.  
  194.     // }}}
  195.     // {{{ tableInfo()
  196.  
  197.     /**
  198.      * Returns information about a table or a result set
  199.      *
  200.      * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  201.      * is a table name.
  202.      *
  203.      * @param object|string $result  MDB2_result object from a query or a
  204.      *                                  string containing the name of a table.
  205.      *                                  While this also accepts a query result
  206.      *                                  resource identifier, this behavior is
  207.      *                                  deprecated.
  208.      * @param int            $mode    a valid tableInfo mode
  209.      *
  210.      * @return array  an associative array with the information requested.
  211.      *                  A MDB2_Error object on failure.
  212.      *
  213.      * @see MDB2_common::tableInfo()
  214.      */
  215.     function tableInfo($result$mode = null)
  216.     {
  217.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  218.         if (is_string($result)) {
  219.             /*
  220.              * Probably received a table name.
  221.              * Create a result resource identifier.
  222.              */
  223.             $id $db->_doQuery("SELECT * FROM $result LIMIT 0");
  224.             if (PEAR::isError($id)) {
  225.                 return $id;
  226.             }
  227.             $got_string = true;
  228.         elseif (MDB2::isResultCommon($result)) {
  229.             /*
  230.              * Probably received a result object.
  231.              * Extract the result resource identifier.
  232.              */
  233.             $id $result->getResource();
  234.             $got_string = false;
  235.         else {
  236.             /*
  237.              * Probably received a result resource identifier.
  238.              * Copy it.
  239.              * Deprecated.  Here for compatibility only.
  240.              */
  241.             $id $result;
  242.             $got_string = false;
  243.         }
  244.  
  245.         if (!is_resource($id)) {
  246.             return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA);
  247.         }
  248.  
  249.         if ($db->options['portability'MDB2_PORTABILITY_LOWERCASE{
  250.             $case_func 'strtolower';
  251.         else {
  252.             $case_func 'strval';
  253.         }
  254.  
  255.         $count @pg_num_fields($id);
  256.         $res   = array();
  257.  
  258.         if ($mode{
  259.             $res['num_fields'$count;
  260.         }
  261.  
  262.         for ($i = 0; $i $count$i++{
  263.             $res[$i= array(
  264.                 'table' => $got_string $case_func($result'',
  265.                 'name'  => $case_func(@pg_field_name($id$i)),
  266.                 'type'  => @pg_field_type($id$i),
  267.                 'len'   => @pg_field_size($id$i),
  268.                 'flags' => $got_string
  269.                            ? $this->_pgFieldFlags($id$i$result)
  270.                            : '',
  271.             );
  272.             if ($mode MDB2_TABLEINFO_ORDER{
  273.                 $res['order'][$res[$i]['name']] $i;
  274.             }
  275.             if ($mode MDB2_TABLEINFO_ORDERTABLE{
  276.                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] $i;
  277.             }
  278.         }
  279.  
  280.         // free the result only if we were called on a table
  281.         if ($got_string{
  282.             @pg_free_result($id);
  283.         }
  284.         return $res;
  285.     }
  286.  
  287.     // }}}
  288.     // {{{ _pgFieldFlags()
  289.  
  290.     /**
  291.      * Get a column's flags
  292.      *
  293.      * Supports "not_null", "default_value", "primary_key", "unique_key"
  294.      * and "multiple_key".  The default value is passed through
  295.      * rawurlencode() in case there are spaces in it.
  296.      *
  297.      * @param int $resource   the PostgreSQL result identifier
  298.      * @param int $num_field  the field number
  299.      *
  300.      * @return string  the flags
  301.      *
  302.      * @access protected
  303.      */
  304.     function _pgFieldFlags($resource$num_field$table_name)
  305.     {
  306.         $db =$GLOBALS['_MDB2_databases'][$this->db_index];
  307.         $field_name @pg_field_name($resource$num_field);
  308.  
  309.         $result @pg_query($db->connection"SELECT f.attnotnull, f.atthasdef
  310.                                 FROM pg_attribute f, pg_class tab, pg_type typ
  311.                                 WHERE tab.relname = typ.typname
  312.                                 AND typ.typrelid = f.attrelid
  313.                                 AND f.attname = '$field_name'
  314.                                 AND tab.relname = '$table_name'");
  315.         if (@pg_num_rows($result> 0{
  316.             $row @pg_fetch_row($result0);
  317.             $flags  ($row[0== 't''not_null ' '';
  318.  
  319.             if ($row[1== 't'{
  320.                 $result @pg_query($db->connection"SELECT a.adsrc
  321.                                     FROM pg_attribute f, pg_class tab, pg_type typ, pg_attrdef a
  322.                                     WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid
  323.                                     AND f.attrelid = a.adrelid AND f.attname = '$field_name'
  324.                                     AND tab.relname = '$table_name' AND f.attnum = a.adnum");
  325.                 $row @pg_fetch_row($result0);
  326.                 $num preg_replace("/'(.*)'::\w+/""\\1"$row[0]);
  327.                 $flags .= 'default_' rawurlencode($num' ';
  328.             }
  329.         else {
  330.             $flags '';
  331.         }
  332.         $result @pg_query($db->connection"SELECT i.indisunique, i.indisprimary, i.indkey
  333.                                 FROM pg_attribute f, pg_class tab, pg_type typ, pg_index i
  334.                                 WHERE tab.relname = typ.typname
  335.                                 AND typ.typrelid = f.attrelid
  336.                                 AND f.attrelid = i.indrelid
  337.                                 AND f.attname = '$field_name'
  338.                                 AND tab.relname = '$table_name'");
  339.         $count @pg_num_rows($result);
  340.  
  341.         for ($i = 0; $i $count $i++{
  342.             $row @pg_fetch_row($result$i);
  343.             $keys explode(' '$row[2]);
  344.  
  345.             if (in_array($num_field + 1$keys)) {
  346.                 $flags .= ($row[0== 't' && $row[1== 'f''unique_key ' '';
  347.                 $flags .= ($row[1== 't''primary_key ' '';
  348.                 if (count($keys> 1)
  349.                     $flags .= 'multiple_key ';
  350.             }
  351.         }
  352.  
  353.         return trim($flags);
  354.     }
  355. }
  356. ?>

Documentation generated on Mon, 11 Mar 2019 14:20:23 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.