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

Source for file mdb.php

Documentation is available at mdb.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PEAR :: Cache :: MDB Container                                       |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1997-2003 The PHP Group                                |
  6. // +----------------------------------------------------------------------+
  7. // | This source file is subject to version 2.0 of the PHP license,       |
  8. // | that is bundled with this package in the file LICENSE, and is        |
  9. // | available at through the world-wide-web at                           |
  10. // | http://www.php.net/license/2_02.txt.                                 |
  11. // | If you did not receive a copy of the PHP license and are unable to   |
  12. // | obtain it through the world-wide-web, please send a note to          |
  13. // | license@php.net so we can mail you a copy immediately.               |
  14. // +----------------------------------------------------------------------+
  15. // | Note: This is a MDB-oriented rewrite of Cache/Container/db.php.      |
  16. // | Thanks to Lukas Smith for his patience in answering my questions     |
  17. // +----------------------------------------------------------------------+
  18. // | Author: Lorenzo Alberton <l.alberton at quipo.it>                    |
  19. // +----------------------------------------------------------------------+
  20. //
  21. // $Id: mdb.php,v 1.3 2003/01/04 11:54:46 mj Exp $
  22.  
  23. require_once 'MDB.php';
  24. require_once 'Cache/Container.php';
  25.  
  26. /**
  27. * PEAR/MDB Cache Container.
  28. *
  29. * NB: The field 'changed' has no meaning for the Cache itself. It's just there
  30. * because it's a good idea to have an automatically updated timestamp
  31. * field for debugging in all of your tables.
  32. *
  33. * A XML MDB-compliant schema example for the table needed is provided.
  34. * Look at the file "mdb_cache_schema.xml" for that.
  35. *
  36. * ------------------------------------------
  37. * A basic usage example:
  38. * ------------------------------------------
  39. *
  40. * $dbinfo = array(
  41. *   'database'    => 'dbname',
  42. *   'phptype'     => 'mysql',
  43. *   'username'    => 'root',
  44. *   'password'    => '',
  45. *   'cache_table' => 'cache'
  46. * );
  47. *
  48. *
  49. * $cache = new Cache('mdb', $dbinfo);
  50. * $id = $cache->generateID('testentry');
  51. *
  52. * if ($data = $cache->get($id)) {
  53. *    echo 'Cache hit.<br />Data: '.$data;
  54. *
  55. * } else {
  56. *   $data = 'data of any kind';
  57. *   $cache->save($id, $data);
  58. *   echo 'Cache miss.<br />';
  59. * }
  60. *
  61. * ------------------------------------------
  62. *
  63. @author   Lorenzo Alberton <l.alberton at quipo.it>
  64. @version  $Id: mdb.php,v 1.3 2003/01/04 11:54:46 mj Exp $
  65. @package  Cache
  66. */
  67.  
  68.     /**
  69.      * Name of the MDB table to store caching data
  70.      *
  71.      * @see  Cache_Container_file::$filename_prefix
  72.      */
  73.     var $cache_table = '';
  74.  
  75.     /**
  76.      * PEAR MDB object
  77.      *
  78.      * @var  object PEAR_MDB 
  79.      */
  80.     var $db;
  81.  
  82.     /**
  83.      * Constructor
  84.      *
  85.      * @param mixed Array with connection info or dsn string
  86.      */
  87.     function Cache_Container_mdb($options)
  88.     {
  89.         $this->db = &MDB::Connect($options);
  90.         if(MDB::isError($this->db)) {
  91.            return new Cache_Error('MDB::connect failed: '
  92.                     . $this->db->getMessage()__FILE____LINE__);
  93.         else {
  94.             $this->db->setFetchMode(MDB_FETCHMODE_ASSOC);
  95.         }
  96.         $this->setOptions($optionsarray_merge($this->allowed_options,
  97.                                          array('dsn''cache_table')));
  98.     }
  99.  
  100.     /**
  101.      * Fetch in the db the data that matches input parameters
  102.      *
  103.      * @param    string  dataset ID
  104.      * @param    string  cache group
  105.      * @return   mixed   dataset value or NULL/Cache_Error on failure
  106.      * @access   public
  107.      */
  108.     function fetch($id$group)
  109.     {
  110.         $query 'SELECT cachedata FROM ' $this->cache_table
  111.                 .' WHERE id='       $this->db->getTextValue($id)
  112.                 .' AND cachegroup=' $this->db->getTextValue($group);
  113.         if($res $this->db->query($query)) {
  114.             if($this->db->endOfResult($res)) {
  115.                 //no rows returned
  116.                 $data = array(NULLNULLNULL);
  117.             else {
  118.                 $clob $this->db->fetchClob($res,0,'cachedata');
  119.                 if(!MDB::isError($clob)) {
  120.                     $cached_data '';
  121.                     while(!$this->db->endOfLOB($clob)) {
  122.                         if(MDB::isError($error =
  123.                                     $this->db->readLob($clob,$data,8000)<0)) {
  124.                             return new Cache_Error('MDB::query failed: '
  125.                                     . $error->getMessage()__FILE____LINE__);
  126.                         }
  127.                         $cached_data .= $data;
  128.                     }
  129.                     unset($data);
  130.                     $this->db->destroyLob($clob);
  131.                     $this->db->freeResult($res);
  132.  
  133.                     //finished fetching LOB, now fetch other fields...
  134.                     $query 'SELECT userdata, expires FROM ' $this->cache_table
  135.                             .' WHERE id='       $this->db->getTextValue($id)
  136.                             .' AND cachegroup=' $this->db->getTextValue($group);
  137.                     if($res $this->db->query($query)) {
  138.                         $row $this->db->fetchInto($res);
  139.                         if (is_array($row)) {
  140.                             $data = array(
  141.                                         $row['expires'],
  142.                                         $this->decode($cached_data),
  143.                                         $row['userdata']
  144.                                     );
  145.                         else {
  146.                             $data = array(NULLNULLNULL);
  147.                         }
  148.                     else {
  149.                         $data = array(NULLNULLNULL);
  150.                     }
  151.                 else {
  152.                     return new Cache_Error('MDB::query failed: '
  153.                              . $clob->getMessage()__FILE____LINE__);
  154.                 }
  155.             }
  156.             $this->db->freeResult($res);
  157.         else {
  158.             //return new Cache_Error('MDB::query failed: '
  159.             //          . $result->getMessage(), __FILE__, __LINE__);
  160.             $data = array(NULLNULLNULL);
  161.         }
  162.  
  163.         // last used required by the garbage collection
  164.         $query 'UPDATE '          $this->cache_table
  165.                 .' SET changed='    time()
  166.                 .' WHERE id='       $this->db->getTextValue($id)
  167.                 .' AND cachegroup=' $this->db->getTextValue($group);
  168.  
  169.         $res $this->db->query($query);
  170.         if (MDB::isError($res)) {
  171.             return new Cache_Error('MDB::query failed: '
  172.                 . $this->db->errorMessage($res)__FILE____LINE__);
  173.         }
  174.         return $data;
  175.     }
  176.  
  177.    /**
  178.      * Stores a dataset in the database
  179.      *
  180.      * If dataset_ID already exists, overwrite it with new data,
  181.      * else insert data in a new record.
  182.      *
  183.      * @param    string  dataset ID
  184.      * @param    mixed   data to be cached
  185.      * @param    integer expiration time
  186.      * @param    string  cache group
  187.      * @param    string  userdata
  188.      * @access   public
  189.      */
  190.     function save($id$data$expires$group$userdata)
  191.     {
  192.         global $db;
  193.         $this->flushPreload($id$group);
  194.  
  195.         $fields = array(
  196.             'id'        => array(
  197.                             'Type'   => 'text',
  198.                             'Value'  => $id,
  199.                             'Key'    => true
  200.                         ),
  201.             'userdata'  => array(
  202.                             'Type'   => 'integer',
  203.                             'Value'  => $userdata,
  204.                             'Null'   => ($userdata ? false : true)
  205.                         ),
  206.             'expires'   => array(
  207.                             'Type'   => 'integer',
  208.                             'Value'  => $this->getExpiresAbsolute($expires)
  209.                         ),
  210.             'cachegroup' => array(
  211.                             'Type'   => 'text',
  212.                             'Value'  => $group
  213.                         )
  214.             );
  215.  
  216.         $result $this->db->replace($this->cache_table$fields);
  217.  
  218.         if(MDB::isError($result)) {
  219.             //Var_Dump::display($result);
  220.             return new Cache_Error('MDB::query failed: '
  221.                     . $this->db->errorMessage($result)__FILE____LINE__);
  222.         }
  223.         unset($fields)//end first part of query
  224.         $query2 'UPDATE '   $this->cache_table
  225.                  .' SET cachedata=?'
  226.                  .' WHERE id='$this->db->getTextValue($id);
  227.  
  228.         if(($prepared_query $this->db->prepareQuery($query2))) {
  229.             $char_lob = array(
  230.                             'Error' => '',
  231.                             'Type' => 'data',
  232.                             'Data' => $this->encode($data)
  233.                         );
  234.             if(!MDB::isError($clob $this->db->createLob($char_lob))) {
  235.                 $this->db->setParamClob($prepared_query,1,$clob,'cachedata');
  236.                 if(MDB::isError($error=$this->db->executeQuery($prepared_query))) {
  237.                     return new Cache_Error('MDB::query failed: '
  238.                             . $error->getMessage(__FILE____LINE__);
  239.                 }
  240.                 $this->db->destroyLob($clob);
  241.             else {
  242.                 // creation of the handler object failed
  243.                 return new Cache_Error('MDB::query failed: '
  244.                         . $clob->getMessage(__FILE____LINE__);
  245.             }
  246.             $this->db->freePreparedQuery($prepared_query);
  247.         else {
  248.             //prepared query failed
  249.             return new Cache_Error('MDB::query failed: '
  250.                     . $prepared_query->getMessage(__FILE____LINE__);
  251.         }
  252.     }
  253.  
  254.     /**
  255.      * Removes a dataset from the database
  256.      *
  257.      * @param    string  dataset ID
  258.      * @param    string  cache group
  259.      */
  260.     function remove($id$group)
  261.     {
  262.         $this->flushPreload($id$group);
  263.  
  264.         $query 'DELETE FROM '     $this->cache_table
  265.                 .' WHERE id='       $this->db->getTextValue($id)
  266.                 .' AND cachegroup=' $this->db->getTextValue($group);
  267.  
  268.         $res $this->db->query($query);
  269.         if (MDB::isError($res)) {
  270.             return new Cache_Error('MDB::query failed: '
  271.                     . $this->db->errorMessage($res)__FILE____LINE__);
  272.         }
  273.     }
  274.  
  275.     /**
  276.      * Remove all cached data for a certain group, or empty
  277.      * the cache table if no group is specified.
  278.      *
  279.      * @param    string  cache group
  280.      */
  281.     function flush($group '')
  282.     {
  283.         $this->flushPreload();
  284.  
  285.         if ($group{
  286.             $query 'DELETE FROM '       $this->cache_table
  287.                     .' WHERE cachegroup=' $this->db->getTextValue($group);
  288.         else {
  289.             $query 'DELETE FROM ' $this->cache_table;
  290.         }
  291.  
  292.         $res $this->db->query($query);
  293.         if (MDB::isError($res)) {
  294.             return new Cache_Error('MDB::query failed: '
  295.                 . $this->db->errorMessage($res)__FILE____LINE__);
  296.         }
  297.     }
  298.  
  299.     /**
  300.      * Check if a dataset ID/group exists.
  301.      *
  302.      * @param    string  dataset ID
  303.      * @param    string  cache group
  304.      * @return   boolean 
  305.      */
  306.     function idExists($id$group)
  307.     {
  308.         $query 'SELECT id FROM '  $this->cache_table
  309.                 .' WHERE id='       $this->db->getTextValue($id)
  310.                 .' AND cachegroup=' $this->db->getTextValue($group);
  311.         echo $query;
  312.         $res $this->db->query($query);
  313.         if (MDB::isError($res)) {
  314.             return new Cache_Error('MDB::query failed: '
  315.                     . $this->db->errorMessage($res)__FILE____LINE__);
  316.         }
  317.         $row $this->db->fetchInto($res);
  318.  
  319.         if (is_array($row)) {
  320.             return true;
  321.         else {
  322.             return false;
  323.         }
  324.     }
  325.  
  326.     /**
  327.      * Garbage collector.
  328.      *
  329.      * @param    int maxlifetime
  330.      */
  331.     function garbageCollection($maxlifetime)
  332.     {
  333.         $this->flushPreload();
  334.         $query 'DELETE FROM '        $this->cache_table
  335.                 .' WHERE (expires <= ' time()
  336.                 .' AND expires > 0) OR changed <= 'time($maxlifetime;
  337.  
  338.         $res $this->db->query($query);
  339.  
  340.         $query 'SELECT sum(length(cachedata)) as CacheSize FROM '
  341.                 . $this->cache_table;
  342.  
  343.         $cachesize $this->db->getOne($query);
  344.         if (MDB::isError($cachesize)) {
  345.             return new Cache_Error('MDB::query failed: '
  346.                    . $this->db->errorMessage($cachesize)__FILE____LINE__);
  347.         }
  348.         //if cache is to big.
  349.         if ($cachesize $this->highwater)
  350.         {
  351.             //find the lowwater mark.
  352.             $query 'SELECT length(cachedata) as size, changed FROM '
  353.                     . $this->cache_table .' ORDER BY changed DESC';
  354.  
  355.             $res $this->db->query($query);
  356.             if (MDB::isError($res)) {
  357.                return new Cache_Error('MDB::query failed: '
  358.                     . $this->db->errorMessage($res)__FILE____LINE__);
  359.             }
  360.             $numrows $this->db->numRows($res);
  361.             $keep_size = 0;
  362.             while ($keep_size $this->lowwater && $numrows--{
  363.                 $entry $this->db->fetchInto($res,MDB_FETCHMODE_ASSOC);
  364.                 $keep_size += $entry['size'];
  365.             }
  366.  
  367.             //delete all entries, which were changed before the "lowwater mark"
  368.             $query 'DELETE FROM ' $this->cache_table
  369.                     .' WHERE changed<='.($entry['changed'$entry['changed': 0);
  370.  
  371.             $res $this->db->query($query);
  372.             if (MDB::isError($res)) {
  373.                return new Cache_Error('MDB::query failed: '
  374.                     . $this->db->errorMessage($res)__FILE____LINE__);
  375.             }
  376.         }
  377.     }
  378.  
  379. }
  380. ?>

Documentation generated on Mon, 11 Mar 2019 10:14:24 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.