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

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