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.70 2007/03/29 18:18:06 quipo 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'__FUNCTION__);
  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 (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?$/i';
  78.         $regexp2 '/^([^ ]+) (PRIMARY|UNIQUE|CHECK)$/i';
  79.         for ($i=0$j=0; $i<$count; ++$i{
  80.             if (!preg_match($regexptrim($column_sql[$i])$matches)) {
  81.                 if (!preg_match($regexp2trim($column_sql[$i]))) {
  82.                     continue;
  83.                 }
  84.                 return $db->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  85.                     'unexpected table column SQL definition: "'.$column_sql[$i].'"'__FUNCTION__);
  86.             }
  87.             $columns[$j]['name'trim($matches[1]implode(''$db->identifier_quoting));
  88.             $columns[$j]['type'strtolower($matches[2]);
  89.             if (isset($matches[4]&& strlen($matches[4])) {
  90.                 $columns[$j]['length'$matches[4];
  91.             }
  92.             if (isset($matches[6]&& strlen($matches[6])) {
  93.                 $columns[$j]['decimal'$matches[6];
  94.             }
  95.             if (isset($matches[7]&& strlen($matches[7])) {
  96.                 $columns[$j]['unsigned'= true;
  97.             }
  98.             if (isset($matches[8]&& strlen($matches[8])) {
  99.                 $columns[$j]['autoincrement'= true;
  100.             }
  101.             if (isset($matches[10]&& strlen($matches[10])) {
  102.                 $default $matches[10];
  103.                 if (strlen($default&& $default[0]=="'"{
  104.                     $default str_replace("''""'"substr($default1strlen($default)-2));
  105.                 }
  106.                 if ($default === 'NULL'{
  107.                     $default = null;
  108.                 }
  109.                 $columns[$j]['default'$default;
  110.             }
  111.             if (isset($matches[11]&& strlen($matches[11])) {
  112.                 $columns[$j]['notnull'($matches[11=== ' NOT NULL');
  113.             }
  114.             ++$j;
  115.         }
  116.         return $columns;
  117.     }
  118.  
  119.     // {{{ getTableFieldDefinition()
  120.  
  121.     /**
  122.      * Get the stucture of a field into an array
  123.      *
  124.      * @param string    $table       name of table that should be used in method
  125.      * @param string    $field_name  name of field that should be used in method
  126.      * @return mixed data array on success, a MDB2 error on failure.
  127.      *           The returned array contains an array for each field definition,
  128.      *           with (some of) these indices:
  129.      *           [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
  130.      * @access public
  131.      */
  132.     function getTableFieldDefinition($table$field_name)
  133.     {
  134.         $db =$this->getDBInstance();
  135.         if (PEAR::isError($db)) {
  136.             return $db;
  137.         }
  138.  
  139.         $result $db->loadModule('Datatype'nulltrue);
  140.         if (PEAR::isError($result)) {
  141.             return $result;
  142.         }
  143.         $query "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  144.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  145.             $query.= 'LOWER(name)='.$db->quote(strtolower($table)'text');
  146.         else {
  147.             $query.= 'name='.$db->quote($table'text');
  148.         }
  149.         $sql $db->queryOne($query);
  150.         if (PEAR::isError($sql)) {
  151.             return $sql;
  152.         }
  153.         $columns $this->_getTableColumns($sql);
  154.         foreach ($columns as $column{
  155.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  156.                 if ($db->options['field_case'== CASE_LOWER{
  157.                     $column['name'strtolower($column['name']);
  158.                 else {
  159.                     $column['name'strtoupper($column['name']);
  160.                 }
  161.             else {
  162.                 $column array_change_key_case($column$db->options['field_case']);
  163.             }
  164.             if ($field_name == $column['name']{
  165.                 $mapped_datatype $db->datatype->mapNativeDatatype($column);
  166.                 if (PEAR::IsError($mapped_datatype)) {
  167.                     return $mapped_datatype;
  168.                 }
  169.                 list($types$length$unsigned$fixed$mapped_datatype;
  170.                 $notnull = false;
  171.                 if (!empty($column['notnull'])) {
  172.                     $notnull $column['notnull'];
  173.                 }
  174.                 $default = false;
  175.                 if (array_key_exists('default'$column)) {
  176.                     $default $column['default'];
  177.                     if (is_null($default&& $notnull{
  178.                         $default '';
  179.                     }
  180.                 }
  181.                 $autoincrement = false;
  182.                 if (!empty($column['autoincrement'])) {
  183.                     $autoincrement = true;
  184.                 }
  185.  
  186.                 $definition[0= array(
  187.                     'notnull' => $notnull,
  188.                     'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i''\\1'$column['type'])
  189.                 );
  190.                 if (!is_null($length)) {
  191.                     $definition[0]['length'$length;
  192.                 }
  193.                 if (!is_null($unsigned)) {
  194.                     $definition[0]['unsigned'$unsigned;
  195.                 }
  196.                 if (!is_null($fixed)) {
  197.                     $definition[0]['fixed'$fixed;
  198.                 }
  199.                 if ($default !== false{
  200.                     $definition[0]['default'$default;
  201.                 }
  202.                 if ($autoincrement !== false{
  203.                     $definition[0]['autoincrement'$autoincrement;
  204.                 }
  205.                 foreach ($types as $key => $type{
  206.                     $definition[$key$definition[0];
  207.                     if ($type == 'clob' || $type == 'blob'{
  208.                         unset($definition[$key]['default']);
  209.                     }
  210.                     $definition[$key]['type'$type;
  211.                     $definition[$key]['mdb2type'$type;
  212.                 }
  213.                 return $definition;
  214.             }
  215.         }
  216.  
  217.         return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  218.             'it was not specified an existing table column'__FUNCTION__);
  219.     }
  220.  
  221.     // }}}
  222.     // {{{ getTableIndexDefinition()
  223.  
  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 =$this->getDBInstance();
  235.         if (PEAR::isError($db)) {
  236.             return $db;
  237.         }
  238.  
  239.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  240.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  241.             $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' $db->quote(strtolower($table)'text');
  242.         else {
  243.             $query.= 'name=%s AND tbl_name=' $db->quote($table'text');
  244.         }
  245.         $query.= ' AND sql NOT NULL ORDER BY name';
  246.         $index_name_mdb2 $db->getIndexName($index_name);
  247.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  248.             $qry sprintf($query$db->quote(strtolower($index_name_mdb2)'text'));
  249.         else {
  250.             $qry sprintf($query$db->quote($index_name_mdb2'text'));
  251.         }
  252.         $sql $db->queryOne($qry'text');
  253.         if (PEAR::isError($sql|| empty($sql)) {
  254.             // fallback to the given $index_name, without transformation
  255.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  256.                 $qry sprintf($query$db->quote(strtolower($index_name)'text'));
  257.             else {
  258.                 $qry sprintf($query$db->quote($index_name'text'));
  259.             }
  260.             $sql $db->queryOne($qry'text');
  261.         }
  262.         if (PEAR::isError($sql)) {
  263.             return $sql;
  264.         }
  265.         if (!$sql{
  266.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  267.                 'it was not specified an existing table index'__FUNCTION__);
  268.         }
  269.  
  270.         $sql strtolower($sql);
  271.         $start_pos strpos($sql'(');
  272.         $end_pos strrpos($sql')');
  273.         $column_names substr($sql$start_pos+1$end_pos-$start_pos-1);
  274.         $column_names split(','$column_names);
  275.  
  276.         if (preg_match("/^create unique/"$sql)) {
  277.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  278.                 'it was not specified an existing table index'__FUNCTION__);
  279.         }
  280.  
  281.         $definition = array();
  282.         $count count($column_names);
  283.         for ($i=0; $i<$count; ++$i{
  284.             $column_name strtok($column_names[$i]' ');
  285.             $collation strtok(' ');
  286.             $definition['fields'][$column_name= array(
  287.                 'position' => $i+1
  288.             );
  289.             if (!empty($collation)) {
  290.                 $definition['fields'][$column_name]['sorting'=
  291.                     ($collation=='ASC' 'ascending' 'descending');
  292.             }
  293.         }
  294.  
  295.         if (empty($definition['fields'])) {
  296.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  297.                 'it was not specified an existing table index'__FUNCTION__);
  298.         }
  299.         return $definition;
  300.     }
  301.  
  302.     // }}}
  303.     // {{{ getTableConstraintDefinition()
  304.  
  305.     /**
  306.      * Get the stucture of a constraint into an array
  307.      *
  308.      * @param string    $table      name of table that should be used in method
  309.      * @param string    $constraint_name name of constraint that should be used in method
  310.      * @return mixed data array on success, a MDB2 error on failure
  311.      * @access public
  312.      */
  313.     function getTableConstraintDefinition($table$constraint_name)
  314.     {
  315.         $db =$this->getDBInstance();
  316.         if (PEAR::isError($db)) {
  317.             return $db;
  318.         }
  319.  
  320.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  321.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  322.             $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' $db->quote(strtolower($table)'text');
  323.         else {
  324.             $query.= 'name=%s AND tbl_name=' $db->quote($table'text');
  325.         }
  326.         $query.= ' AND sql NOT NULL ORDER BY name';
  327.         $constraint_name_mdb2 $db->getIndexName($constraint_name);
  328.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  329.             $qry sprintf($query$db->quote(strtolower($constraint_name_mdb2)'text'));
  330.         else {
  331.             $qry sprintf($query$db->quote($constraint_name_mdb2'text'));
  332.         }
  333.         $sql $db->queryOne($qry'text');
  334.         if (PEAR::isError($sql|| empty($sql)) {
  335.             // fallback to the given $index_name, without transformation
  336.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  337.                 $qry sprintf($query$db->quote(strtolower($constraint_name)'text'));
  338.             else {
  339.                 $qry sprintf($query$db->quote($constraint_name'text'));
  340.             }
  341.             $sql $db->queryOne($qry'text');
  342.         }
  343.         if (PEAR::isError($sql)) {
  344.             return $sql;
  345.         }
  346.         if (!$sql && $constraint_name == 'primary'{
  347.             // search in table definition for PRIMARY KEYs
  348.             $query "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  349.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  350.                 $query.= 'LOWER(name)='.$db->quote(strtolower($table)'text');
  351.             else {
  352.                 $query.= 'name='.$db->quote($table'text');
  353.             }
  354.             $query.= " AND sql NOT NULL ORDER BY name";
  355.             $sql $db->queryOne($query'text');
  356.             if (PEAR::isError($sql)) {
  357.                 return $sql;
  358.             }
  359.             if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i"$sql$tmp)) {
  360.                 $definition = array();
  361.                 $definition['primary'= true;
  362.                 $definition['fields'= array();
  363.                 $column_names split(','$tmp[1]);
  364.                 $colpos = 1;
  365.                 foreach ($column_names as $column_name{
  366.                     $definition['fields'][$column_name= array(
  367.                         'position' => $colpos++
  368.                     );
  369.                 }
  370.                 return $definition;
  371.             }
  372.             $sql = false;
  373.         }
  374.         if (!$sql{
  375.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  376.                 $constraint_name ' is not an existing table constraint'__FUNCTION__);
  377.         }
  378.  
  379.         $sql strtolower($sql);
  380.         $start_pos strpos($sql'(');
  381.         $end_pos strrpos($sql')');
  382.         $column_names substr($sql$start_pos+1$end_pos-$start_pos-1);
  383.         $column_names split(','$column_names);
  384.  
  385.         if (!preg_match("/^create unique/"$sql)) {
  386.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  387.                 $constraint_name ' is not an existing table constraint'__FUNCTION__);
  388.         }
  389.  
  390.         $definition = array();
  391.         $definition['unique'= true;
  392.         $count count($column_names);
  393.         for ($i=0; $i<$count; ++$i{
  394.             $column_name strtok($column_names[$i]," ");
  395.             $collation strtok(" ");
  396.             $definition['fields'][$column_name= array(
  397.                 'position' => $i+1
  398.             );
  399.             if (!empty($collation)) {
  400.                 $definition['fields'][$column_name]['sorting'=
  401.                     ($collation=='ASC' 'ascending' 'descending');
  402.             }
  403.         }
  404.  
  405.         if (empty($definition['fields'])) {
  406.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  407.                 $constraint_name ' is not an existing table constraint'__FUNCTION__);
  408.         }
  409.         return $definition;
  410.     }
  411.  
  412.     // }}}
  413.     // {{{ getTriggerDefinition()
  414.  
  415.     /**
  416.      * Get the structure of a trigger into an array
  417.      *
  418.      * EXPERIMENTAL
  419.      *
  420.      * WARNING: this function is experimental and may change the returned value
  421.      * at any time until labelled as non-experimental
  422.      *
  423.      * @param string    $trigger    name of trigger that should be used in method
  424.      * @return mixed data array on success, a MDB2 error on failure
  425.      * @access public
  426.      */
  427.     function getTriggerDefinition($trigger)
  428.     {
  429.         $db =$this->getDBInstance();
  430.         if (PEAR::isError($db)) {
  431.             return $db;
  432.         }
  433.  
  434.         $query "SELECT name as trigger_name,
  435.                          tbl_name AS table_name,
  436.                          sql AS trigger_body,
  437.                          NULL AS trigger_type,
  438.                          NULL AS trigger_event,
  439.                          NULL AS trigger_comment,
  440.                          1 AS trigger_enabled
  441.                     FROM sqlite_master
  442.                    WHERE type='trigger'";
  443.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  444.             $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger)'text');
  445.         else {
  446.             $query.= ' AND name='.$db->quote($trigger'text');
  447.         }
  448.         $types = array(
  449.             'trigger_name'    => 'text',
  450.             'table_name'      => 'text',
  451.             'trigger_body'    => 'text',
  452.             'trigger_type'    => 'text',
  453.             'trigger_event'   => 'text',
  454.             'trigger_comment' => 'text',
  455.             'trigger_enabled' => 'boolean',
  456.         );
  457.         $def $db->queryRow($query$typesMDB2_FETCHMODE_ASSOC);
  458.         if (PEAR::isError($def)) {
  459.             return $def;
  460.         }
  461.         if (empty($def)) {
  462.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  463.                 'it was not specified an existing trigger'__FUNCTION__);
  464.         }
  465.         if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims"$def['trigger_body']$tmp)) {
  466.             $def['trigger_type'strtoupper($tmp[1]);
  467.             $def['trigger_event'strtoupper($tmp[2]);
  468.         }
  469.         return $def;
  470.     }
  471.  
  472.     // }}}
  473.     // {{{ tableInfo()
  474.  
  475.     /**
  476.      * Returns information about a table
  477.      *
  478.      * @param string         $result  a string containing the name of a table
  479.      * @param int            $mode    a valid tableInfo mode
  480.      *
  481.      * @return array  an associative array with the information requested.
  482.      *                  A MDB2_Error object on failure.
  483.      *
  484.      * @see MDB2_Driver_Common::tableInfo()
  485.      * @since Method available since Release 1.7.0
  486.      */
  487.     function tableInfo($result$mode = null)
  488.     {
  489.         if (is_string($result)) {
  490.            return parent::tableInfo($result$mode);
  491.         }
  492.  
  493.         $db =$this->getDBInstance();
  494.         if (PEAR::isError($db)) {
  495.             return $db;
  496.         }
  497.  
  498.         return $db->raiseError(MDB2_ERROR_NOT_CAPABLEnullnull,
  499.            'This DBMS can not obtain tableInfo from result sets'__FUNCTION__);
  500.     }
  501. }
  502.  
  503. ?>

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