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

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