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.68 2007/03/05 22:44:52 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.             if (!empty($collation)) {
  288.                 $definition['fields'][$column_name]['sorting'=
  289.                     ($collation=='ASC' 'ascending' 'descending');
  290.             }
  291.         }
  292.  
  293.         if (empty($definition['fields'])) {
  294.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  295.                 'it was not specified an existing table index'__FUNCTION__);
  296.         }
  297.         return $definition;
  298.     }
  299.  
  300.     // }}}
  301.     // {{{ getTableConstraintDefinition()
  302.  
  303.     /**
  304.      * Get the stucture of a constraint into an array
  305.      *
  306.      * @param string    $table      name of table that should be used in method
  307.      * @param string    $index_name name of index that should be used in method
  308.      * @return mixed data array on success, a MDB2 error on failure
  309.      * @access public
  310.      */
  311.     function getTableConstraintDefinition($table$index_name)
  312.     {
  313.         $db =$this->getDBInstance();
  314.         if (PEAR::isError($db)) {
  315.             return $db;
  316.         }
  317.  
  318.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  319.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  320.             $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' $db->quote(strtolower($table)'text');
  321.         else {
  322.             $query.= 'name=%s AND tbl_name=' $db->quote($table'text');
  323.         }
  324.         $query.= ' AND sql NOT NULL ORDER BY name';
  325.         $index_name_mdb2 $db->getIndexName($index_name);
  326.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  327.             $qry sprintf($query$db->quote(strtolower($index_name_mdb2)'text'));
  328.         else {
  329.             $qry sprintf($query$db->quote($index_name_mdb2'text'));
  330.         }
  331.         $sql $db->queryOne($qry'text');
  332.         if (PEAR::isError($sql|| empty($sql)) {
  333.             // fallback to the given $index_name, without transformation
  334.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  335.                 $qry sprintf($query$db->quote(strtolower($index_name)'text'));
  336.             else {
  337.                 $qry sprintf($query$db->quote($index_name'text'));
  338.             }
  339.             $sql $db->queryOne($qry'text');
  340.         }
  341.         if (PEAR::isError($sql)) {
  342.             return $sql;
  343.         }
  344.         if (!$sql && $index_name == 'primary'{
  345.             // search in table definition for PRIMARY KEYs
  346.             $query "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  347.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  348.                 $query.= 'LOWER(name)='.$db->quote(strtolower($table)'text');
  349.             else {
  350.                 $query.= 'name='.$db->quote($table'text');
  351.             }
  352.             $query.= " AND sql NOT NULL ORDER BY name";
  353.             $sql $db->queryOne($query'text');
  354.             if (PEAR::isError($sql)) {
  355.                 return $sql;
  356.             }
  357.             if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i"$sql$tmp)) {
  358.                 $definition = array();
  359.                 $definition['primary'= true;
  360.                 $definition['fields'= array();
  361.                 $column_names split(','$tmp[1]);
  362.                 foreach ($column_names as $column_name{
  363.                     $definition['fields'][$column_name= array();
  364.                 }
  365.                 return $definition;
  366.             }
  367.             $sql = false;
  368.         }
  369.         if (!$sql{
  370.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  371.                 'it was not specified an existing table constraint'__FUNCTION__);
  372.         }
  373.  
  374.         $sql strtolower($sql);
  375.         $start_pos strpos($sql'(');
  376.         $end_pos strrpos($sql')');
  377.         $column_names substr($sql$start_pos+1$end_pos-$start_pos-1);
  378.         $column_names split(','$column_names);
  379.  
  380.         if (!preg_match("/^create unique/"$sql)) {
  381.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  382.                 'it was not specified an existing table constraint'__FUNCTION__);
  383.         }
  384.  
  385.         $definition = array();
  386.         $definition['unique'= true;
  387.         $count count($column_names);
  388.         for ($i=0; $i<$count; ++$i{
  389.             $column_name strtok($column_names[$i]," ");
  390.             $collation strtok(" ");
  391.             $definition['fields'][$column_name= array();
  392.             if (!empty($collation)) {
  393.                 $definition['fields'][$column_name]['sorting'=
  394.                     ($collation=='ASC' 'ascending' 'descending');
  395.             }
  396.         }
  397.  
  398.         if (empty($definition['fields'])) {
  399.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  400.                 'it was not specified an existing table constraint'__FUNCTION__);
  401.         }
  402.         return $definition;
  403.     }
  404.  
  405.     // }}}
  406.     // {{{ getTriggerDefinition()
  407.  
  408.     /**
  409.      * Get the structure of a trigger into an array
  410.      *
  411.      * EXPERIMENTAL
  412.      *
  413.      * WARNING: this function is experimental and may change the returned value
  414.      * at any time until labelled as non-experimental
  415.      *
  416.      * @param string    $trigger    name of trigger that should be used in method
  417.      * @return mixed data array on success, a MDB2 error on failure
  418.      * @access public
  419.      */
  420.     function getTriggerDefinition($trigger)
  421.     {
  422.         $db =$this->getDBInstance();
  423.         if (PEAR::isError($db)) {
  424.             return $db;
  425.         }
  426.  
  427.         $query "SELECT name as trigger_name,
  428.                          tbl_name AS table_name,
  429.                          sql AS trigger_body,
  430.                          NULL AS trigger_type,
  431.                          NULL AS trigger_event,
  432.                          NULL AS trigger_comment,
  433.                          1 AS trigger_enabled
  434.                     FROM sqlite_master
  435.                    WHERE type='trigger'";
  436.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  437.             $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger)'text');
  438.         else {
  439.             $query.= ' AND name='.$db->quote($trigger'text');
  440.         }
  441.         $types = array(
  442.             'trigger_name'    => 'text',
  443.             'table_name'      => 'text',
  444.             'trigger_body'    => 'text',
  445.             'trigger_type'    => 'text',
  446.             'trigger_event'   => 'text',
  447.             'trigger_comment' => 'text',
  448.             'trigger_enabled' => 'boolean',
  449.         );
  450.         $def $db->queryRow($query$typesMDB2_FETCHMODE_ASSOC);
  451.         if (PEAR::isError($def)) {
  452.             return $def;
  453.         }
  454.         if (empty($def)) {
  455.             return $db->raiseError(MDB2_ERROR_NOT_FOUNDnullnull,
  456.                 'it was not specified an existing trigger'__FUNCTION__);
  457.         }
  458.         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)) {
  459.             $def['trigger_type'strtoupper($tmp[1]);
  460.             $def['trigger_event'strtoupper($tmp[2]);
  461.         }
  462.         return $def;
  463.     }
  464.  
  465.     // }}}
  466.     // {{{ tableInfo()
  467.  
  468.     /**
  469.      * Returns information about a table
  470.      *
  471.      * @param string         $result  a string containing the name of a table
  472.      * @param int            $mode    a valid tableInfo mode
  473.      *
  474.      * @return array  an associative array with the information requested.
  475.      *                  A MDB2_Error object on failure.
  476.      *
  477.      * @see MDB2_Driver_Common::tableInfo()
  478.      * @since Method available since Release 1.7.0
  479.      */
  480.     function tableInfo($result$mode = null)
  481.     {
  482.         if (is_string($result)) {
  483.            return parent::tableInfo($result$mode);
  484.         }
  485.  
  486.         $db =$this->getDBInstance();
  487.         if (PEAR::isError($db)) {
  488.             return $db;
  489.         }
  490.  
  491.         return $db->raiseError(MDB2_ERROR_NOT_CAPABLEnullnull,
  492.            'This DBMS can not obtain tableInfo from result sets'__FUNCTION__);
  493.     }
  494. }
  495.  
  496. ?>

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