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

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