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

Source for file sqlite.php

Documentation is available at sqlite.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: Lukas Smith <smith@pooteeweet.org>                           |
  43. // +----------------------------------------------------------------------+
  44. //
  45. // $Id: sqlite.php,v 1.45 2006/04/15 10:48:06 lsmith Exp $
  46. //
  47.  
  48. require_once 'MDB2/Driver/Reverse/Common.php';
  49.  
  50. /**
  51.  * MDB2 SQlite driver for the schema reverse engineering module
  52.  *
  53.  * @package MDB2
  54.  * @category Database
  55.  * @author  Lukas Smith <smith@pooteeweet.org>
  56.  */
  57. class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common
  58. {
  59.     function _getTableColumns($sql)
  60.     {
  61.         $db =$this->getDBInstance();
  62.         if (PEAR::isError($db)) {
  63.             return $db;
  64.         }
  65.         $start_pos strpos($sql'(');
  66.         $end_pos strrpos($sql')');
  67.         $column_def substr($sql$start_pos+1$end_pos-$start_pos-1);
  68.         // replace the decimal length-places-separator with a colon
  69.         $column_def preg_replace('/(\d),(\d)/''\1:\2'$column_def);
  70.         $column_sql split(','$column_def);
  71.         $columns = array();
  72.         $count count($column_sql);
  73.         if ($count == 0{
  74.             return $db->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  75.                 'unexpected empty table column definition list');
  76.         }
  77.         $regexp '/^([^ ]+) (CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( UNSIGNED)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NOT NULL)?$/i';
  78.         for ($i=0$j=0; $i<$count; ++$i{
  79.             if (!preg_match($regexptrim($column_sql[$i])$matches)) {
  80.                 return $db->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  81.                     'unexpected table column SQL definition: "'.$column_sql[$i].'"');
  82.             }
  83.             $columns[$j]['name'$matches[1];
  84.             $columns[$j]['type'strtolower($matches[2]);
  85.             if (isset($matches[4]&& strlen($matches[4])) {
  86.                 $columns[$j]['length'$matches[4];
  87.             }
  88.             if (isset($matches[6]&& strlen($matches[6])) {
  89.                 $columns[$j]['decimal'$matches[6];
  90.             }
  91.             if (isset($matches[7]&& strlen($matches[7])) {
  92.                 $columns[$j]['unsigned'= true;
  93.             }
  94.             if (isset($matches[8]&& strlen($matches[8])) {
  95.                 $columns[$j]['autoincrement'= true;
  96.             }
  97.             if (isset($matches[10]&& strlen($matches[10])) {
  98.                 $default $matches[10];
  99.                 if (strlen($default&& $default[0]=="'"{
  100.                     $default str_replace("''""'"substr($default1strlen($default)-2));
  101.                 }
  102.                 if ($default === 'NULL'{
  103.                     $default = null;
  104.                 }
  105.                 $columns[$j]['default'$default;
  106.             }
  107.             if (isset($matches[11]&& strlen($matches[11])) {
  108.                 $columns[$j]['notnull'= true;
  109.             }
  110.             ++$j;
  111.         }
  112.         return $columns;
  113.     }
  114.  
  115.     // {{{ getTableFieldDefinition()
  116.  
  117.     /**
  118.      * get the stucture of a field into an array
  119.      *
  120.      * @param string    $table         name of table that should be used in method
  121.      * @param string    $field_name     name of field that should be used in method
  122.      * @return mixed data array on success, a MDB2 error on failure
  123.      * @access public
  124.      */
  125.     function getTableFieldDefinition($table$field_name)
  126.     {
  127.         $db =$this->getDBInstance();
  128.         if (PEAR::isError($db)) {
  129.             return $db;
  130.         }
  131.  
  132.         $result $db->loadModule('Datatype'nulltrue);
  133.         if (PEAR::isError($result)) {
  134.             return $result;
  135.         }
  136.         $table $db->quote($table'text');
  137.         $query "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  138.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  139.             $query.= 'LOWER(name)='.strtolower($table);
  140.         else {
  141.             $query.= "name=$table";
  142.         }
  143.         $sql $db->queryOne($query);
  144.         if (PEAR::isError($sql)) {
  145.             return $sql;
  146.         }
  147.         $columns $this->_getTableColumns($sql);
  148.         foreach ($columns as $column{
  149.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  150.                 if ($db->options['field_case'== CASE_LOWER{
  151.                     $column['name'strtolower($column['name']);
  152.                 else {
  153.                     $column['name'strtoupper($column['name']);
  154.                 }
  155.             else {
  156.                 $column array_change_key_case($column$db->options['field_case']);
  157.             }
  158.             if ($field_name == $column['name']{
  159.                 list($types$length$unsigned$db->datatype->mapNativeDatatype($column);
  160.                 $notnull = false;
  161.                 if (array_key_exists('notnull'$column)) {
  162.                     $notnull $column['notnull'];
  163.                 }
  164.                 $default = false;
  165.                 if (array_key_exists('default'$column)) {
  166.                     $default $column['default'];
  167.                     if (is_null($default&& $notnull{
  168.                         $default '';
  169.                     }
  170.                 }
  171.                 $autoincrement = false;
  172.                 if (array_key_exists('autoincrement'$column&& $column['autoincrement']{
  173.                     $autoincrement = true;
  174.                 }
  175.                 $definition = array();
  176.                 foreach ($types as $key => $type{
  177.                     $definition[$key= array(
  178.                         'type' => $type,
  179.                         'notnull' => $notnull,
  180.                     );
  181.                     if ($length > 0{
  182.                         $definition[$key]['length'$length;
  183.                     }
  184.                     if ($unsigned{
  185.                         $definition[$key]['unsigned'= true;
  186.                     }
  187.                     if ($default !== false{
  188.                         $definition[$key]['default'$default;
  189.                     }
  190.                     if ($autoincrement !== false{
  191.                         $definition[$key]['autoincrement'$autoincrement;
  192.                     }
  193.                 }
  194.                 return $definition;
  195.             }
  196.         }
  197.  
  198.         return $db->raiseError(MDB2_ERRORnullnull,
  199.             'getTableFieldDefinition: it was not specified an existing table column');
  200.     }
  201.  
  202.     // }}}
  203.     // {{{ getTableIndexDefinition()
  204.  
  205.     /**
  206.      * get the stucture of an index into an array
  207.      *
  208.      * @param string    $table      name of table that should be used in method
  209.      * @param string    $index_name name of index that should be used in method
  210.      * @return mixed data array on success, a MDB2 error on failure
  211.      * @access public
  212.      */
  213.     function getTableIndexDefinition($table$index_name)
  214.     {
  215.         $db =$this->getDBInstance();
  216.         if (PEAR::isError($db)) {
  217.             return $db;
  218.         }
  219.  
  220.         $index_name $db->getIndexName($index_name);
  221.         $index_name $db->quote($index_name'text');
  222.         $table $db->quote($table'text');
  223.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  224.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  225.             $query.= "LOWER(name)=".strtolower($index_name)." AND LOWER(tbl_name)=".strtolower($table);
  226.         else {
  227.             $query.= "name=$index_name AND tbl_name=$table";
  228.         }
  229.         $query.= " AND sql NOT NULL ORDER BY name";
  230.         $sql $db->queryOne($query'text');
  231.         if (PEAR::isError($sql)) {
  232.             return $sql;
  233.         }
  234.         if (!$sql{
  235.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  236.                 'getTableIndexDefinition: it was not specified an existing table index');
  237.         }
  238.  
  239.         $sql strtolower($sql);
  240.         $start_pos strpos($sql'(');
  241.         $end_pos strrpos($sql')');
  242.         $column_names substr($sql$start_pos+1$end_pos-$start_pos-1);
  243.         $column_names split(','$column_names);
  244.  
  245.         if (preg_match("/^create unique/"$sql)) {
  246.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  247.                 'getTableIndexDefinition: it was not specified an existing table index');
  248.         }
  249.  
  250.         $definition = array();
  251.         $count count($column_names);
  252.         for ($i=0; $i<$count; ++$i{
  253.             $column_name strtok($column_names[$i]," ");
  254.             $collation strtok(" ");
  255.             $definition['fields'][$column_name= array();
  256.             if (!empty($collation)) {
  257.                 $definition['fields'][$column_name]['sorting'=
  258.                     ($collation=='ASC' 'ascending' 'descending');
  259.             }
  260.         }
  261.  
  262.         if (!array_key_exists('fields'$definition)) {
  263.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  264.                 'getTableIndexDefinition: it was not specified an existing table index');
  265.         }
  266.         return $definition;
  267.     }
  268.  
  269.     // }}}
  270.     // {{{ getTableConstraintDefinition()
  271.  
  272.     /**
  273.      * get the stucture of a constraint into an array
  274.      *
  275.      * @param string    $table      name of table that should be used in method
  276.      * @param string    $index_name name of index that should be used in method
  277.      * @return mixed data array on success, a MDB2 error on failure
  278.      * @access public
  279.      */
  280.     function getTableConstraintDefinition($table$index_name)
  281.     {
  282.         $db =$this->getDBInstance();
  283.         if (PEAR::isError($db)) {
  284.             return $db;
  285.         }
  286.  
  287.         $index_name $db->getIndexName($index_name);
  288.         $table $db->quote($table'text');
  289.         $index_name $db->quote($index_name'text');
  290.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  291.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  292.             $query.= 'LOWER(name)='.strtolower($index_name).' AND LOWER(tbl_name)='.strtolower($table);
  293.         else {
  294.             $query.= "name=$index_name AND tbl_name=$table";
  295.         }
  296.         $query.= " AND sql NOT NULL ORDER BY name";
  297.         $sql $db->queryOne($query'text');
  298.         if (PEAR::isError($sql)) {
  299.             return $sql;
  300.         }
  301.         if (!$sql{
  302.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  303.                 'getTableIndexDefinition: it was not specified an existing table index');
  304.         }
  305.  
  306.         $sql strtolower($sql);
  307.         $start_pos strpos($sql'(');
  308.         $end_pos strrpos($sql')');
  309.         $column_names substr($sql$start_pos+1$end_pos-$start_pos-1);
  310.         $column_names split(','$column_names);
  311.  
  312.         if (!preg_match("/^create unique/"$sql)) {
  313.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  314.                 'getTableConstraintDefinition: it was not specified an existing table constraint');
  315.         }
  316.  
  317.         $definition = array();
  318.         $definition['unique'= true;
  319.         $count count($column_names);
  320.         for ($i=0; $i<$count; ++$i{
  321.             $column_name strtok($column_names[$i]," ");
  322.             $collation strtok(" ");
  323.             $definition['fields'][$column_name= array();
  324.             if (!empty($collation)) {
  325.                 $definition['fields'][$column_name]['sorting'=
  326.                     ($collation=='ASC' 'ascending' 'descending');
  327.             }
  328.         }
  329.  
  330.         if (!array_key_exists('fields'$definition)) {
  331.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  332.                 'getTableConstraintDefinition: it was not specified an existing table constraint');
  333.         }
  334.         return $definition;
  335.     }
  336.  
  337.     // }}}
  338.     // {{{ tableInfo()
  339.  
  340.     /**
  341.      * Returns information about a table
  342.      *
  343.      * @param string         $result  a string containing the name of a table
  344.      * @param int            $mode    a valid tableInfo mode
  345.      *
  346.      * @return array  an associative array with the information requested.
  347.      *                  A MDB2_Error object on failure.
  348.      *
  349.      * @see MDB2_Driver_Common::tableInfo()
  350.      * @since Method available since Release 1.7.0
  351.      */
  352.     function tableInfo($result$mode = null)
  353.     {
  354.         $db =$this->getDBInstance();
  355.         if (PEAR::isError($db)) {
  356.             return $db;
  357.         }
  358.  
  359.         if (!is_string($result)) {
  360.             return $db->raiseError(MDB2_ERROR_NOT_CAPABLEnullnull,
  361.                 'This DBMS can not obtain tableInfo from result sets');
  362.         }
  363.  
  364.         /*
  365.          * Probably received a table name.
  366.          * Create a result resource identifier.
  367.          */
  368.         $id $db->queryAll('PRAGMA table_info('.$db->quote($result'text').');'nullMDB2_FETCHMODE_ASSOC);
  369.         $got_string = true;
  370.  
  371.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  372.             if ($db->options['field_case'== CASE_LOWER{
  373.                 $case_func 'strtolower';
  374.             else {
  375.                 $case_func 'strtoupper';
  376.             }
  377.         else {
  378.             $case_func 'strval';
  379.         }
  380.  
  381.         $count count($id);
  382.         $res   = array();
  383.  
  384.         if ($mode{
  385.             $res['num_fields'$count;
  386.         }
  387.  
  388.         $db->loadModule('Datatype'nulltrue);
  389.         for ($i = 0; $i $count$i++{
  390.             $id[$iarray_change_key_case($id[$i]CASE_LOWER);
  391.             if (strpos($id[$i]['type']'('!== false{
  392.                 $bits explode('('$id[$i]['type']);
  393.                 $type $bits[0];
  394.                 $len  rtrim($bits[1],')');
  395.             else {
  396.                 $type $id[$i]['type'];
  397.                 $len  = 0;
  398.             }
  399.  
  400.             $flags '';
  401.             if ($id[$i]['pk']{
  402.                 $flags.= 'primary_key ';
  403.             }
  404.             if ($id[$i]['notnull']{
  405.                 $flags.= 'not_null ';
  406.             }
  407.             if ($id[$i]['dflt_value'!== null{
  408.                 $flags.= 'default_' rawurlencode($id[$i]['dflt_value']);
  409.             }
  410.             $flags trim($flags);
  411.  
  412.             $res[$i= array(
  413.                 'table' => $case_func($result),
  414.                 'name'  => $case_func($id[$i]['name']),
  415.                 'type'  => $type,
  416.                 'length'   => $len,
  417.                 'flags' => $flags,
  418.             );
  419.             $mdb2type_info $db->datatype->mapNativeDatatype($res[$i]);
  420.             if (PEAR::isError($mdb2type_info)) {
  421.                return $mdb2type_info;
  422.             }
  423.             $res[$i]['mdb2type'$mdb2type_info[0][0];
  424.  
  425.             if ($mode MDB2_TABLEINFO_ORDER{
  426.                 $res['order'][$res[$i]['name']] $i;
  427.             }
  428.             if ($mode MDB2_TABLEINFO_ORDERTABLE{
  429.                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] $i;
  430.             }
  431.         }
  432.  
  433.         return $res;
  434.     }
  435. }
  436.  
  437. ?>

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