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

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