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

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