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

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