Changeset 136 for trunk/lib/DB.inc.php


Ignore:
Timestamp:
Jun 3, 2006 7:47:48 PM (18 years ago)
Author:
scdev
Message:

Q - Merged branches/2.0singleton into trunk. Completed updating classes to use singleton methods. Implemented tests. Fixed some bugs. Changed some interfaces.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/lib/DB.inc.php

    r119 r136  
    44 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
    55 *
    6  * DB abstraction layer.
     6 * Very lightweight DB semi-abstraction layer. Mainly to catch errors with mysql_query, with some goodies.
    77 *
    88 * @author  Quinn Comendant <quinn@strangecode.com>
    9  * @version 1.0.1
     9 * @version 2.1
    1010 */
    1111
    1212class DB {
    1313
    14     // If DB::connect has successfully opened a db connection.
     14    // If $db->connect has successfully opened a db connection.
    1515    var $_connected = false;
    1616
    17     // Database handler.
     17    // Database handle.
    1818    var $dbh;
    1919
     
    3030        'db_pass' => null,
    3131
    32         // Debugging.
    33         'db_always_debug' => false, // TRUE = display all SQL queries.
    34         'db_debug' => false, // TRUE = display db errors.
    35         'db_die_on_failure' => false, // TRUE = script stops on db error.
     32        // Display all SQL queries.
     33        'db_always_debug' => false,
     34
     35        // Display db errors.
     36        'db_debug' => false,
     37       
     38        // Script stops on db error.
     39        'db_die_on_failure' => false,
    3640    );
    3741
     
    4953     * This method enforces the singleton pattern for this class.
    5054     *
    51      * @return  object  Reference to the global SessionCache object.
     55     * @return  object  Reference to the global DB object.
    5256     * @access  public
    5357     * @static
     
    6569
    6670    /**
    67      * Constructor.
    68      */
    69     function DB()
    70     {
    71         // Initialize default params.
     71     * Set (or overwrite existing) parameters by passing an array of new parameters.
     72     *
     73     * @access public
     74     *
     75     * @param  array    $params     Array of parameters (key => val pairs).
     76     */
     77    function setParam($params)
     78    {
     79        $app =& App::getInstance();
     80   
    7281        if (isset($params) && is_array($params)) {
    7382            // Merge new parameters with old overriding only those passed.
    7483            $this->_params = array_merge($this->_params, $params);
    75         }
    76     }
    77 
    78     /**
    79      * Set (or overwrite existing) parameters by passing an array of new parameters.
     84        } else {
     85            $app->logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
     86        }
     87    }
     88
     89    /**
     90     * Return the value of a parameter, if it exists.
    8091     *
    8192     * @access public
    82      *
    83      * @param  array    $params     Array of parameters (key => val pairs).
    84      */
    85     function setParam($params)
    86     {
    87         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    88             $_this =& DB::getInstance();
    89         }
    90 
    91         if (isset($params) && is_array($params)) {
    92             // Merge new parameters with old overriding only those passed.
    93             $_this->_params = array_merge($_this->_params, $params);
     93     * @param string $param        Which parameter to return.
     94     * @return mixed               Configured parameter value.
     95     */
     96    function getParam($param)
     97    {
     98        $app =& App::getInstance();
     99   
     100        if (isset($this->_params[$param])) {
     101            return $this->_params[$param];
    94102        } else {
    95             App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
    96         }
    97     }
    98 
    99     /**
    100      * Return the value of a parameter.
    101      *
    102      * @access  public
    103      *
    104      * @param   string  $param      The key of the parameter to return.
    105      *
    106      * @return  mixed               Parameter value.
    107      */
    108     function getParam($param)
    109     {
    110         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    111             $_this =& DB::getInstance();
    112         }
    113 
    114         if (isset($_this->_params[$param])) {
    115             return $_this->_params[$param];
    116         } else {
    117             App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
     103            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_NOTICE, __FILE__, __LINE__);
    118104            return null;
    119105        }
     
    129115    function connect()
    130116    {
    131         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    132             $_this =& DB::getInstance();
    133         }
    134 
    135         if (!$_this->getParam('db_name') || !$_this->getParam('db_user') || !$_this->getParam('db_pass')) {
    136             App::logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
     117        $app =& App::getInstance();
     118   
     119        if (!$this->getParam('db_name') || !$this->getParam('db_user') || !$this->getParam('db_pass')) {
     120            $app->logMsg('Database credentials missing.', LOG_EMERG, __FILE__, __LINE__);
    137121            return false;
    138122        }
    139123
    140124        // Connect to database. Always create a new link to the server.
    141         if ($_this->dbh = mysql_connect($_this->getParam('db_server'), $_this->getParam('db_user'), $_this->getParam('db_pass'), true)) {
     125        if ($this->dbh = mysql_connect($this->getParam('db_server'), $this->getParam('db_user'), $this->getParam('db_pass'), true)) {
    142126            // Select database
    143             mysql_select_db($_this->getParam('db_name'), $_this->dbh);
     127            mysql_select_db($this->getParam('db_name'), $this->dbh);
    144128        }
    145129
    146130        // Test for connection errors.
    147         if (!$_this->dbh || mysql_error($_this->dbh)) {
    148             $mysql_error_msg = $_this->dbh ? 'Codebase MySQL error: (' . mysql_errno($_this->dbh) . ') ' . mysql_error($_this->dbh) : 'Codebase MySQL error: Could not connect to server.';
    149             App::logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
     131        if (!$this->dbh || mysql_error($this->dbh)) {
     132            $mysql_error_msg = $this->dbh ? 'Codebase MySQL error: (' . mysql_errno($this->dbh) . ') ' . mysql_error($this->dbh) : 'Codebase MySQL error: Could not connect to server.';
     133            $app->logMsg($mysql_error_msg, LOG_EMERG, __FILE__, __LINE__);
    150134
    151135            // Print helpful or pretty error?
    152             if ($_this->getParam('db_debug')) {
     136            if ($this->getParam('db_debug')) {
    153137                echo $mysql_error_msg . "\n";
    154             } else {
    155                 echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
    156138            }
    157139
    158140            // Die or continue without connection?
    159             if ($_this->getParam('db_die_on_failure')) {
     141            if ($this->getParam('db_die_on_failure')) {
    160142                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
    161143                die;
     
    166148
    167149        // DB connection success!
    168         $_this->_connected = true;
     150        $this->_connected = true;
    169151
    170152        // Tell MySQL what character set we're useing. Available only on MySQL verions > 4.01.01.
    171         $_this->query("/*!40101 SET NAMES '" . $_this->mysql_character_sets[strtolower(App::getParam('character_set'))] . "' */");
     153        $this->query("/*!40101 SET NAMES '" . $this->mysql_character_sets[strtolower($app->getParam('character_set'))] . "' */");
    172154
    173155        return true;
     
    183165    function close()
    184166    {
    185         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    186             $_this =& DB::getInstance();
    187         }
    188 
    189         if (!$_this->_connected) {
    190             return false;
    191         }
    192 
    193         mysql_close($_this->dbh);
     167        if (!$this->_connected) {
     168            return false;
     169        }
     170
     171        return mysql_close($this->dbh);
    194172    }
    195173
     
    204182    function getDBH()
    205183    {
    206         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    207             $_this =& DB::getInstance();
    208         }
    209 
    210         if (!$_this->_connected) {
    211             return false;
    212         }
    213 
    214         return $_this->dbh;
     184        if (!$this->_connected) {
     185            return false;
     186        }
     187
     188        return $this->dbh;
    215189    }
    216190
     
    224198    function isConnected()
    225199    {
    226         return $this->_connected;
     200        return (true === $this->_connected);
    227201    }
    228202   
     
    238212    function escapeString($string)
    239213    {
    240         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    241             $_this =& DB::getInstance();
    242         }
    243         return mysql_real_escape_string($string, $_this->dbh);
     214        if (!$this->_connected) {
     215            return false;
     216        }
     217
     218        return mysql_real_escape_string($string, $this->dbh);
    244219    }
    245220
     
    253228     */
    254229    function query($query, $debug=false)
    255     {
     230    {   
    256231        static $_query_count = 0;
    257 
    258         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    259             $_this =& DB::getInstance();
    260         }
    261 
    262         if (!$_this->_connected) {
     232        $app =& App::getInstance();
     233
     234        if (!$this->_connected) {
    263235           return false;
    264236        }
     
    266238        $_query_count++;
    267239        $debugqry = preg_replace("/\n[\t ]+/", "\n", $query);
    268         if ($_this->getParam('db_always_debug') || $debug) {
     240        if ($this->getParam('db_always_debug') || $debug) {
    269241            echo "<!-- ----------------- Query $_query_count ---------------------\n$debugqry\n-->\n";
    270242        }
    271243
    272244        // Execute!
    273         $qid = mysql_query($query, $_this->dbh);
     245        $qid = mysql_query($query, $this->dbh);
    274246
    275247        // Error checking.
    276         if (!$qid || mysql_error($_this->dbh)) {
    277             if ($_this->getParam('db_debug')) {
    278                 echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($_this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
     248        if (!$qid || mysql_error($this->dbh)) {
     249            if ($this->getParam('db_debug')) {
     250                echo '<pre style="padding:2em; background:#ddd; font:9px monaco;">' . wordwrap(mysql_error($this->dbh)) . '<hr>' . htmlspecialchars($debugqry) . '</pre>';
    279251            } else {
    280252                echo _("This page is temporarily unavailable. It should be back up in a few minutes.");
    281253            }
    282             App::logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($_this->dbh), mysql_error($_this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
    283             if ($_this->getParam('db_die_on_failure')) {
     254            $app->logMsg(sprintf('MySQL error %s: %s in query: %s', mysql_errno($this->dbh), mysql_error($this->dbh), $debugqry), LOG_EMERG, __FILE__, __LINE__);
     255            if ($this->getParam('db_die_on_failure')) {
    284256                echo "\n\n<!-- Script execution stopped out of embarrassment. -->";
    285257                die;
     
    302274    function tableExists($table, $use_cached_results=true)
    303275    {
    304         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    305             $_this =& DB::getInstance();
    306         }
    307 
    308         if (!$_this->_connected) {
    309             return false;
    310         }
    311 
    312         if (!isset($_this->existing_tables) || !$use_cached_results) {
    313             $_this->existing_tables = array();
    314             $qid = $_this->query("SHOW TABLES");
     276        $app =& App::getInstance();
     277   
     278        if (!$this->_connected) {
     279            return false;
     280        }
     281
     282        if (!isset($this->existing_tables) || !$use_cached_results) {
     283            $this->existing_tables = array();
     284            $qid = $this->query("SHOW TABLES");
    315285            while (list($row) = mysql_fetch_row($qid)) {
    316                 $_this->existing_tables[] = $row;
    317             }
    318         }
    319         if (in_array($table, $_this->existing_tables)) {
     286                $this->existing_tables[] = $row;
     287            }
     288        }
     289        if (in_array($table, $this->existing_tables)) {
    320290            return true;
    321291        } else {
    322             App::logMsg(sprintf('nonexistent DB table: %s.%s', $_this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
     292            $app->logMsg(sprintf('nonexistent DB table: %s.%s', $this->getParam('db_name'), $table), LOG_ALERT, __FILE__, __LINE__);
    323293            return false;
    324294        }
     
    336306    function columnExists($table, $columns, $strict=true, $use_cached_results=true)
    337307    {
    338         if (!isset($_this) || !is_a($_this, 'DB') && !is_subclass_of($_this, 'DB')) {
    339             $_this =& DB::getInstance();
    340         }
    341 
    342         if (!$_this->_connected) {
     308        if (!$this->_connected) {
    343309            return false;
    344310        }
    345311
    346312        // Ensure the table exists.
    347         if (!$_this->tableExists($table, $use_cached_results)) {
     313        if (!$this->tableExists($table, $use_cached_results)) {
    348314            return false;
    349315        }
     
    354320        }
    355321
    356         if (!isset($_this->table_columns[$table]) || !$use_cached_results) {
     322        if (!isset($this->table_columns[$table]) || !$use_cached_results) {
    357323            // Populate and cache array of current columns for this table.
    358             $_this->table_columns[$table] = array();
    359             $qid = $_this->query("DESCRIBE $table");
     324            $this->table_columns[$table] = array();
     325            $qid = $this->query("DESCRIBE $table");
    360326            while ($row = mysql_fetch_row($qid)) {
    361                 $_this->table_columns[$table][] = $row[0];
     327                $this->table_columns[$table][] = $row[0];
    362328            }
    363329        }
     
    366332            // Do an exact comparison of table schemas.
    367333            sort($columns);
    368             sort($_this->table_columns[$table]);
    369             return $_this->table_columns[$table] == $columns;
     334            sort($this->table_columns[$table]);
     335            return $this->table_columns[$table] == $columns;
    370336        } else {
    371337            // Only check that the specified columns are available in the table.
    372             $match_columns = array_intersect($_this->table_columns[$table], $columns);
     338            $match_columns = array_intersect($this->table_columns[$table], $columns);
    373339            sort($columns);
    374340            sort($match_columns);
Note: See TracChangeset for help on using the changeset viewer.