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-2008 Manuel Lemos, Tomas V.V.Cox,                 |
  6. // | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton                       |
  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. // | Authors: Lukas Smith <smith@pooteeweet.org>                          |
  43. // |          Lorenzo Alberton <l.alberton@quipo.it>                      |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: sqlite.php,v 1.74 2008/03/05 11:08:53 quipo Exp $
  47. //
  48.  
  49. require_once 'MDB2/Driver/Manager/Common.php';
  50.  
  51. /**
  52.  * MDB2 SQLite driver for the management modules
  53.  *
  54.  * @package MDB2
  55.  * @category Database
  56.  * @author  Lukas Smith <smith@pooteeweet.org>
  57.  * @author  Lorenzo Alberton <l.alberton@quipo.it>
  58.  */
  59. class MDB2_Driver_Manager_sqlite extends MDB2_Driver_Manager_Common
  60. {
  61.     // {{{ createDatabase()
  62.  
  63.     /**
  64.      * create a new database
  65.      *
  66.      * @param string $name    name of the database that should be created
  67.      * @param array  $options array with charset info
  68.      *
  69.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  70.      * @access public
  71.      */
  72.     function createDatabase($name$options = array())
  73.     {
  74.         $db =$this->getDBInstance();
  75.         if (PEAR::isError($db)) {
  76.             return $db;
  77.         }
  78.  
  79.         $database_file $db->_getDatabaseFile($name);
  80.         if (file_exists($database_file)) {
  81.             return $db->raiseError(MDB2_ERROR_ALREADY_EXISTSnullnull,
  82.                 'database already exists'__FUNCTION__);
  83.         }
  84.         $php_errormsg '';
  85.         $handle @sqlite_open($database_file$db->dsn['mode']$php_errormsg);
  86.         if (!$handle{
  87.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  88.                 (isset($php_errormsg$php_errormsg 'could not create the database file')__FUNCTION__);
  89.         }
  90.         if (!empty($options['charset'])) {
  91.             $query 'PRAGMA encoding = ' $db->quote($options['charset']'text');
  92.             @sqlite_query($query$handle);
  93.         }
  94.         @sqlite_close($handle);
  95.         return MDB2_OK;
  96.     }
  97.  
  98.     // }}}
  99.     // {{{ dropDatabase()
  100.  
  101.     /**
  102.      * drop an existing database
  103.      *
  104.      * @param string $name name of the database that should be dropped
  105.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  106.      * @access public
  107.      */
  108.     function dropDatabase($name)
  109.     {
  110.         $db =$this->getDBInstance();
  111.         if (PEAR::isError($db)) {
  112.             return $db;
  113.         }
  114.  
  115.         $database_file $db->_getDatabaseFile($name);
  116.         if (!@file_exists($database_file)) {
  117.             return $db->raiseError(MDB2_ERROR_CANNOT_DROPnullnull,
  118.                 'database does not exist'__FUNCTION__);
  119.         }
  120.         $result @unlink($database_file);
  121.         if (!$result{
  122.             return $db->raiseError(MDB2_ERROR_CANNOT_DROPnullnull,
  123.                 (isset($php_errormsg$php_errormsg 'could not remove the database file')__FUNCTION__);
  124.         }
  125.         return MDB2_OK;
  126.     }
  127.  
  128.     // }}}
  129.     // {{{ _getAdvancedFKOptions()
  130.  
  131.     /**
  132.      * Return the FOREIGN KEY query section dealing with non-standard options
  133.      * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
  134.      *
  135.      * @param array $definition 
  136.      * @return string 
  137.      * @access protected
  138.      */
  139.     function _getAdvancedFKOptions($definition)
  140.     {
  141.         $query '';
  142.         if (!empty($definition['match'])) {
  143.             $query .= ' MATCH '.$definition['match'];
  144.         }
  145.         if (!empty($definition['onupdate']&& (strtoupper($definition['onupdate']!= 'NO ACTION')) {
  146.             $query .= ' ON UPDATE '.$definition['onupdate'];
  147.         }
  148.         if (!empty($definition['ondelete']&& (strtoupper($definition['ondelete']!= 'NO ACTION')) {
  149.             $query .= ' ON DELETE '.$definition['ondelete'];
  150.         }
  151.         if (!empty($definition['deferrable'])) {
  152.             $query .= ' DEFERRABLE';
  153.         else {
  154.             $query .= ' NOT DEFERRABLE';
  155.         }
  156.         if (!empty($definition['initiallydeferred'])) {
  157.             $query .= ' INITIALLY DEFERRED';
  158.         else {
  159.             $query .= ' INITIALLY IMMEDIATE';
  160.         }
  161.         return $query;
  162.     }
  163.  
  164.     // }}}
  165.     // {{{ _getCreateTableQuery()
  166.  
  167.     /**
  168.      * Create a basic SQL query for a new table creation
  169.      * @param string $name   Name of the database that should be created
  170.      * @param array $fields  Associative array that contains the definition of each field of the new table
  171.      * @param array $options  An associative array of table options
  172.      * @return mixed string (the SQL query) on success, a MDB2 error on failure
  173.      * @see createTable()
  174.      */
  175.     function _getCreateTableQuery($name$fields$options = array())
  176.     {
  177.         $db =$this->getDBInstance();
  178.         if (PEAR::isError($db)) {
  179.             return $db;
  180.         }
  181.  
  182.         if (!$name{
  183.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  184.                 'no valid table name specified'__FUNCTION__);
  185.         }
  186.         if (empty($fields)) {
  187.             return $db->raiseError(MDB2_ERROR_CANNOT_CREATEnullnull,
  188.                 'no fields specified for table "'.$name.'"'__FUNCTION__);
  189.         }
  190.         $query_fields $this->getFieldDeclarationList($fields);
  191.         if (PEAR::isError($query_fields)) {
  192.             return $query_fields;
  193.         }
  194.         if (!empty($options['primary'])) {
  195.             $query_fields.= ', PRIMARY KEY ('.implode(', 'array_keys($options['primary'])).')';
  196.         }
  197.         if (!empty($options['foreign_keys'])) {
  198.             foreach ($options['foreign_keys'as $fkname => $fkdef{
  199.                 if (empty($fkdef)) {
  200.                     continue;
  201.                 }
  202.                 $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', 'array_keys($fkdef['fields'])).')';
  203.                 $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', 'array_keys($fkdef['references']['fields'])).')';
  204.                 $query_fields.= $this->_getAdvancedFKOptions($fkdef);
  205.             }
  206.         }
  207.  
  208.         $name $db->quoteIdentifier($nametrue);
  209.         $result 'CREATE ';
  210.         if (!empty($options['temporary'])) {
  211.             $result .= $this->_getTemporaryTableQuery();
  212.         }
  213.         $result .= " TABLE $name ($query_fields)";
  214.         return $result;
  215.     }
  216.  
  217.     // }}}
  218.     // {{{ createTable()
  219.  
  220.     /**
  221.      * create a new table
  222.      *
  223.      * @param string $name   Name of the database that should be created
  224.      * @param array $fields  Associative array that contains the definition of each field of the new table
  225.      * @param array $options  An associative array of table options
  226.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  227.      * @access public
  228.      */
  229.     function createTable($name$fields$options = array())
  230.     {
  231.         $result = parent::createTable($name$fields$options);
  232.         if (PEAR::isError($result)) {
  233.             return $result;
  234.         }
  235.         // create triggers to enforce FOREIGN KEY constraints
  236.         if (!empty($options['foreign_keys'])) {
  237.             $db =$this->getDBInstance();
  238.             if (PEAR::isError($db)) {
  239.                 return $db;
  240.             }
  241.             foreach ($options['foreign_keys'as $fkname => $fkdef{
  242.                 if (empty($fkdef)) {
  243.                     continue;
  244.                 }
  245.                 //set actions to 'RESTRICT' if not set
  246.                 $fkdef['onupdate'= empty($fkdef['onupdate']'RESTRICT' strtoupper($fkdef['onupdate']);
  247.                 $fkdef['ondelete'= empty($fkdef['ondelete']'RESTRICT' strtoupper($fkdef['ondelete']);
  248.  
  249.                 $trigger_names = array(
  250.                     'insert'    => $fkname.'_insert_trg',
  251.                     'update'    => $fkname.'_update_trg',
  252.                     'pk_update' => $fkname.'_pk_update_trg',
  253.                     'pk_delete' => $fkname.'_pk_delete_trg',
  254.                 );
  255.                 
  256.                 //create the [insert|update] triggers on the FK table
  257.                 $table_fields array_keys($fkdef['fields']);
  258.                 $referenced_fields array_keys($fkdef['references']['fields']);
  259.                 $query 'CREATE TRIGGER %s BEFORE %s ON '.$name
  260.                         .' FOR EACH ROW BEGIN'
  261.                         .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
  262.                         .' WHERE  (SELECT ';
  263.                 $aliased_fields = array();
  264.                 foreach ($referenced_fields as $field{
  265.                     $aliased_fields[$fkdef['references']['table'.'.'.$field .' AS '.$field;
  266.                 }
  267.                 $query .= implode(','$aliased_fields)
  268.                        .' FROM '.$fkdef['references']['table']
  269.                        .' WHERE ';
  270.                 $conditions = array();
  271.                 for ($i=0; $i<count($table_fields)$i++{
  272.                     $conditions[$referenced_fields[$i.' = NEW.'.$table_fields[$i];
  273.                 }
  274.                 $query .= implode(' AND '$conditions).') IS NULL; END;';
  275.                 $result $db->exec(sprintf($query$trigger_names['insert']'INSERT''insert'));
  276.                 if (PEAR::isError($result)) {
  277.                     return $result;
  278.                 }
  279.  
  280.                 $result $db->exec(sprintf($query$trigger_names['update']'UPDATE''update'));
  281.                 if (PEAR::isError($result)) {
  282.                     return $result;
  283.                 }
  284.                 
  285.                 //create the ON [UPDATE|DELETE] triggers on the primary table
  286.                 $restrict_action 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
  287.                                   .' WHERE  (SELECT ';
  288.                 $aliased_fields = array();
  289.                 foreach ($table_fields as $field{
  290.                     $aliased_fields[$name .'.'.$field .' AS '.$field;
  291.                 }
  292.                 $restrict_action .= implode(','$aliased_fields)
  293.                        .' FROM '.$name
  294.                        .' WHERE ';
  295.                 $conditions  = array();
  296.                 $new_values  = array();
  297.                 $null_values = array();
  298.                 for ($i=0; $i<count($table_fields)$i++{
  299.                     $conditions[]  $table_fields[$i.' = OLD.'.$referenced_fields[$i];
  300.                     $new_values[]  $table_fields[$i.' = NEW.'.$referenced_fields[$i];
  301.                     $null_values[$table_fields[$i.' = NULL';
  302.                 }
  303.                 $restrict_action .= implode(' AND '$conditions).') IS NOT NULL';
  304.  
  305.                 $cascade_action_update 'UPDATE '.$name.' SET '.implode(', '$new_values.' WHERE '.implode(' AND '$conditions);
  306.                 $cascade_action_delete 'DELETE FROM '.$name.' WHERE '.implode(' AND '$conditions);
  307.                 $setnull_action        'UPDATE '.$name.' SET '.implode(', '$null_values).' WHERE '.implode(' AND '$conditions);
  308.  
  309.                 if ('SET DEFAULT' == $fkdef['onupdate'|| 'SET DEFAULT' == $fkdef['ondelete']{
  310.                     $db->loadModule('Reverse'nulltrue);
  311.                     $default_values = array();
  312.                     foreach ($table_fields as $table_field{
  313.                         $field_definition $db->reverse->getTableFieldDefinition($name$field);
  314.                         if (PEAR::isError($field_definition)) {
  315.                             return $field_definition;
  316.                         }
  317.                         $default_values[$table_field .' = '$field_definition[0]['default'];
  318.                     }
  319.                     $setdefault_action 'UPDATE '.$name.' SET '.implode(', '$default_values).' WHERE '.implode(' AND '$conditions);
  320.                 }
  321.  
  322.                 $query 'CREATE TRIGGER %s'
  323.                         .' %s ON '.$fkdef['references']['table']
  324.                         .' FOR EACH ROW BEGIN ';
  325.  
  326.                 if ('CASCADE' == $fkdef['onupdate']{
  327.                     $sql_update sprintf($query$trigger_names['pk_update']'AFTER UPDATE',  'update'$cascade_action_update'; END;';
  328.                 elseif ('SET NULL' == $fkdef['onupdate']{
  329.                     $sql_update sprintf($query$trigger_names['pk_update']'BEFORE UPDATE''update'$setnull_action'; END;';
  330.                 elseif ('SET DEFAULT' == $fkdef['onupdate']{
  331.                     $sql_update sprintf($query$trigger_names['pk_update']'BEFORE UPDATE''update'$setdefault_action'; END;';
  332.                 elseif ('NO ACTION' == $fkdef['onupdate']{
  333.                     $sql_update sprintf($query.$restrict_action$trigger_names['pk_update']'AFTER UPDATE''update''; END;';
  334.                 else {
  335.                     //'RESTRICT'
  336.                     $sql_update sprintf($query.$restrict_action$trigger_names['pk_update']'BEFORE UPDATE''update''; END;';
  337.                 }
  338.                 if ('CASCADE' == $fkdef['ondelete']{
  339.                     $sql_delete sprintf($query$trigger_names['pk_delete']'AFTER DELETE',  'delete'$cascade_action_delete'; END;';
  340.                 elseif ('SET NULL' == $fkdef['ondelete']{
  341.                     $sql_delete sprintf($query$trigger_names['pk_delete']'BEFORE DELETE''delete'$setnull_action'; END;';
  342.                 elseif ('SET DEFAULT' == $fkdef['ondelete']{
  343.                     $sql_delete sprintf($query$trigger_names['pk_delete']'BEFORE DELETE''delete'$setdefault_action'; END;';
  344.                 elseif ('NO ACTION' == $fkdef['ondelete']{
  345.                     $sql_delete sprintf($query.$restrict_action$trigger_names['pk_delete']'AFTER DELETE''delete')  '; END;';
  346.                 else {
  347.                     //'RESTRICT'
  348.                     $sql_delete sprintf($query.$restrict_action$trigger_names['pk_delete']'BEFORE DELETE''delete''; END;';
  349.                 }
  350.  
  351.                 if (PEAR::isError($result)) {
  352.                     return $result;
  353.                 }
  354.                 $result $db->exec($sql_delete);
  355.                 if (PEAR::isError($result)) {
  356.                     return $result;
  357.                 }
  358.                 $result $db->exec($sql_update);
  359.                 if (PEAR::isError($result)) {
  360.                     return $result;
  361.                 }
  362.             }
  363.         }
  364.         if (PEAR::isError($result)) {
  365.             return $result;
  366.         }
  367.         return MDB2_OK;
  368.     }
  369.  
  370.     // }}}
  371.     // {{{ dropTable()
  372.  
  373.     /**
  374.      * drop an existing table
  375.      *
  376.      * @param string $name name of the table that should be dropped
  377.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  378.      * @access public
  379.      */
  380.     function dropTable($name)
  381.     {
  382.         $db =$this->getDBInstance();
  383.         if (PEAR::isError($db)) {
  384.             return $db;
  385.         }
  386.         
  387.         //delete the triggers associated to existing FK constraints
  388.         $constraints $this->listTableConstraints($name);
  389.         if (!PEAR::isError($constraints&& !empty($constraints)) {
  390.             $db->loadModule('Reverse'nulltrue);
  391.             foreach ($constraints as $constraint{
  392.                 $definition $db->reverse->getTableConstraintDefinition($name$constraint);
  393.                 if (!PEAR::isError($definition&& !empty($definition['foreign'])) {
  394.                     $result $this->_dropFKTriggers($name$constraint$definition['references']['table']);
  395.                     if (PEAR::isError($result)) {
  396.                         return $result;
  397.                     }
  398.                 }
  399.             }
  400.         }
  401.  
  402.         $name $db->quoteIdentifier($nametrue);
  403.         return $db->exec("DROP TABLE $name");
  404.     }
  405.  
  406.     // }}}
  407.     // {{{ vacuum()
  408.  
  409.     /**
  410.      * Optimize (vacuum) all the tables in the db (or only the specified table)
  411.      * and optionally run ANALYZE.
  412.      *
  413.      * @param string $table table name (all the tables if empty)
  414.      * @param array  $options an array with driver-specific options:
  415.      *                - timeout [int] (in seconds) [mssql-only]
  416.      *                - analyze [boolean] [pgsql and mysql]
  417.      *                - full [boolean] [pgsql-only]
  418.      *                - freeze [boolean] [pgsql-only]
  419.      *
  420.      * @return mixed MDB2_OK success, a MDB2 error on failure
  421.      * @access public
  422.      */
  423.     function vacuum($table = null$options = array())
  424.     {
  425.         $db =$this->getDBInstance();
  426.         if (PEAR::isError($db)) {
  427.             return $db;
  428.         }
  429.  
  430.         $query 'VACUUM';
  431.         if (!empty($table)) {
  432.             $query .= ' '.$db->quoteIdentifier($tabletrue);
  433.         }
  434.         return $db->exec($query);
  435.     }
  436.  
  437.     // }}}
  438.     // {{{ alterTable()
  439.  
  440.     /**
  441.      * alter an existing table
  442.      *
  443.      * @param string $name         name of the table that is intended to be changed.
  444.      * @param array $changes     associative array that contains the details of each type
  445.      *                              of change that is intended to be performed. The types of
  446.      *                              changes that are currently supported are defined as follows:
  447.      *
  448.      *                              name
  449.      *
  450.      *                                 New name for the table.
  451.      *
  452.      *                             add
  453.      *
  454.      *                                 Associative array with the names of fields to be added as
  455.      *                                  indexes of the array. The value of each entry of the array
  456.      *                                  should be set to another associative array with the properties
  457.      *                                  of the fields to be added. The properties of the fields should
  458.      *                                  be the same as defined by the MDB2 parser.
  459.      *
  460.      *
  461.      *                             remove
  462.      *
  463.      *                                 Associative array with the names of fields to be removed as indexes
  464.      *                                  of the array. Currently the values assigned to each entry are ignored.
  465.      *                                  An empty array should be used for future compatibility.
  466.      *
  467.      *                             rename
  468.      *
  469.      *                                 Associative array with the names of fields to be renamed as indexes
  470.      *                                  of the array. The value of each entry of the array should be set to
  471.      *                                  another associative array with the entry named name with the new
  472.      *                                  field name and the entry named Declaration that is expected to contain
  473.      *                                  the portion of the field declaration already in DBMS specific SQL code
  474.      *                                  as it is used in the CREATE TABLE statement.
  475.      *
  476.      *                             change
  477.      *
  478.      *                                 Associative array with the names of the fields to be changed as indexes
  479.      *                                  of the array. Keep in mind that if it is intended to change either the
  480.      *                                  name of a field and any other properties, the change array entries
  481.      *                                  should have the new names of the fields as array indexes.
  482.      *
  483.      *                                 The value of each entry of the array should be set to another associative
  484.      *                                  array with the properties of the fields to that are meant to be changed as
  485.      *                                  array entries. These entries should be assigned to the new values of the
  486.      *                                  respective properties. The properties of the fields should be the same
  487.      *                                  as defined by the MDB2 parser.
  488.      *
  489.      *                             Example
  490.      *                                 array(
  491.      *                                     'name' => 'userlist',
  492.      *                                     'add' => array(
  493.      *                                         'quota' => array(
  494.      *                                             'type' => 'integer',
  495.      *                                             'unsigned' => 1
  496.      *                                         )
  497.      *                                     ),
  498.      *                                     'remove' => array(
  499.      *                                         'file_limit' => array(),
  500.      *                                         'time_limit' => array()
  501.      *                                     ),
  502.      *                                     'change' => array(
  503.      *                                         'name' => array(
  504.      *                                             'length' => '20',
  505.      *                                             'definition' => array(
  506.      *                                                 'type' => 'text',
  507.      *                                                 'length' => 20,
  508.      *                                             ),
  509.      *                                         )
  510.      *                                     ),
  511.      *                                     'rename' => array(
  512.      *                                         'sex' => array(
  513.      *                                             'name' => 'gender',
  514.      *                                             'definition' => array(
  515.      *                                                 'type' => 'text',
  516.      *                                                 'length' => 1,
  517.      *                                                 'default' => 'M',
  518.      *                                             ),
  519.      *                                         )
  520.      *                                     )
  521.      *                                 )
  522.      *
  523.      * @param boolean $check     indicates whether the function should just check if the DBMS driver
  524.      *                              can perform the requested table alterations if the value is true or
  525.      *                              actually perform them otherwise.
  526.      * @access public
  527.      *
  528.       * @return mixed MDB2_OK on success, a MDB2 error on failure
  529.      */
  530.     function alterTable($name$changes$check$options = array())
  531.     {
  532.         $db =$this->getDBInstance();
  533.         if (PEAR::isError($db)) {
  534.             return $db;
  535.         }
  536.  
  537.         foreach ($changes as $change_name => $change{
  538.             switch ($change_name{
  539.             case 'add':
  540.             case 'remove':
  541.             case 'change':
  542.             case 'name':
  543.             case 'rename':
  544.                 break;
  545.             default:
  546.                 return $db->raiseError(MDB2_ERROR_CANNOT_ALTERnullnull,
  547.                     'change type "'.$change_name.'" not yet supported'__FUNCTION__);
  548.             }
  549.         }
  550.  
  551.         if ($check{
  552.             return MDB2_OK;
  553.         }
  554.  
  555.         $db->loadModule('Reverse'nulltrue);
  556.  
  557.         // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it
  558.         $fields $db->manager->listTableFields($name);
  559.         if (PEAR::isError($fields)) {
  560.             return $fields;
  561.         }
  562.  
  563.         $fields array_flip($fields);
  564.         foreach ($fields as $field => $value{
  565.             $definition $db->reverse->getTableFieldDefinition($name$field);
  566.             if (PEAR::isError($definition)) {
  567.                 return $definition;
  568.             }
  569.             $fields[$field$definition[0];
  570.         }
  571.  
  572.         $indexes $db->manager->listTableIndexes($name);
  573.         if (PEAR::isError($indexes)) {
  574.             return $indexes;
  575.         }
  576.  
  577.         $indexes array_flip($indexes);
  578.         foreach ($indexes as $index => $value{
  579.             $definition $db->reverse->getTableIndexDefinition($name$index);
  580.             if (PEAR::isError($definition)) {
  581.                 return $definition;
  582.             }
  583.             $indexes[$index$definition;
  584.         }
  585.  
  586.         $constraints $db->manager->listTableConstraints($name);
  587.         if (PEAR::isError($constraints)) {
  588.             return $constraints;
  589.         }
  590.  
  591.         if (!array_key_exists('foreign_keys'$options)) {
  592.             $options['foreign_keys'= array();
  593.         }
  594.         $constraints array_flip($constraints);
  595.         foreach ($constraints as $constraint => $value{
  596.             if (!empty($definition['primary'])) {
  597.                 if (!array_key_exists('primary'$options)) {
  598.                     $options['primary'$definition['fields'];
  599.                     //remove from the $constraint array, it's already handled by createTable()
  600.                     unset($constraints[$constraint]);
  601.                 }
  602.             else {
  603.                 $c_definition $db->reverse->getTableConstraintDefinition($name$constraint);
  604.                 if (PEAR::isError($c_definition)) {
  605.                     return $c_definition;
  606.                 }
  607.                 if (!empty($c_definition['foreign'])) {
  608.                     if (!array_key_exists($constraint$options['foreign_keys'])) {
  609.                         $options['foreign_keys'][$constraint$c_definition;
  610.                     }
  611.                     //remove from the $constraint array, it's already handled by createTable()
  612.                     unset($constraints[$constraint]);
  613.                 else {
  614.                     $constraints[$constraint$c_definition;
  615.                 }
  616.             }
  617.         }
  618.  
  619.         $name_new $name;
  620.         $create_order $select_fields array_keys($fields);
  621.         foreach ($changes as $change_name => $change{
  622.             switch ($change_name{
  623.             case 'add':
  624.                 foreach ($change as $field_name => $field{
  625.                     $fields[$field_name$field;
  626.                     $create_order[$field_name;
  627.                 }
  628.                 break;
  629.             case 'remove':
  630.                 foreach ($change as $field_name => $field{
  631.                     unset($fields[$field_name]);
  632.                     $select_fields array_diff($select_fieldsarray($field_name));
  633.                     $create_order array_diff($create_orderarray($field_name));
  634.                 }
  635.                 break;
  636.             case 'change':
  637.                 foreach ($change as $field_name => $field{
  638.                     $fields[$field_name$field['definition'];
  639.                 }
  640.                 break;
  641.             case 'name':
  642.                 $name_new $change;
  643.                 break;
  644.             case 'rename':
  645.                 foreach ($change as $field_name => $field{
  646.                     unset($fields[$field_name]);
  647.                     $fields[$field['name']] $field['definition'];
  648.                     $create_order[array_search($field_name$create_order)$field['name'];
  649.                 }
  650.                 break;
  651.             default:
  652.                 return $db->raiseError(MDB2_ERROR_CANNOT_ALTERnullnull,
  653.                     'change type "'.$change_name.'" not yet supported'__FUNCTION__);
  654.             }
  655.         }
  656.  
  657.         $data = null;
  658.         if (!empty($select_fields)) {
  659.             $query 'SELECT '.implode(', '$select_fields).' FROM '.$db->quoteIdentifier($nametrue);
  660.             $data $db->queryAll($querynullMDB2_FETCHMODE_ORDERED);
  661.         }
  662.  
  663.         $result $this->dropTable($name);
  664.         if (PEAR::isError($result)) {
  665.             return $result;
  666.         }
  667.  
  668.         $result $this->createTable($name_new$fields$options);
  669.         if (PEAR::isError($result)) {
  670.             return $result;
  671.         }
  672.  
  673.         foreach ($indexes as $index => $definition{
  674.             $this->createIndex($name_new$index$definition);
  675.         }
  676.  
  677.         foreach ($constraints as $constraint => $definition{
  678.             $this->createConstraint($name_new$constraint$definition);
  679.         }
  680.  
  681.         if (!empty($select_fields&& !empty($data)) {
  682.             $query 'INSERT INTO '.$db->quoteIdentifier($name_newtrue);
  683.             $query.= '('.implode(', 'array_slice(array_keys($fields)0count($select_fields))).')';
  684.             $query.=' VALUES (?'.str_repeat(', ?'(count($select_fields- 1)).')';
  685.             $stmt =$db->prepare($querynullMDB2_PREPARE_MANIP);
  686.             if (PEAR::isError($stmt)) {
  687.                 return $stmt;
  688.             }
  689.             foreach ($data as $row{
  690.                 $result $stmt->execute($row);
  691.                 if (PEAR::isError($result)) {
  692.                     return $result;
  693.                 }
  694.             }
  695.         }
  696.         return MDB2_OK;
  697.     }
  698.  
  699.     // }}}
  700.     // {{{ listDatabases()
  701.  
  702.     /**
  703.      * list all databases
  704.      *
  705.      * @return mixed array of database names on success, a MDB2 error on failure
  706.      * @access public
  707.      */
  708.     function listDatabases()
  709.     {
  710.         $db =$this->getDBInstance();
  711.         if (PEAR::isError($db)) {
  712.             return $db;
  713.         }
  714.  
  715.         return $db->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  716.             'list databases is not supported'__FUNCTION__);
  717.     }
  718.  
  719.     // }}}
  720.     // {{{ listUsers()
  721.  
  722.     /**
  723.      * list all users
  724.      *
  725.      * @return mixed array of user names on success, a MDB2 error on failure
  726.      * @access public
  727.      */
  728.     function listUsers()
  729.     {
  730.         $db =$this->getDBInstance();
  731.         if (PEAR::isError($db)) {
  732.             return $db;
  733.         }
  734.  
  735.         return $db->raiseError(MDB2_ERROR_UNSUPPORTEDnullnull,
  736.             'list databases is not supported'__FUNCTION__);
  737.     }
  738.  
  739.     // }}}
  740.     // {{{ listViews()
  741.  
  742.     /**
  743.      * list all views in the current database
  744.      *
  745.      * @return mixed array of view names on success, a MDB2 error on failure
  746.      * @access public
  747.      */
  748.     function listViews()
  749.     {
  750.         $db =$this->getDBInstance();
  751.         if (PEAR::isError($db)) {
  752.             return $db;
  753.         }
  754.  
  755.         $query "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL";
  756.         $result $db->queryCol($query);
  757.         if (PEAR::isError($result)) {
  758.             return $result;
  759.         }
  760.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  761.             $result array_map(($db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper')$result);
  762.         }
  763.         return $result;
  764.     }
  765.  
  766.     // }}}
  767.     // {{{ listTableViews()
  768.  
  769.     /**
  770.      * list the views in the database that reference a given table
  771.      *
  772.      * @param string table for which all referenced views should be found
  773.      * @return mixed array of view names on success, a MDB2 error on failure
  774.      * @access public
  775.      */
  776.     function listTableViews($table)
  777.     {
  778.         $db =$this->getDBInstance();
  779.         if (PEAR::isError($db)) {
  780.             return $db;
  781.         }
  782.  
  783.         $query "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
  784.         $views $db->queryAll($queryarray('text''text')MDB2_FETCHMODE_ASSOC);
  785.         if (PEAR::isError($views)) {
  786.             return $views;
  787.         }
  788.         $result = array();
  789.         foreach ($views as $row{
  790.             if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i"$row['sql'])) {
  791.                 if (!empty($row['name'])) {
  792.                     $result[$row['name']] = true;
  793.                 }
  794.             }
  795.         }
  796.  
  797.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  798.             $result array_change_key_case($result$db->options['field_case']);
  799.         }
  800.         return array_keys($result);
  801.     }
  802.  
  803.     // }}}
  804.     // {{{ listTables()
  805.  
  806.     /**
  807.      * list all tables in the current database
  808.      *
  809.      * @return mixed array of table names on success, a MDB2 error on failure
  810.      * @access public
  811.      */
  812.     function listTables()
  813.     {
  814.         $db =$this->getDBInstance();
  815.         if (PEAR::isError($db)) {
  816.             return $db;
  817.         }
  818.  
  819.         $query "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  820.         $table_names $db->queryCol($query);
  821.         if (PEAR::isError($table_names)) {
  822.             return $table_names;
  823.         }
  824.         $result = array();
  825.         foreach ($table_names as $table_name{
  826.             if (!$this->_fixSequenceName($table_nametrue)) {
  827.                 $result[$table_name;
  828.             }
  829.         }
  830.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  831.             $result array_map(($db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper')$result);
  832.         }
  833.         return $result;
  834.     }
  835.  
  836.     // }}}
  837.     // {{{ listTableFields()
  838.  
  839.     /**
  840.      * list all fields in a table in the current database
  841.      *
  842.      * @param string $table name of table that should be used in method
  843.      * @return mixed array of field names on success, a MDB2 error on failure
  844.      * @access public
  845.      */
  846.     function listTableFields($table)
  847.     {
  848.         $db =$this->getDBInstance();
  849.         if (PEAR::isError($db)) {
  850.             return $db;
  851.         }
  852.  
  853.         $result $db->loadModule('Reverse'nulltrue);
  854.         if (PEAR::isError($result)) {
  855.             return $result;
  856.         }
  857.         $query "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  858.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  859.             $query.= 'LOWER(name)='.$db->quote(strtolower($table)'text');
  860.         else {
  861.             $query.= 'name='.$db->quote($table'text');
  862.         }
  863.         $sql $db->queryOne($query);
  864.         if (PEAR::isError($sql)) {
  865.             return $sql;
  866.         }
  867.         $columns $db->reverse->_getTableColumns($sql);
  868.         $fields = array();
  869.         foreach ($columns as $column{
  870.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  871.                 if ($db->options['field_case'== CASE_LOWER{
  872.                     $column['name'strtolower($column['name']);
  873.                 else {
  874.                     $column['name'strtoupper($column['name']);
  875.                 }
  876.             else {
  877.                 $column array_change_key_case($column$db->options['field_case']);
  878.             }
  879.             $fields[$column['name'];
  880.         }
  881.         return $fields;
  882.     }
  883.  
  884.     // }}}
  885.     // {{{ listTableTriggers()
  886.  
  887.     /**
  888.      * list all triggers in the database that reference a given table
  889.      *
  890.      * @param string table for which all referenced triggers should be found
  891.      * @return mixed array of trigger names on success, a MDB2 error on failure
  892.      * @access public
  893.      */
  894.     function listTableTriggers($table = null)
  895.     {
  896.         $db =$this->getDBInstance();
  897.         if (PEAR::isError($db)) {
  898.             return $db;
  899.         }
  900.  
  901.         $query "SELECT name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL";
  902.         if (!is_null($table)) {
  903.             if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  904.                 $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table)'text');
  905.             else {
  906.                 $query.= ' AND tbl_name='.$db->quote($table'text');
  907.             }
  908.         }
  909.         $result $db->queryCol($query);
  910.         if (PEAR::isError($result)) {
  911.             return $result;
  912.         }
  913.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  914.             $result array_map(($db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper')$result);
  915.         }
  916.         return $result;
  917.     }
  918.  
  919.     // }}}
  920.     // {{{ createIndex()
  921.  
  922.     /**
  923.      * Get the stucture of a field into an array
  924.      *
  925.      * @param string    $table         name of the table on which the index is to be created
  926.      * @param string    $name         name of the index to be created
  927.      * @param array     $definition        associative array that defines properties of the index to be created.
  928.      *                                  Currently, only one property named FIELDS is supported. This property
  929.      *                                  is also an associative with the names of the index fields as array
  930.      *                                  indexes. Each entry of this array is set to another type of associative
  931.      *                                  array that specifies properties of the index that are specific to
  932.      *                                  each field.
  933.      *
  934.      *                                 Currently, only the sorting property is supported. It should be used
  935.      *                                  to define the sorting direction of the index. It may be set to either
  936.      *                                  ascending or descending.
  937.      *
  938.      *                                 Not all DBMS support index sorting direction configuration. The DBMS
  939.      *                                  drivers of those that do not support it ignore this property. Use the
  940.      *                                  function support() to determine whether the DBMS driver can manage indexes.
  941.  
  942.      *                                  Example
  943.      *                                     array(
  944.      *                                         'fields' => array(
  945.      *                                             'user_name' => array(
  946.      *                                                 'sorting' => 'ascending'
  947.      *                                             ),
  948.      *                                             'last_login' => array()
  949.      *                                         )
  950.      *                                     )
  951.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  952.      * @access public
  953.      */
  954.     function createIndex($table$name$definition)
  955.     {
  956.         $db =$this->getDBInstance();
  957.         if (PEAR::isError($db)) {
  958.             return $db;
  959.         }
  960.  
  961.         $table $db->quoteIdentifier($tabletrue);
  962.         $name  $db->getIndexName($name);
  963.         $query = "CREATE INDEX $name ON $table";
  964.         $fields = array();
  965.         foreach ($definition['fields'as $field_name => $field{
  966.             $field_string $field_name;
  967.             if (!empty($field['sorting'])) {
  968.                 switch ($field['sorting']{
  969.                 case 'ascending':
  970.                     $field_string.= ' ASC';
  971.                     break;
  972.                 case 'descending':
  973.                     $field_string.= ' DESC';
  974.                     break;
  975.                 }
  976.             }
  977.             $fields[$field_string;
  978.         }
  979.         $query .= ' ('.implode(', '$fields')';
  980.         return $db->exec($query);
  981.     }
  982.  
  983.     // }}}
  984.     // {{{ dropIndex()
  985.  
  986.     /**
  987.      * drop existing index
  988.      *
  989.      * @param string    $table         name of table that should be used in method
  990.      * @param string    $name         name of the index to be dropped
  991.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  992.      * @access public
  993.      */
  994.     function dropIndex($table$name)
  995.     {
  996.         $db =$this->getDBInstance();
  997.         if (PEAR::isError($db)) {
  998.             return $db;
  999.         }
  1000.  
  1001.         $name $db->getIndexName($name);
  1002.         return $db->exec("DROP INDEX $name");
  1003.     }
  1004.  
  1005.     // }}}
  1006.     // {{{ listTableIndexes()
  1007.  
  1008.     /**
  1009.      * list all indexes in a table
  1010.      *
  1011.      * @param string $table name of table that should be used in method
  1012.      * @return mixed array of index names on success, a MDB2 error on failure
  1013.      * @access public
  1014.      */
  1015.     function listTableIndexes($table)
  1016.     {
  1017.         $db =$this->getDBInstance();
  1018.         if (PEAR::isError($db)) {
  1019.             return $db;
  1020.         }
  1021.  
  1022.         $table $db->quote($table'text');
  1023.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  1024.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1025.             $query.= 'LOWER(tbl_name)='.strtolower($table);
  1026.         else {
  1027.             $query.= "tbl_name=$table";
  1028.         }
  1029.         $query.= " AND sql NOT NULL ORDER BY name";
  1030.         $indexes $db->queryCol($query'text');
  1031.         if (PEAR::isError($indexes)) {
  1032.             return $indexes;
  1033.         }
  1034.  
  1035.         $result = array();
  1036.         foreach ($indexes as $sql{
  1037.             if (preg_match("/^create index ([^ ]+) on /i"$sql$tmp)) {
  1038.                 $index $this->_fixIndexName($tmp[1]);
  1039.                 if (!empty($index)) {
  1040.                     $result[$index= true;
  1041.                 }
  1042.             }
  1043.         }
  1044.  
  1045.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1046.             $result array_change_key_case($result$db->options['field_case']);
  1047.         }
  1048.         return array_keys($result);
  1049.     }
  1050.  
  1051.     // }}}
  1052.     // {{{ createConstraint()
  1053.  
  1054.     /**
  1055.      * create a constraint on a table
  1056.      *
  1057.      * @param string $table      name of the table on which the constraint is to be created
  1058.      * @param string $name       name of the constraint to be created
  1059.      * @param array  $definition associative array that defines properties of the constraint to be created.
  1060.      *                            Currently, only one property named FIELDS is supported. This property
  1061.      *                            is also an associative with the names of the constraint fields as array
  1062.      *                            constraints. Each entry of this array is set to another type of associative
  1063.      *                            array that specifies properties of the constraint that are specific to
  1064.      *                            each field.
  1065.      *
  1066.      *                            Example
  1067.      *                               array(
  1068.      *                                   'fields' => array(
  1069.      *                                       'user_name' => array(),
  1070.      *                                       'last_login' => array()
  1071.      *                                   )
  1072.      *                               )
  1073.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1074.      * @access public
  1075.      */
  1076.     function createConstraint($table$name$definition)
  1077.     {
  1078.         $db =$this->getDBInstance();
  1079.         if (PEAR::isError($db)) {
  1080.             return $db;
  1081.         }
  1082.  
  1083.         if (!empty($definition['primary'])) {
  1084.             return $db->manager->alterTable($tablearray()falsearray('primary' => $definition['fields']));
  1085.         }
  1086.         
  1087.         if (!empty($definition['foreign'])) {
  1088.             return $db->manager->alterTable($tablearray()falsearray('foreign_keys' => array($name => $definition)));
  1089.         }
  1090.  
  1091.         $table $db->quoteIdentifier($tabletrue);
  1092.         $name  $db->getIndexName($name);
  1093.         $query = "CREATE UNIQUE INDEX $name ON $table";
  1094.         $fields = array();
  1095.         foreach ($definition['fields'as $field_name => $field{
  1096.             $field_string $field_name;
  1097.             if (!empty($field['sorting'])) {
  1098.                 switch ($field['sorting']{
  1099.                 case 'ascending':
  1100.                     $field_string.= ' ASC';
  1101.                     break;
  1102.                 case 'descending':
  1103.                     $field_string.= ' DESC';
  1104.                     break;
  1105.                 }
  1106.             }
  1107.             $fields[$field_string;
  1108.         }
  1109.         $query .= ' ('.implode(', '$fields')';
  1110.         return $db->exec($query);
  1111.     }
  1112.  
  1113.     // }}}
  1114.     // {{{ dropConstraint()
  1115.  
  1116.     /**
  1117.      * drop existing constraint
  1118.      *
  1119.      * @param string    $table        name of table that should be used in method
  1120.      * @param string    $name         name of the constraint to be dropped
  1121.      * @param string    $primary      hint if the constraint is primary
  1122.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1123.      * @access public
  1124.      */
  1125.     function dropConstraint($table$name$primary = false)
  1126.     {
  1127.         if ($primary || $name == 'PRIMARY'{
  1128.             return $this->alterTable($tablearray()falsearray('primary' => null));
  1129.         }
  1130.  
  1131.         $db =$this->getDBInstance();
  1132.         if (PEAR::isError($db)) {
  1133.             return $db;
  1134.         }
  1135.  
  1136.         //is it a FK constraint? If so, also delete the associated triggers
  1137.         $db->loadModule('Reverse'nulltrue);
  1138.         $definition $db->reverse->getTableConstraintDefinition($table$name);
  1139.         if (!PEAR::isError($definition&& !empty($definition['foreign'])) {
  1140.             //first drop the FK enforcing triggers
  1141.             $result $this->_dropFKTriggers($table$name$definition['references']['table']);
  1142.             if (PEAR::isError($result)) {
  1143.                 return $result;
  1144.             }
  1145.             //then drop the constraint itself
  1146.             return $this->alterTable($tablearray()falsearray('foreign_keys' => array($name => null)));
  1147.         }
  1148.  
  1149.         $name $db->getIndexName($name);
  1150.         return $db->exec("DROP INDEX $name");
  1151.     }
  1152.  
  1153.     // }}}
  1154.     // {{{ _dropFKTriggers()
  1155.     
  1156.     /**
  1157.      * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
  1158.      *
  1159.      * @param string $table  table name
  1160.      * @param string $fkname FOREIGN KEY constraint name
  1161.      * @param string $referenced_table  referenced table name
  1162.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1163.      * @access private
  1164.      */
  1165.     function _dropFKTriggers($table$fkname$referenced_table)
  1166.     {
  1167.         $db =$this->getDBInstance();
  1168.         if (PEAR::isError($db)) {
  1169.             return $db;
  1170.         }
  1171.  
  1172.         $triggers  $this->listTableTriggers($table);
  1173.         $triggers2 $this->listTableTriggers($referenced_table);
  1174.         if (!PEAR::isError($triggers2&& !PEAR::isError($triggers)) {
  1175.             $triggers array_merge($triggers$triggers2);
  1176.             $pattern '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
  1177.             foreach ($triggers as $trigger{
  1178.                 if (preg_match($pattern$trigger)) {
  1179.                     $result $db->exec('DROP TRIGGER '.$trigger);
  1180.                     if (PEAR::isError($result)) {
  1181.                         return $result;
  1182.                     }
  1183.                 }
  1184.             }
  1185.         }
  1186.         return MDB2_OK;
  1187.     }
  1188.  
  1189.     // }]]
  1190.     // {{{ listTableConstraints()
  1191.  
  1192.     /**
  1193.      * list all constraints in a table
  1194.      *
  1195.      * @param string $table name of table that should be used in method
  1196.      * @return mixed array of constraint names on success, a MDB2 error on failure
  1197.      * @access public
  1198.      */
  1199.     function listTableConstraints($table)
  1200.     {
  1201.         $db =$this->getDBInstance();
  1202.         if (PEAR::isError($db)) {
  1203.             return $db;
  1204.         }
  1205.  
  1206.         $table $db->quote($table'text');
  1207.         $query "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  1208.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1209.             $query.= 'LOWER(tbl_name)='.strtolower($table);
  1210.         else {
  1211.             $query.= "tbl_name=$table";
  1212.         }
  1213.         $query.= " AND sql NOT NULL ORDER BY name";
  1214.         $indexes $db->queryCol($query'text');
  1215.         if (PEAR::isError($indexes)) {
  1216.             return $indexes;
  1217.         }
  1218.  
  1219.         $result = array();
  1220.         foreach ($indexes as $sql{
  1221.             if (preg_match("/^create unique index ([^ ]+) on /i"$sql$tmp)) {
  1222.                 $index $this->_fixIndexName($tmp[1]);
  1223.                 if (!empty($index)) {
  1224.                     $result[$index= true;
  1225.                 }
  1226.             }
  1227.         }
  1228.         
  1229.         // also search in table definition for PRIMARY KEYs...
  1230.         $query "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  1231.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1232.             $query.= 'LOWER(name)='.strtolower($table);
  1233.         else {
  1234.             $query.= "name=$table";
  1235.         }
  1236.         $query.= " AND sql NOT NULL ORDER BY name";
  1237.         $table_def $db->queryOne($query'text');
  1238.         if (PEAR::isError($table_def)) {
  1239.             return $table_def;
  1240.         }
  1241.         if (preg_match("/\bPRIMARY\s+KEY\b/i"$table_def$tmp)) {
  1242.             $result['primary'= true;
  1243.         }
  1244.  
  1245.         // ...and for FOREIGN KEYs
  1246.         if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx"$table_def$tmp)) {
  1247.             foreach ($tmp[1as $fk{
  1248.                 $result[$fk= true;
  1249.             }
  1250.         }
  1251.  
  1252.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1253.             $result array_change_key_case($result$db->options['field_case']);
  1254.         }
  1255.         return array_keys($result);
  1256.     }
  1257.  
  1258.     // }}}
  1259.     // {{{ createSequence()
  1260.  
  1261.     /**
  1262.      * create sequence
  1263.      *
  1264.      * @param string    $seq_name     name of the sequence to be created
  1265.      * @param string    $start         start value of the sequence; default is 1
  1266.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1267.      * @access public
  1268.      */
  1269.     function createSequence($seq_name$start = 1)
  1270.     {
  1271.         $db =$this->getDBInstance();
  1272.         if (PEAR::isError($db)) {
  1273.             return $db;
  1274.         }
  1275.  
  1276.         $sequence_name $db->quoteIdentifier($db->getSequenceName($seq_name)true);
  1277.         $seqcol_name $db->quoteIdentifier($db->options['seqcol_name']true);
  1278.         $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";
  1279.         $res $db->exec($query);
  1280.         if (PEAR::isError($res)) {
  1281.             return $res;
  1282.         }
  1283.         if ($start == 1{
  1284.             return MDB2_OK;
  1285.         }
  1286.         $res $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')');
  1287.         if (!PEAR::isError($res)) {
  1288.             return MDB2_OK;
  1289.         }
  1290.         // Handle error
  1291.         $result $db->exec("DROP TABLE $sequence_name");
  1292.         if (PEAR::isError($result)) {
  1293.             return $db->raiseError($resultnullnull,
  1294.                 'could not drop inconsistent sequence table'__FUNCTION__);
  1295.         }
  1296.         return $db->raiseError($resnullnull,
  1297.             'could not create sequence table'__FUNCTION__);
  1298.     }
  1299.  
  1300.     // }}}
  1301.     // {{{ dropSequence()
  1302.  
  1303.     /**
  1304.      * drop existing sequence
  1305.      *
  1306.      * @param string    $seq_name     name of the sequence to be dropped
  1307.      * @return mixed MDB2_OK on success, a MDB2 error on failure
  1308.      * @access public
  1309.      */
  1310.     function dropSequence($seq_name)
  1311.     {
  1312.         $db =$this->getDBInstance();
  1313.         if (PEAR::isError($db)) {
  1314.             return $db;
  1315.         }
  1316.  
  1317.         $sequence_name $db->quoteIdentifier($db->getSequenceName($seq_name)true);
  1318.         return $db->exec("DROP TABLE $sequence_name");
  1319.     }
  1320.  
  1321.     // }}}
  1322.     // {{{ listSequences()
  1323.  
  1324.     /**
  1325.      * list all sequences in the current database
  1326.      *
  1327.      * @return mixed array of sequence names on success, a MDB2 error on failure
  1328.      * @access public
  1329.      */
  1330.     function listSequences()
  1331.     {
  1332.         $db =$this->getDBInstance();
  1333.         if (PEAR::isError($db)) {
  1334.             return $db;
  1335.         }
  1336.  
  1337.         $query "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  1338.         $table_names $db->queryCol($query);
  1339.         if (PEAR::isError($table_names)) {
  1340.             return $table_names;
  1341.         }
  1342.         $result = array();
  1343.         foreach ($table_names as $table_name{
  1344.             if ($sqn $this->_fixSequenceName($table_nametrue)) {
  1345.                 $result[$sqn;
  1346.             }
  1347.         }
  1348.         if ($db->options['portability'MDB2_PORTABILITY_FIX_CASE{
  1349.             $result array_map(($db->options['field_case'== CASE_LOWER ? 'strtolower' 'strtoupper')$result);
  1350.         }
  1351.         return $result;
  1352.     }
  1353.  
  1354.     // }}}
  1355. }
  1356. ?>

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