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.33 2005/12/15 22:52:56 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 =$this->getDBInstance();
  71.         if (PEAR::isError($db)) {
  72.             return $db;
  73.         }
  74.  
  75.         $result $db->loadModule('Datatype');
  76.         if (PEAR::isError($result)) {
  77.             return $result;
  78.         }
  79.  
  80.         $column $db->queryRow("SELECT
  81.                     attnum,attname,typname AS type,attlen AS length,attnotnull,
  82.                     atttypmod,usename,usesysid,pg_class.oid,relpages,
  83.                     reltuples,relhaspkey,relhasrules,relacl,adsrc
  84.                     FROM pg_class,pg_user,pg_type,
  85.                          pg_attribute left outer join pg_attrdef on
  86.                          pg_attribute.attrelid=pg_attrdef.adrelid
  87.                     WHERE (pg_class.relname='$table')
  88.                         and (pg_class.oid=pg_attribute.attrelid)
  89.                         and (pg_class.relowner=pg_user.usesysid)
  90.                         and (pg_attribute.atttypid=pg_type.oid)
  91.                         and attnum > 0
  92.                         and attname = '$field_name'
  93.                         ORDER BY attnum
  94.                         "nullMDB2_FETCHMODE_ASSOC);
  95.         if (PEAR::isError($column)) {
  96.             return $column;
  97.         }
  98.         list($types$length$unsigned$db->datatype->mapNativeDatatype($column);
  99.         $notnull = false;
  100.         if (array_key_exists('attnotnull'$column&& $column['attnotnull'== 't'{
  101.             $notnull = true;
  102.         }
  103.         $default = false;
  104.         // todo .. check how default look like
  105.         if (!preg_match("/nextval\('([^']+)'/"$column['adsrc'])
  106.             && strlen($column['adsrc']> 2
  107.         {
  108.             $default substr($column['adsrc']1-1);
  109.             if (is_null($default&& $notnull{
  110.                 $default '';
  111.             }
  112.         }
  113.         $autoincrement = false;
  114.         if (preg_match("/nextval\('([^']+)'/"$column['adsrc']$nextvals)) {
  115.             $autoincrement = true;
  116.         }
  117.         $definition = array();
  118.         foreach ($types as $key => $type{
  119.             $definition[$key= array(
  120.                 'type' => $type,
  121.                 'notnull' => $notnull,
  122.             );
  123.             if ($length > 0{
  124.                 $definition[$key]['length'$length;
  125.             }
  126.              if ($unsigned{
  127.                 $definition[$key]['unsigned'= true;
  128.             }
  129.             if ($default !== false{
  130.                 $definition[$key]['default'$default;
  131.             }
  132.             if ($autoincrement !== false{
  133.                 $definition[$key]['autoincrement'$autoincrement;
  134.             }
  135.         }
  136.         return $definition;
  137.     }
  138.  
  139.     // }}}
  140.     // {{{ getTableIndexDefinition()
  141.     /**
  142.      * get the stucture of an index into an array
  143.      *
  144.      * @param string    $table      name of table that should be used in method
  145.      * @param string    $index_name name of index that should be used in method
  146.      * @return mixed data array on success, a MDB2 error on failure
  147.      * @access public
  148.      */
  149.     function getTableIndexDefinition($table$index_name)
  150.     {
  151.         $db =$this->getDBInstance();
  152.         if (PEAR::isError($db)) {
  153.             return $db;
  154.         }
  155.  
  156.         $index_name $db->getIndexName($index_name);
  157.         $query = "SELECT relname, indisunique, indisprimary, indkey FROM pg_index, pg_class
  158.             WHERE pg_class.relname='$index_name' AND pg_class.oid=pg_index.indexrelid
  159.                AND indisunique != 't' AND indisprimary != 't'";
  160.         $row $db->queryRow($querynullMDB2_FETCHMODE_ASSOC);
  161.         if (PEAR::isError($row)) {
  162.             return $row;
  163.         }
  164.         if (!$row{
  165.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  166.                 'getTableIndexDefinition: it was not specified an existing table index');
  167.         }
  168.  
  169.         $db->loadModule('Manager');
  170.         $columns $db->manager->listTableFields($table);
  171.  
  172.         $definition = array();
  173.  
  174.         $index_column_numbers explode(' '$row['indkey']);
  175.  
  176.         foreach ($index_column_numbers as $number{
  177.             $definition['fields'][$columns[($number - 1)]] = array('sorting' => 'ascending');
  178.         }
  179.         return $definition;
  180.     }
  181.  
  182.     // }}}
  183.     // {{{ getTableConstraintDefinition()
  184.     /**
  185.      * get the stucture of a constraint into an array
  186.      *
  187.      * @param string    $table      name of table that should be used in method
  188.      * @param string    $index_name name of index that should be used in method
  189.      * @return mixed data array on success, a MDB2 error on failure
  190.      * @access public
  191.      */
  192.     function getTableConstraintDefinition($table$index_name)
  193.     {
  194.         $db =$this->getDBInstance();
  195.         if (PEAR::isError($db)) {
  196.             return $db;
  197.         }
  198.  
  199.         $index_name $db->getIndexName($index_name);
  200.         $query = "SELECT relname, indisunique, indisprimary, indkey FROM pg_index, pg_class
  201.             WHERE pg_class.relname='$index_name' AND pg_class.oid=pg_index.indexrelid
  202.               AND (indisunique = 't' OR indisprimary = 't')";
  203.         $row $db->queryRow($querynullMDB2_FETCHMODE_ASSOC);
  204.         if (PEAR::isError($row)) {
  205.             return $row;
  206.         }
  207.         if (!$row{
  208.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  209.                 'getTableConstraintDefinition: it was not specified an existing table constraint');
  210.         }
  211.  
  212.         $db->loadModule('Manager');
  213.         $columns $db->manager->listTableFields($table);
  214.  
  215.         $definition = array();
  216.         if ($row['indisprimary'== 't'{
  217.             $definition['primary'= true;
  218.         elseif ($row['indisunique'== 't'{
  219.             $definition['unique'= true;
  220.         }
  221.  
  222.         $index_column_numbers explode(' '$row['indkey']);
  223.  
  224.         foreach ($index_column_numbers as $number{
  225.             $definition['fields'][$columns[($number - 1)]] = array('sorting' => 'ascending');
  226.         }
  227.         return $definition;
  228.     }
  229.  
  230.     // }}}
  231.     // {{{ tableInfo()
  232.  
  233.     /**
  234.      * Returns information about a table or a result set
  235.      *
  236.      * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  237.      * is a table name.
  238.      *
  239.      * @param object|string $result  MDB2_result object from a query or a
  240.      *                                  string containing the name of a table.
  241.      *                                  While this also accepts a query result
  242.      *                                  resource identifier, this behavior is
  243.      *                                  deprecated.
  244.      * @param int            $mode    a valid tableInfo mode
  245.      *
  246.      * @return array  an associative array with the information requested.
  247.      *                  A MDB2_Error object on failure.
  248.      *
  249.      * @see MDB2_Driver_Common::tableInfo()
  250.      */
  251.     function tableInfo($result$mode = null)
  252.     {
  253.         $db =$this->getDBInstance();
  254.         if (PEAR::isError($db)) {
  255.             return $db;
  256.         }
  257.  
  258.         if (is_string($result)) {
  259.             /*
  260.              * Probably received a table name.
  261.              * Create a result resource identifier.
  262.              */
  263.             $id $db->_doQuery("SELECT * FROM $result LIMIT 0"false);
  264.             if (PEAR::isError($id)) {
  265.                 return $id;
  266.             }
  267.             $got_string = true;
  268.         elseif (MDB2::isResultCommon($result)) {
  269.             /*
  270.              * Probably received a result object.
  271.              * Extract the result resource identifier.
  272.              */
  273.             $id $result->getResource();
  274.             $got_string = false;
  275.         else {
  276.             /*
  277.              * Probably received a result resource identifier.
  278.              * Copy it.
  279.              * Deprecated.  Here for compatibility only.
  280.              */
  281.             $id $result;
  282.             $got_string = false;
  283.         }
  284.  
  285.         if (!is_resource($id)) {
  286.             return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA);
  287.         }
  288.  
  289.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  290.             if ($db->options['field_case'== CASE_LOWER{
  291.                 $case_func 'strtolower';
  292.             else {
  293.                 $case_func 'strtoupper';
  294.             }
  295.         else {
  296.             $case_func 'strval';
  297.         }
  298.  
  299.         $count @pg_num_fields($id);
  300.         $res   = array();
  301.  
  302.         if ($mode{
  303.             $res['num_fields'$count;
  304.         }
  305.  
  306.         $db->loadModule('Datatype');
  307.         for ($i = 0; $i $count$i++{
  308.             $res[$i= array(
  309.                 'table' => $got_string $case_func($result'',
  310.                 'name'  => $case_func(@pg_field_name($id$i)),
  311.                 'type'  => @pg_field_type($id$i),
  312.                 'length'   => @pg_field_size($id$i),
  313.                 'flags' => $got_string
  314.                            ? $this->_pgFieldFlags($id$i$result)
  315.                            : '',
  316.             );
  317.             $mdb2type_info $db->datatype->mapNativeDatatype($res[$i]);
  318.             $res[$i]['mdb2type'$mdb2type_info[0][0];
  319.             if ($mode MDB2_TABLEINFO_ORDER{
  320.                 $res['order'][$res[$i]['name']] $i;
  321.             }
  322.             if ($mode MDB2_TABLEINFO_ORDERTABLE{
  323.                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] $i;
  324.             }
  325.         }
  326.  
  327.         // free the result only if we were called on a table
  328.         if ($got_string{
  329.             @pg_free_result($id);
  330.         }
  331.         return $res;
  332.     }
  333.  
  334.     // }}}
  335.     // {{{ _pgFieldFlags()
  336.  
  337.     /**
  338.      * Get a column's flags
  339.      *
  340.      * Supports "not_null", "default_value", "primary_key", "unique_key"
  341.      * and "multiple_key".  The default value is passed through
  342.      * rawurlencode() in case there are spaces in it.
  343.      *
  344.      * @param int $resource   the PostgreSQL result identifier
  345.      * @param int $num_field  the field number
  346.      *
  347.      * @return string  the flags
  348.      *
  349.      * @access protected
  350.      */
  351.     function _pgFieldFlags($resource$num_field$table_name)
  352.     {
  353.         $db =$this->getDBInstance();
  354.         if (PEAR::isError($db)) {
  355.             return $db;
  356.         }
  357.  
  358.         $connection $db->getConnection();
  359.         if (PEAR::isError($connection)) {
  360.             return $connection;
  361.         }
  362.  
  363.         $field_name @pg_field_name($resource$num_field);
  364.  
  365.         $result @pg_query($connection"SELECT f.attnotnull, f.atthasdef
  366.                                 FROM pg_attribute f, pg_class tab, pg_type typ
  367.                                 WHERE tab.relname = typ.typname
  368.                                 AND typ.typrelid = f.attrelid
  369.                                 AND f.attname = '$field_name'
  370.                                 AND tab.relname = '$table_name'");
  371.         if (@pg_num_rows($result> 0{
  372.             $row @pg_fetch_row($result0);
  373.             $flags  ($row[0== 't''not_null ' '';
  374.  
  375.             if ($row[1== 't'{
  376.                 $result @pg_query($connection"SELECT a.adsrc
  377.                                     FROM pg_attribute f, pg_class tab, pg_type typ, pg_attrdef a
  378.                                     WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid
  379.                                     AND f.attrelid = a.adrelid AND f.attname = '$field_name'
  380.                                     AND tab.relname = '$table_name' AND f.attnum = a.adnum");
  381.                 $row @pg_fetch_row($result0);
  382.                 $num preg_replace("/'(.*)'::\w+/""\\1"$row[0]);
  383.                 $flags.= 'default_' rawurlencode($num' ';
  384.             }
  385.         else {
  386.             $flags '';
  387.         }
  388.         $result @pg_query($connection"SELECT i.indisunique, i.indisprimary, i.indkey
  389.                                 FROM pg_attribute f, pg_class tab, pg_type typ, pg_index i
  390.                                 WHERE tab.relname = typ.typname
  391.                                 AND typ.typrelid = f.attrelid
  392.                                 AND f.attrelid = i.indrelid
  393.                                 AND f.attname = '$field_name'
  394.                                 AND tab.relname = '$table_name'");
  395.         $count @pg_num_rows($result);
  396.  
  397.         for ($i = 0; $i $count $i++{
  398.             $row @pg_fetch_row($result$i);
  399.             $keys explode(' '$row[2]);
  400.  
  401.             if (in_array($num_field + 1$keys)) {
  402.                 $flags.= ($row[0== 't' && $row[1== 'f''unique_key ' '';
  403.                 $flags.= ($row[1== 't''primary_key ' '';
  404.                 if (count($keys> 1)
  405.                     $flags.= 'multiple_key ';
  406.             }
  407.         }
  408.  
  409.         return trim($flags);
  410.     }
  411. }
  412. ?>

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