kernel
[ class tree: kernel ] [ index: kernel ] [ all elements ]

Source for file BitDbBase.php

Documentation is available at BitDbBase.php

  1. <?php
  2. /**
  3.  * ADOdb Library interface Class
  4.  *
  5.  * @package kernel
  6.  * @version $Header$
  7.  *
  8.  *  Copyright (c) 2004 bitweaver.org
  9.  *  Copyright (c) 2003 tikwiki.org
  10.  *  Copyright (c) 2002-2003, Luis Argerich, Garland Foster, Eduardo Polidor, et. al.
  11.  *  All Rights Reserved. See below for details and a complete list of authors.
  12.  *  Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See http://www.gnu.org/copyleft/lesser.html for details
  13.  *
  14.  * @author spider <spider@steelsun.com>
  15.  */
  16.  
  17. /**
  18.  * ensure your AdoDB install is a subdirectory off your include path
  19.  */
  20.  
  21. define'BIT_QUERY_DEFAULT'-)// deprecated constant for no cache time
  22. define'BIT_QUERY_CACHE_DISABLE'-);
  23. define'BIT_MAX_RECORDS'-);
  24.  
  25. // num queries has to be global
  26. global $gNumQueries;
  27. $gNumQueries 0;
  28.  
  29.  
  30. /**
  31.  * This class is used for database access and provides a number of functions to help
  32.  * with database portability.
  33.  *
  34.  * Currently used as a base class, this class should be optional to ensure bitweaver
  35.  * continues to function correctly, without a valid database connection.
  36.  *
  37.  * @package kernel
  38.  */
  39. class BitDb {
  40.     /**
  41.     * Used to store the ADODB db object used to access the database.
  42.     * This is just a pointer to a single global variable used by all classes.
  43.     * This limits database connections to just one per request.
  44.     * @private
  45.     */
  46.     var $mDb;
  47.     /**
  48.     * Used to identify the ADODB db object
  49.     * @private
  50.     */
  51.     var $mName;
  52.     /**
  53.     * Used to store the ADODB db object type
  54.     * @private
  55.     */
  56.     var $mType;
  57.     /**
  58.     * Used to store failed commands
  59.     * @private
  60.     */
  61.     var $mFailed = array();
  62.     /**
  63.     * Used to store the number of queries executed.
  64.     * @private
  65.     */
  66.     var $mNumQueries = 0;
  67.     /**
  68.     * Used to store the total query time for this request.
  69.     * @private
  70.     */
  71.     var $mQueryTime = 0;
  72.     /**
  73.     * Case sensitivity flag used in convertQuery
  74.     * @private
  75.     */
  76.     var $mCaseSensitive = TRUE;
  77.     /**
  78.     * Used to enable AdoDB caching
  79.     * @private
  80.     */
  81.     var $mCacheFlag;
  82.     /**
  83.     * Used to determine SQL debug output. BitDbAdodb overrides associated methods to use the debugging mechanisms built into ADODB
  84.     * @private
  85.     */
  86.     var $mDebug;
  87.     /**
  88.     * Determines if fatal query functions should terminate script execution. Defaults to TRUE. Can be deactived for things like expected duplicate inserts
  89.     * @private
  90.     */
  91.     var $mFatalActive;
  92.     /**
  93.     * During initialisation, database parameters are passed to the class.
  94.     * If these parameters are not valid, class will not be initialised.
  95.     */
  96.     function BitDb({
  97.         global $gDebug;
  98.         $this->mDebug = $gDebug;
  99.         $this->mCacheFlag = TRUE;
  100.         $this->mNumQueries = 0;
  101.         $this->mQueryTime = 0;
  102.         $this->setFatalActive();
  103.         global $gBitDbCaseSensitivity;
  104.         $this->setCaseSensitivity$gBitDbCaseSensitivity );
  105.     }
  106.     /**
  107.     * This function contains any pre-connection work
  108.     * @private
  109.     * @todo investigate if this is the correct way to do it.
  110.     */
  111.     function preDBConnection({
  112.         // Pre connection setup
  113.         if(isset($this->mType)) {
  114.             // we have a db we're gonna try to load
  115.             switch ($this->mType{
  116.                 case "sybase":
  117.                 // avoid database change messages
  118.                 ini_set("sybct.min_server_severity""11");
  119.                 break;
  120.             }
  121.         else {
  122.             die("No database type specified");
  123.         }
  124.     }
  125.     /**
  126.     * This function contains any post-connection work
  127.     * @private
  128.     * @todo investigate if this is the correct way to do it.
  129.     * @todo remove the BIT_DB_PREFIX, change to a member variable
  130.     * @todo get spiderr to explain the schema line
  131.     */
  132.     function postDBConnection({
  133.         // Post connection setup
  134.         switch ($this->mType{
  135.             case "sybase":
  136.             case "mssql":
  137.                 $this->mDb->Execute("set quoted_identifier on");
  138.                 break;
  139.             case "mysql":
  140.                 $version $this->getDatabaseVersion();
  141.                 if( ($version['major'>= && $version['minor'>=1|| ($version['major'>= 5) ) {
  142.                     $this->mDb->Execute("set session sql_mode='PIPES_AS_CONCAT'");
  143.                 }
  144.                 break;
  145.             case "postgres":
  146.                 // Do a little prep work for postgres, no break, cause we want default case too
  147.                 if (defined("BIT_DB_PREFIX"&& preg_match"/\./"BIT_DB_PREFIX) ) {
  148.                     $schema preg_replace("/[`\.]/"""BIT_DB_PREFIX);
  149.                     // Assume we want to dump in a schema, so set the search path and nuke the prefix here.
  150.                     // $result = $this->mDb->Execute( "SET search_path TO $schema,public" );
  151.                 }
  152.                 break;
  153.         }
  154.     }
  155.  
  156.     /**
  157.     * Determines if the database connection is valid
  158.     * @return true if DB connection is valid, false if not
  159.     */
  160.     function isValid({
  161.         return!empty$this->mDb ) );
  162.     }
  163.     /**
  164.     * Determines if the database connection is valid
  165.     * @return true if DB connection is valid, false if not
  166.     */
  167.     function isFatalActive({
  168.         return$this->mFatalActive );
  169.     }
  170.     /**
  171.     * Determines if the database connection is valid
  172.     * @return true if DB connection is valid, false if not
  173.     */
  174.     function setFatalActive$pActive=TRUE {
  175.         $this->mFatalActive = $pActive;
  176.     }
  177.     /**
  178.     * Used to start query timer if in debug mode
  179.     */
  180.     function queryStart({
  181.         global $gBitTimer;
  182.         $this->mQueryLap $gBitTimer->elapsed();
  183.     }
  184.     /** will activate ADODB like native debugging output
  185.     * @param pLevel debugging level - FALSE is off, TRUE is on, 99 is verbose
  186.     ***/
  187.     function debug$pLevel=99 {
  188.         $this->mDebug = $pLevel;
  189.     }
  190.  
  191.     /** returns the level of query debugging output
  192.     * @return pLevel debugging level - FALSE is off, TRUE is on, 99 is verbose
  193.     ***/
  194.     function getDebugLevel({
  195.         return$this->mDebug );
  196.     }
  197.     /**
  198.     * Sets the case sensitivity mode which is used in convertQuery
  199.     * @return true if DB connection is valid, false if not
  200.     */
  201.     function setCaseSensitivity$pSensitivity=TRUE {
  202.         $this->mCaseSensitive = $pSensitivity;
  203.     }
  204.     /**
  205.     * Sets the case sensitivity mode which is used in convertQuery
  206.     * @return true if DB connection is valid, false if not
  207.     */
  208.     function getCaseSensitivity$pSensitivity=TRUE {
  209.         switch ($this->mType{
  210.             case "firebird":
  211.             case "oci8":
  212.             case "oci8po":
  213.                 // Force Oracle to always be insensitive
  214.                 $ret FALSE;
  215.                 break;
  216.             default:
  217.                 $ret $this->mCaseSensitive;
  218.                 break;
  219.         }
  220.  
  221.         return$ret );
  222.     }
  223.     /**
  224.     * Used to stop query tracking and output results if in debug mode
  225.     */
  226.     function queryComplete({
  227.         global $gNumQueries;
  228.         //count the number of queries made
  229.         $gNumQueries++;
  230.         $this->mNumQueries++;
  231.         global $gBitTimer;
  232.         $interval $gBitTimer->elapsed($this->mQueryLap;
  233.         $this->mQueryTime += $interval;
  234.         if$this->getDebugLevel() ) {
  235.             $style $interval .5 'color:red;' (( $interval .15 'color:orange;' '');
  236.             $querySpeed $interval .5 tra'VERY SLOW' )(( $interval .15 tra'SLOW' 'complete');
  237.             print '<p style="'.$style.'">
  238.                     <span style="display:inline-block;width:30%">### Query: <strong>'.$gNumQueries.'</strong> '.$querySpeed.'</span>
  239.                     <span style="display:inline-block;width:33%">Start time: '.round$this->mQueryLap).'</span> 
  240.                     <span style="display:inline-block;width:33%">### Query run time: '.round$interval).'</span></p>';
  241.             flush();
  242.         }
  243.         $this->mQueryLap 0;
  244.     }
  245.  
  246.     /**
  247.     * Used to create tables - most commonly from package/schema_inc.php files
  248.     * @todo remove references to BIT_DB_PREFIX, us a member function
  249.     * @param pTables an array of tables and creation information in DataDict
  250.     *  style
  251.     * @param pOptions an array of options used while creating the tables
  252.     * @return true|false
  253.     *  true if created with no errors | false if errors are stored in $this->mFailed
  254.     */
  255.     function createTables($pTables$pOptions array()) {
  256.         // PURE VIRTUAL
  257.     }
  258.  
  259.     /**
  260.     * Used to check if tables already exists.
  261.     * @todo should be used to confirm tables are already created
  262.     * @param pTable the table name
  263.     * @return true if table already exists
  264.     */
  265.     function tableExists($pTable{
  266.         // PURE VIRTUAL
  267.     }
  268.  
  269.     /**
  270.     * Used to drop tables
  271.     * @todo remove references to BIT_DB_PREFIX, us a member function
  272.     * @param pTables an array of table names to drop
  273.     * @return true | false
  274.     *  true if dropped with no errors |
  275.     *  false if errors are stored in $this->mFailed
  276.     */
  277.     function dropTables($pTables{
  278.         // PURE VIRTUAL
  279.     }
  280.  
  281.     /**
  282.     * Function to set ADODB query caching member variable
  283.     * @param pCacheExecute flag to enable or disable ADODB query caching
  284.     * @return nothing 
  285.     */
  286.     function setCaching$pCacheFlag=TRUE {
  287.         $this->mCacheFlag = $pCacheFlag;
  288.     }
  289.  
  290.     /**
  291.     * Function to set ADODB query caching member variable
  292.     * @param pCacheExecute flag to enable or disable ADODB query caching
  293.     * @return nothing 
  294.     */
  295.     function isCachingActive({
  296.         return$this->mCacheFlag );
  297.     }
  298.  
  299.     /**
  300.     * Quotes a string to be sent to the database
  301.     * @param pStr string to be quotes
  302.     * @return quoted string using AdoDB->qstr()
  303.     */
  304.     function qstr($pStr{
  305.         // PURE VIRTUAL
  306.     }
  307.  
  308.     /** Queries the database, returning an error if one occurs, rather
  309.     * than exiting while printing the error. -rlpowell
  310.     * @param pQuery the SQL query. Use backticks (`) to quote all table
  311.     *  and attribute names for AdoDB to quote appropriately.
  312.     * @param pError the error string to modify and return
  313.     * @param pValues an array of values used in a parameterised query
  314.     * @param pNumRows the number of rows (LIMIT) to return in this query
  315.     * @param pOffset the row number to begin returning rows from. Used in
  316.     * @return an AdoDB RecordSet object
  317.     *  conjunction with $pNumRows
  318.     * @todo currently not used anywhere.
  319.     */
  320.     function queryError$pQuery&$pError$pValues NULL$pNumRows = -1$pOffset = -{
  321.         // PURE VIRTUAL
  322.     }
  323.  
  324.     /** Queries the database reporting an error if detected
  325.     * than exiting while printing the error. -rlpowell
  326.     * @param pQuery the SQL query. Use backticks (`) to quote all table
  327.     *  and attribute names for AdoDB to quote appropriately.
  328.     * @param pValues an array of values used in a parameterised query
  329.     * @param pNumRows the number of rows (LIMIT) to return in this query
  330.     * @param pOffset the row number to begin returning rows from. Used in
  331.     *  conjunction with $pNumRows
  332.     * @return an AdoDB RecordSet object
  333.     */
  334.     function query($query$values null$numrows BIT_QUERY_DEFAULT$offset BIT_QUERY_DEFAULT$pCacheTime=BIT_QUERY_DEFAULT {
  335.         // PURE VIRTUAL
  336.     }
  337.  
  338.     /**
  339.     * ADODB compatibility functions for bitcommerce
  340.     */
  341.     function Execute($pQuery$pNumRows false$zf_cache false$pCacheTime=BIT_QUERY_DEFAULT{
  342.         if $this->mType == "firebird"{
  343.             $pQuery preg_replace("/\\\'/""''"$pQuery);
  344.             $pQuery preg_replace("/ NOW/"" 'NOW'"$pQuery);
  345.             $pQuery preg_replace("/now\(\)/""'NOW'"$pQuery);
  346.         }
  347.         return $this->query$pQueryNULL$pNumRowsNULL$pCacheTime );
  348.     }
  349.  
  350.     /**
  351.      * Create a list of tables available in the current database
  352.      *
  353.      * @param ttype can either be 'VIEW' or 'TABLE' or false.
  354.      *          If false, both views and tables are returned.
  355.      *         "VIEW" returns only views
  356.      *         "TABLE" returns only tables
  357.      * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
  358.      * @param mask  is the input mask - only supported by oci8 and postgresql
  359.      *
  360.      * @return  array of tables for current database.
  361.     */
  362.     function MetaTables$ttype false$showSchema false$mask=false {
  363.         // PURE VIRTUAL
  364.     }
  365.  
  366.     /**
  367.      * List columns in a database as an array of ADOFieldObjects.
  368.      * See top of file for definition of object.
  369.      *
  370.      * @param table    table name to query
  371.      * @param upper    uppercase table name (required by some databases)
  372.      * @param schema is optional database schema to use - not supported by all databases.
  373.      *
  374.      * @return  array of ADOFieldObjects for current table.
  375.      */
  376.     function MetaColumns($table,$normalize=true$schema=false{
  377.         // PURE VIRTUAL
  378.     }
  379.  
  380.     /**
  381.      * List indexes in a database as an array of ADOFieldObjects.
  382.      * See top of file for definition of object.
  383.      *
  384.      * @param table    table name to query
  385.      * @param primary list primary indexes
  386.      * @param owner list owner of index
  387.      *
  388.      * @return  array of ADOFieldObjects for current table.
  389.      */
  390.     function MetaIndexes($table,$primary=false$owner=false{
  391.         // PURE VIRTUAL
  392.     }
  393.  
  394.  
  395.     /** Executes the SQL and returns all elements of the first column as a 1-dimensional array. The recordset is discarded for you automatically. If an error occurs, false is returned.
  396.     * See AdoDB GetCol() function for more detail.
  397.     * @param pQuery the SQL query. Use backticks (`) to quote all table
  398.     *  and attribute names for AdoDB to quote appropriately.
  399.     * @param pValues an array of values used in a parameterised query
  400.     * @param pForceArray if set to true, when an array is created for each value
  401.     * @param pFirst2Cols if set to true, only returns the first two columns
  402.     * @return the associative array, or false if an error occurs
  403.     * @todo not currently used anywhere
  404.     */
  405.  
  406.     function getCol$pQuery$pValues=FALSE$pTrim=FALSE {
  407.         // PURE VIRTUAL
  408.     }
  409.     /** Returns an associative array for the given query.
  410.     * See AdoDB GetAssoc() function for more detail.
  411.     * @param pQuery the SQL query. Use backticks (`) to quote all table
  412.     *  and attribute names for AdoDB to quote appropriately.
  413.     * @param pValues an array of values used in a parameterised query
  414.     * @param pForceArray if set to true, when an array is created for each value
  415.     * @param pFirst2Cols if set to true, only returns the first two columns
  416.     * @return the associative array, or false if an error occurs
  417.     */
  418.     function getArray$pQuery$pValues=FALSE$pForceArray=FALSE$pFirst2Cols=FALSE$pCacheTime=BIT_QUERY_DEFAULT {
  419.         // PURE VIRTUAL
  420.     }
  421.  
  422.     /** Returns an associative array for the given query.
  423.     * See AdoDB GetAssoc() function for more detail.
  424.     * @param pQuery the SQL query. Use backticks (`) to quote all table
  425.     *  and attribute names for AdoDB to quote appropriately.
  426.     * @param pValues an array of values used in a parameterised query
  427.     * @param pForceArray if set to true, when an array is created for each value
  428.     * @param pFirst2Cols if set to true, only returns the first two columns
  429.     * @return the associative array, or false if an error occurs
  430.     */
  431.     function getAssoc$pQuery$pValues=FALSE$pForceArray=FALSE$pFirst2Cols=FALSE$pCacheTime=BIT_QUERY_DEFAULT {
  432.         // PURE VIRTUAL
  433.     }
  434.  
  435.     /** Executes the SQL and returns the first row as an array. The recordset and remaining rows are discarded for you automatically. If an error occurs, false is returned.
  436.     * See AdoDB GetRow() function for more detail.
  437.     * @param pQuery the SQL query. Use backticks (`) to quote all table
  438.     *  and attribute names for AdoDB to quote appropriately.
  439.     * @param pValues an array of values used in a parameterised query
  440.     * @return returns the first row as an array, or false if an error occurs
  441.     */
  442.     function getRow$pQuery$pValues=FALSE$pCacheTime=BIT_QUERY_DEFAULT {
  443.         // PURE VIRTUAL
  444.     }
  445.  
  446.     /** Returns a single column value from the database.
  447.     * @param pQuery the SQL query. Use backticks (`) to quote all table
  448.     *  and attribute names for AdoDB to quote appropriately.
  449.     * @param pValues an array of values used in a parameterised query
  450.     * @param pReportErrors report errors to STDOUT
  451.     * @param pOffset the row number to begin returning rows from.
  452.     * @return the associative array, or false if an error occurs
  453.     */
  454.     function getOne($pQuery$pValues=NULL$pNumRows=NULL$pOffset=NULL$pCacheTime BIT_QUERY_DEFAULT {
  455.         // PURE VIRTUAL
  456.     }
  457.  
  458.     /**
  459.     * This function will take a set of fields identified by an associative array - $insertData
  460.     * generate a suitable SQL script
  461.     * and insert the data into the specified table - $insertTable
  462.     * @param insertTable Name of the table to be inserted into
  463.     * @param insertData Array of data to be inserted. Array keys provide the field names
  464.     * @return Error status of the insert
  465.     */
  466.     function associateInsert$insertTable$insertData {
  467.         $setSql '`'.implodearray_keys$insertData )'`, `' ).'`' );
  468.         //stupid little loop to generate question marks. Start at one, and tack at the end to ease dealing with comma
  469.         $valueSql '';
  470.         for$i 1$i count$insertData )$i++ {
  471.             $valueSql .= '?, ';
  472.         }
  473.         $valueSql .= '?';
  474.  
  475.         if$insertTable[0!= '`' {
  476.             $insertTable '`'.$insertTable.'`';
  477.         }
  478.  
  479.         $query "INSERT INTO $insertTable ( $setSql ) VALUES ( $valueSql )";
  480.  
  481.         $result $this->query$queryarray_values$insertData ) );
  482.  
  483.         return$result );
  484.     }
  485.  
  486.     /**
  487.     * This function will take a set of fields identified by an associative array - $updateData
  488.     * generate a suitable SQL script
  489.     * update the data into the specified table
  490.     * at the location identified in updateId which holds a name and value entry
  491.     * @param updateTable Name of the table to be updated
  492.     * @param updateData Array of data to be changed. Array keys provide the field names
  493.     *  If an array key contains an '=' it will assumed to already be properly quoted.
  494.     *  This allows use of keys like this: `column_name` = `column_name` + ?
  495.     * @param updateId Array identifying the record to update.
  496.     *         Array key 'name' provide the field name, and 'value' the record key
  497.     * @return Error status of the insert
  498.     */
  499.     function associateUpdate$updateTable$updateData$updateId {
  500.         $setSql '';
  501.         foreach$updateData as $key=>$value {
  502.             if (strpos($key,'='=== false{
  503.                 $setSql .= ", `$key` = ?";
  504.             }
  505.             else
  506.                 $setSql .= ', ' $key;
  507.             }
  508.         $setSql =     substr($setSql,1);
  509.         $bindVars array_values$updateData );
  510.         $keyNames '`'.implodearray_keys$updateId )'`=? AND `' ).'`=?' );
  511.         $keyVars array_values$updateId );
  512.         $bindVars array_merge$bindVars$keyVars );
  513.         if$updateTable[0!= '`' {
  514.             $updateTable '`'.$updateTable.'`';
  515.         }
  516.  
  517.         $query "UPDATE $updateTable SET $setSql WHERE $keyNames";
  518.         $result $this->query$query$bindVars );
  519.  
  520.         return$result );
  521.     }
  522.  
  523.     /**
  524.     * A database portable Sequence management function.
  525.     *
  526.     * @param pSequenceName Name of the sequence to be used
  527.     *         It will be created if it does not already exist
  528.     * @return        if not supported, otherwise a sequence id
  529.     */
  530.     function GenID$pSequenceName$pUseDbPrefix true {
  531.         // PURE VIRTUAL
  532.     }
  533.  
  534.     /**
  535.     * A database portable Sequence management function.
  536.     *
  537.     * @param pSequenceName Name of the sequence to be used
  538.     *         It will be created if it does not already exist
  539.     * @param pStartID Allows setting the initial value of the sequence
  540.     * @return        if not supported, otherwise a sequence id
  541.     * @todo    To be combined with GenID
  542.     */
  543.     function CreateSequence($seqname='adodbseq',$startID=1{
  544.         // PURE VIRTUAL
  545.     }
  546.  
  547.     /**
  548.     * A database portable IFNULL function.
  549.     *
  550.     * @param pField argument to compare to NULL
  551.     * @param pNullRepl the NULL replacement value
  552.     * @return string that represents the function that checks whether
  553.     *  $pField is NULL for the given database, and if NULL, change the
  554.     *  value returned to $pNullRepl.
  555.     */
  556.     function ifNull($pField$pNullRepl{
  557.         // PURE VIRTUAL
  558.     }
  559.  
  560.     /**
  561.      * A database portable RANDOM() function.
  562.      * Adodb overrides it anyway with it's $rand property.
  563.      *
  564.      * @return string with RANDOM() function.
  565.      */
  566.     function random({
  567.  
  568.         switch$this->mType {
  569.             case "postgres":
  570.             case "pgsql":
  571.                 return "RANDOM()";
  572.  
  573.             case "mssql":
  574.                 return "NEWID()";
  575.  
  576.             default:
  577.                 return "RAND()";
  578.  
  579.         }
  580.     }
  581.  
  582.     /** Format the timestamp in the format the database accepts.
  583.     * @param pDate a Unix integer timestamp or an ISO format Y-m-d H:i:s
  584.     * @return the timestamp as a quoted string.
  585.     * @todo could be used to later convert all int timestamps into db
  586.     *  timestamps. Currently not used anywhere.
  587.     */
  588.     function ls($pDate{
  589.         // PURE VIRTUAL
  590.     }
  591.  
  592.     /**
  593.      * Return the current timestamp literal relevent to the database type
  594.      * @todo This needs extending to allow the use of GMT timestamp
  595.      *         rather then the current server time
  596.      */
  597.     function NOW({
  598.         global $gBitDbType$gBitSystem;
  599.         switch$gBitDbType {
  600.             case "firebird":
  601.                 $ret $gBitSystem->getUTCTimestamp()// UTC time to get round server offsets
  602.                 break;
  603.             default:
  604.                 $ret 'now()';
  605.         }
  606.         return $ret;
  607.     }
  608.  
  609.     /**
  610.      * Return the current timestamp literal relevent to the database type
  611.      * @todo This needs extending to allow the use of GMT timestamp
  612.      *         rather then the current server time
  613.      */
  614.     function qtNOW({
  615.         global $gBitDbType$gBitSystem;
  616.         switch$gBitDbType {
  617.             case "firebird":
  618.                 $ret "'".$gBitSystem->getUTCTimestamp()."'"// UTC time to get round server offsets
  619.                 break;
  620.             default:
  621.                 $ret 'now()';
  622.         }
  623.         return $ret;
  624.     }
  625.  
  626.     /** Return the sql to cast the given column from a time stamp to a Unix epoch
  627.     * this is most useful for the many places bitweaver stores time as epoch integers
  628.     * ADODB has no native support for this, see http://phplens.com/lens/lensforum/msgs.php?id=13661&x=1
  629.     * @param pColumn name of an integer, or long integer column
  630.     * @return the timestamp as a quoted string.
  631.     * @todo could be used to later convert all int timestamps into db
  632.     *  timestamps. Currently not used anywhere.
  633.     */
  634.     function SQLTimestampToInt$pColumn {
  635.         global $gBitDbType;
  636.         switch$gBitDbType {
  637.             case "firebird":
  638.                 $ret "CAST `$pColumn` AS TIMESTAMP";
  639.                 break;
  640.             case "mysql":
  641.             case "mysqli":
  642.                 $ret "UNIX_TIMESTAMP( `$pColumn` )";
  643.                 break;
  644.             case "pgsql":
  645.             case "postgres":
  646.             case "postgres7":
  647.                 $ret $pColumn.'::abstime::integer';
  648.                 break;
  649.             default:
  650.                 $ret $pColumn;
  651.         }
  652.         return $ret;
  653.     }
  654.  
  655.     /** Return the sql to cast the given column from an long integer to a time stamp.
  656.     * this is most useful for the many places bitweaver stores time as epoch integers
  657.     * ADODB has no native support for this, see http://phplens.com/lens/lensforum/msgs.php?id=13661&x=1
  658.     * @param pColumn name of an integer, or long integer column
  659.     * @return the timestamp as a quoted string.
  660.     * @todo could be used to later convert all int timestamps into db
  661.     *  timestamps. Currently not used anywhere.
  662.     */
  663.     function SQLIntToTimestamp$pColumn {
  664.         global $gBitDbType;
  665.         switch$gBitDbType {
  666.             case "firebird":
  667.                 $ret "(`$pColumn` / 86400.000000) + CAST ( '01/01/1970' AS TIMESTAMP )";
  668.                 break;
  669.             case "mysql":
  670.             case "mysqli":
  671.                 $ret "CAST( `$pColumn` AS DATETIME )";
  672.                 break;
  673.             case "pgsql":
  674.             case "postgres":
  675.             case "postgres7":
  676.                 $ret $pColumn.'::integer::abstime::timestamptz';
  677.                 break;
  678.             default:
  679.                 $ret $pColumn;
  680.         }
  681.         return $ret;
  682.     }
  683.  
  684.     public static function getPeriodFormat$pPeriod {
  685.         switch$pPeriod {
  686.             case 'year':
  687.                 $format 'Y';
  688.                 break;
  689.             case 'quarter':
  690.                 $format 'Y-\QQ';
  691.                 break;
  692.             case 'day':
  693.                 $format 'Y-m-d';
  694.                 break;
  695.             case 'week':
  696.                 $format 'Y \Week W';
  697.                 break;
  698.             case 'month':
  699.             default:
  700.                 $format 'Y-m';
  701.                 break;
  702.         }
  703.         return $format;
  704.     }
  705.  
  706.     /** Return the sql to lock selected rows for updating.
  707.     * ADODB has no native support for this, see http://phplens.com/lens/lensforum/msgs.php?id=13661&x=1
  708.     * @param pColumn name of an integer, or long integer column
  709.     * @return the timestamp as a quoted string.
  710.     * @todo could be used to later convert all int timestamps into db
  711.     *  timestamps. Currently not used anywhere.
  712.     */
  713.     function SQLForUpdate({
  714.         global $gBitDbType;
  715.         switch$gBitDbType {
  716.             case "firebird":
  717.             case "pgsql":
  718.             case "postgres":
  719.             case "postgres7":
  720.                 $ret ' FOR UPDATE ';
  721.                 break;
  722.             default:
  723.                 $ret '';
  724.         }
  725.         return $ret;
  726.     }
  727.  
  728.     /**
  729.      * Format date column in sql string given an input format that understands Y M D
  730.      */
  731.     function SQLDate($pDateFormat$pBaseDate=false{
  732.         // PURE VIRTUAL
  733.     }
  734.  
  735.     /**
  736.      * Calculate the offset of a date for a particular database and generate
  737.      * appropriate SQL. Useful for calculating future/past dates and storing
  738.      * in a database.
  739.      * @param pDays Number of days to offset by
  740.      *         If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
  741.      * @param pColumn Value to be offset
  742.      *         If NULL an offset from the current time is supplied
  743.      * @return New number of days
  744.      *
  745.      * @todo Not currently used - this is database specific and uses TIMESTAMP
  746.      *  rather than unix seconds
  747.      */
  748.     function OffsetDate$pDays$pColumn=NULL {
  749.         // PURE VIRTUAL
  750.     }
  751.  
  752.     /** Converts backtick (`) quotes to the appropriate quote for the
  753.     * database.
  754.     * @private
  755.     * @param pQuery the SQL query using backticks (`)
  756.     * @return the correctly quoted SQL statement
  757.     * @todo investigate replacement by AdoDB NameQuote() function
  758.     */
  759.     function convertQuery&$pQuery {
  760.         $pQuery preg_replace"!(^\s+)|(\s+$)!s"""$pQuery );
  761.         if!empty$this->mType ) ) {
  762.             switch$this->mType {
  763.                 case "oci8":
  764.                 case "oci8po":
  765.                     // Force Oracle to always be insensitive
  766.                     $pQuery str_replace'`'''$pQuery );
  767.                     break;
  768.                 case "pgsql":
  769.                 case "postgres":    // For PEAR
  770.                 case "postgres7":    // Deprecated ADODB
  771.                 case "mssql":
  772.                 case "sybase":
  773.                 case "firebird":
  774.                     if$this->getCaseSensitivity() ) {
  775.                         $pQuery str_replace'`''"'$pQuery );
  776.                     else {
  777.                         $pQuery str_replace'`'''$pQuery );
  778.                     }
  779.                     break;
  780.                 case "sqlite":
  781.                     $pQuery str_replace'`'''$pQuery );
  782.                     break;
  783.             }
  784.         }
  785.     }
  786.  
  787.     /**
  788.      * Converts field sorting abbreviation to SQL - you can pass in a single string or an entire array of sortmodes
  789.      *
  790.      * @param string or array $pSortMode fieldname and sort order string (eg name_asc)
  791.      * @access public
  792.      * @return the correctly quoted SQL ORDER statement
  793.      */
  794.     function convertSortmode$pSortMode {
  795.         ifis_array$pSortMode ) ) {
  796.             $sql '';
  797.             foreach$pSortMode as $sortMode {
  798.                 if!empty$sql ) ) {
  799.                     $sql .= ',';
  800.                 }
  801.                 $sql .= $this->convertSortmodeOneItem$sortMode );
  802.             }
  803.             return $sql;
  804.         else {
  805.             return $this->convertSortmodeOneItem$pSortMode );
  806.         }
  807.     }
  808.  
  809.     /**
  810.      * Converts field sorting abbreviation to SQL and it also allows us to do things like sort by random rows.
  811.      *
  812.      * @param array $pSortMode If pSortMode is 'random' it will insert the properly named db-specific function to achieve this.
  813.      * @access public
  814.      * @return valid, database-specific sortmode - if sortmode is not valid, NULL is returned
  815.      */
  816.     function convertSortmodeOneItem$pSortMode {
  817.         // check $sort_mode for evil stuff
  818.         if$pSortMode preg_replace('/[^.0-9A-Za-z_,]/'''$pSortMode) ) {
  819.             if$sep strrpos$pSortMode'_' ) ) {
  820.                 $order substr$pSortMode$sep );
  821.                 // force ending to neither _asc or _desc
  822.                 if $order !='_asc' && $order != '_desc' {
  823.                     $pSortMode substr$pSortMode0$sep '_desc';
  824.                 }
  825.             elseif$pSortMode != 'random' {
  826.                 $pSortMode .= '_desc';
  827.             }
  828.  
  829.             $pSortMode preg_replace'/lastModif/''last_modified'$pSortMode );
  830.             $pSortMode preg_replace'/pageName/''title'$pSortMode );
  831.             $pSortMode preg_replace'/^user_(asc|desc)/''login_\1'$pSortMode );
  832.  
  833.             $bIsFunction FALSE;
  834.  
  835.             //Use random() of BitDbBase. BitDbAdodb will override it with its implementation.
  836.             if$pSortMode == "random" {
  837.                 $pSortMode $this->random ();
  838.                 $bIsFunction TRUE;
  839.             }
  840.  
  841.             if!$bIsFunction {
  842.                 switch$this->mType {
  843.                     case "oci8po":
  844.                         $pSortMode preg_replace"/_asc$/""` ASC NULLS LAST"$pSortMode );
  845.                         $pSortMode preg_replace"/_desc$/""` DESC NULLS LAST"$pSortMode );
  846.                         break;
  847.                     case "firebird":
  848.                         // Use of alias in order by is not supported because of optimizer processing
  849.                         if $pSortMode == 'page_name_asc' )           $pSortMode 'title_asc';
  850.                         if $pSortMode == 'page_name_desc' )          $pSortMode 'title_desc';
  851.                         if $pSortMode == 'content_id_asc' )          $pSortMode 'lc.content_id_asc';
  852.                         if $pSortMode == 'content_id_desc' )         $pSortMode 'lc.content_id_desc';
  853.                         if $pSortMode == 'item_position_asc' )          $pSortMode 'tfgim2.item_position_asc';
  854.                         if $pSortMode == 'item_position_desc' )         $pSortMode 'tfgim2.item_position_desc';
  855.                         if $pSortMode == 'creator_user_asc' )        $pSortMode 'uuc.login_asc';
  856.                         if $pSortMode == 'creator_user_desc' )       $pSortMode 'uuc.login_desc';
  857.                         if $pSortMode == 'creator_real_name_asc' )   $pSortMode 'uuc.real_name_asc';
  858.                         if $pSortMode == 'creator_real_name_desc' )  $pSortMode 'uuc.real_name_desc';
  859.                         if $pSortMode == 'modifier_user_asc' )       $pSortMode 'uue.login_asc';
  860.                         if $pSortMode == 'modifier_user_desc' )      $pSortMode 'uue.login_desc';
  861.                         if $pSortMode == 'modifier_real_name_asc' )  $pSortMode 'uue.real_name_asc';
  862.                         if $pSortMode == 'modifier_real_name_desc' $pSortMode 'uue.real_name_desc';
  863.                     case "oci8":
  864.                     case "sybase":
  865.                     case "mssql":
  866.                     case "sqlite":
  867.                     case "mysql3":
  868.                     case "postgres":
  869.                     case "mysql":
  870.                     default:
  871.                         $pSortMode preg_replace"/_asc$/""` ASC"$pSortMode );
  872.                         $pSortMode preg_replace"/_desc$/""` DESC"$pSortMode );
  873.                         break;
  874.                 }
  875.                 $pSortMode str_replace",""`,`",$pSortMode );
  876.                 ifstrpos$pSortMode'.' ) ) {
  877.                     $pSortMode str_replace"."".`",$pSortMode );
  878.                 else {
  879.                     $pSortMode "`" $pSortMode;
  880.                 }
  881.             }
  882.         else {
  883.             $pSortMode NULL;
  884.         }
  885.         return $pSortMode;
  886.     }
  887.  
  888.     /** Returns the keyword to force a column comparison to be case sensitive
  889.     * for none case-sensitive databases (eg MySQL)
  890.     * @return the SQL keyword
  891.     * @todo only used in gBitSystem and users_lib to compare login names
  892.     */
  893.     function convertBinary({
  894.         switch ($this->mType{
  895.             case "oci8":
  896.             case "firebird":
  897.             case "sqlite":
  898.             break;
  899.             case "mysql3":
  900.             case "mysql":
  901.             return "BINARY";
  902.             break;
  903.         }
  904.     }
  905.  
  906.     /** Used to cast variable types for certain databases (ie SyBase & MSSQL)
  907.     * @param pVar the variable value to cast
  908.     * @param pType the current variable type
  909.     * @return the SQL casting statement
  910.     */
  911.     function sqlCast($pVar,$pType{
  912.         switch ($this->mType{
  913.             case "sybase":
  914.             case "mssql":
  915.             switch ($pType{
  916.                 case "int":
  917.                 return " CONVERT(numeric(14,0),$pVar";
  918.                 break;
  919.                 case "string":
  920.                 return " CONVERT(varchar(255),$pVar";
  921.                 break;
  922.                 case "float":
  923.                 return " CONVERT(numeric(10,5),$pVar";
  924.                 break;
  925.             }
  926.             break;
  927.             default:
  928.             return($pVar);
  929.             break;
  930.         }
  931.     }
  932.     /**
  933.     * Used to encode blob data (eg PostgreSQL). Can be called statically
  934.     * @todo had a lot of trouble with AdoDB BlobEncode and BlobDecode
  935.     *  the code works but will need work for dbs other than PgSQL
  936.     * @param pData a string of raw blob data
  937.     * @return escaped blob data
  938.     */
  939.     function dbByteEncode&$pData {
  940.         // need to use this global so as not to break static calls
  941.         global $gBitDbType;
  942.         switch $gBitDbType {
  943.             case "postgres":
  944.                 $search array(chr(92)chr(0)chr(39));
  945.                 $replace array('\\\134''\\\000''\\\047');
  946.                 $ret str_replace($search$replace$pData);
  947.                 break;
  948.             default:
  949.                 $ret &$pData;
  950.                 break;
  951.         }
  952.         return $ret;
  953.     }
  954.  
  955.     /**
  956.     * Used to decode blob data (eg PostgreSQL)
  957.     * @todo had a lot of trouble with AdoDB BlobEncode and BlobDecode
  958.     *  the code works but will need work for dbs other than PgSQL
  959.     * @param pData escaped blob data
  960.     * @return string of raw blob data
  961.     */
  962.     function dbByteDecode&$pData {
  963.         switch ($this->mDb->mType{
  964.             case "postgres":
  965.                 $ret stripcslashes$pData );
  966.                 break;
  967.             default:
  968.                 $ret &$pData;
  969.                 break;
  970.         }
  971.         return $ret;
  972.     }
  973.  
  974.     /**
  975.      *    Improved method of initiating a transaction. Used together with CompleteTrans().
  976.      *    Advantages include:
  977.      *
  978.      *    a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
  979.      *       Only the outermost block is treated as a transaction.<br>
  980.      *    b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
  981.      *    c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
  982.      *       are disabled, making it backward compatible.
  983.      */
  984.     function StartTrans({
  985.         // PURE VIRTUAL
  986.     }
  987.  
  988.     /**
  989.      *    Used together with StartTrans() to end a transaction. Monitors connection
  990.      *    for sql errors, and will commit or rollback as appropriate.
  991.      *
  992.      *    autoComplete if true, monitor sql errors and commit and rollback as appropriate,
  993.      *    and if set to false force rollback even if no SQL error detected.
  994.      *    @returns true on commit, false on rollback.
  995.      */
  996.     function CompleteTrans({
  997.         // PURE VIRTUAL
  998.     }
  999.  
  1000.     /**
  1001.      * If database does not support transactions, rollbacks always fail, so return false
  1002.      * otherwise returns true if the Rollback was successful
  1003.      *
  1004.      * @return true/false. 
  1005.      */
  1006.     function RollbackTrans({
  1007.         // PURE VIRTUAL
  1008.     }
  1009.  
  1010.     /**
  1011.     * @return rows affected by UPDATE/DELETE
  1012.     */
  1013.     function Affected_Rows({
  1014.         // PURE VIRTUAL
  1015.     }
  1016.  
  1017.     /**
  1018.      * Check for Postgres specific extensions
  1019.      */
  1020.     function isAdvancedPostgresEnabled({
  1021.         // This code makes use of the badass /usr/share/pgsql/contrib/tablefunc.sql
  1022.         // contribution that you have to install like: psql foo < /usr/share/pgsql/contrib/tablefunc.sql
  1023.         return defined'ADVANCED_PGSQL' );
  1024.     }
  1025.  
  1026.  
  1027.     /**
  1028.      * determine current version of the databse
  1029.      * @return hash including 'description', 'version' full string, 'major', 'minor', and 'revsion'
  1030.      */
  1031.     function getDatabaseVersion({
  1032.         $ret $this->mDb->ServerInfo();
  1033.         $versionHash explode'.'$ret['version');
  1034.         $ret['major'!empty$versionHash[0$versionHash[00;
  1035.         $ret['minor'!empty$versionHash[1$versionHash[10;
  1036.         $ret['revision'!empty$versionHash[2$versionHash[20;
  1037.         return $ret;
  1038.     }
  1039.  
  1040.  
  1041.     /**
  1042.      * Compatibility function for DBs with case insensitive searches
  1043.      * (like MySQL, see: http://dev.mysql.com/doc/refman/5.1/en/case-sensitivity.html)
  1044.      * How to use:
  1045.      *     AND ".$this->mDb->getCaseLessColumn('lc.title')." = 'page title'
  1046.      * The reason all this matters is that huge performane difference between:
  1047.      *   where title = 'PAGE TITLE'
  1048.      * and
  1049.      *   where UPPER(tittle) = 'PAGE TITTLE'
  1050.      * The latter version will not make use of the index on page title (at least for MySQl)
  1051.      * while the first vesion will use the index.  In a case insensitive search DB (MySQL) both
  1052.      * forms of the query will give the same results, the only difference being the preformance.
  1053.      * Spiderr suggested this solution and suppled the code below
  1054.      */
  1055.     function getCaselessColumn$pColumn {
  1056.         global $gBitDbType;
  1057.         switch$gBitDbType {
  1058.             case "mysql":
  1059.             case "mysqli":
  1060.                 $ret $pColumn;
  1061.                 break;
  1062.             default:
  1063.                 $ret " UPPER($pColumn";
  1064.                 break;
  1065.         }
  1066.         return $ret;
  1067.     }
  1068.  
  1069.     /**
  1070.      * Renamed a few functions - these are the temporary backward compatability calls with the deprecated note
  1071.      * These funcitons will be removed in due course
  1072.      */
  1073.     /**
  1074.      * @deprecated deprecated since version 2.0.0
  1075.      */
  1076.     function convert_sortmode$pSortMode {
  1077.         deprecated$this->depText'convert_sortmode''convertSortmode' ) );
  1078.         return $this->convertSortmode$pSortMode );
  1079.     }
  1080.     /**
  1081.      * @deprecated deprecated since version 2.0.0
  1082.      */
  1083.     function convert_sortmode_one_item$pSortMode {
  1084.         deprecated$this->depText'convert_sortmode_one_item''convertSortmodeOneItem' ) );
  1085.         return $this->convertSortmode$pSortMode );
  1086.     }
  1087.     /**
  1088.      * @deprecated deprecated since version 2.0.0
  1089.      */
  1090.     function convert_binary({
  1091.         deprecated$this->depText'convert_binary''convertBinary' ) );
  1092.         return $this->convertBinary();
  1093.     }
  1094.     /**
  1095.      * @deprecated deprecated since version 2.0.0
  1096.      */
  1097.     function sql_cast$pVar$pType {
  1098.         deprecated$this->depText'sql_cast''sqlCast' ) );
  1099.         return $this->sqlCast$pVar$pType );
  1100.     }
  1101.     /**
  1102.      * @deprecated deprecated since version 2.0.0
  1103.      */
  1104.     function db_byte_encode&$pData {
  1105.         deprecated$this->depText'db_byte_encode''dbByteEncode' ) );
  1106.         return $this->dbByteEncode$pData );
  1107.     }
  1108.     /**
  1109.      * @deprecated deprecated since version 2.0.0
  1110.      */
  1111.     function db_byte_decode&$pData {
  1112.         deprecated$this->depText'db_byte_decode''dbByteDecode' ) );
  1113.         return $this->dbByteDecode$pData );
  1114.     }
  1115.     function depText$pFrom$pTo {
  1116.         return "We have changed this method to BitDbBase::{$pTo}().
  1117.     Please update your code accordingly - you can try using the following (please back up your code before applying this):
  1118.     find <your package>/ -name \"*.php\" -exec perl -i -wpe 's/\b{$pFrom}\b/{$pTo}/g' {} \;";
  1119.     }
  1120. }
  1121. ?>

Documentation generated on Wed, 29 Jul 2015 13:55:49 +0000 by phpDocumentor 1.5.0-lsces