MDB2
[ class tree: MDB2 ] [ index: MDB2 ] [ all elements ]

Source for file pgsql.php

Documentation is available at pgsql.php

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

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