You are here

public function APDQCache::set in Asynchronous Prefetch Database Query Cache 7

Implements DrupalCacheInterface::set().

Overrides DrupalDatabaseCache::set

File

./apdqc.cache.inc, line 568
Extends Drupal's default database cache so async queries happen.

Class

APDQCache
A pretty darn quick cache implementation of Drupal's default cache backend.

Code

public function set($cid, $data, $expire = CACHE_PERMANENT) {

  // When setting cache items, clean up old session data in case it is stale.
  $gc_frequency = variable_get('cache_garbage_collection_frequency', CACHE_GARBAGE_COLLECTION_FREQUENCY);
  if (!empty($gc_frequency)) {
    $this
      ->cleanSession();
  }
  $fields = array(
    'serialized' => 0,
    'created' => REQUEST_TIME,
    'expire' => $expire,
  );
  if (!is_string($data)) {
    $fields['data'] = serialize($data);
    $fields['serialized'] = 1;
  }
  else {
    $fields['data'] = $data;
    $fields['serialized'] = 0;
  }
  if ($this->compressed > 1 || $this->compressed && $fields['serialized']) {
    $deflate = gzdeflate($fields['data'], $this->compression_level);
    if (strlen($deflate) < strlen($fields['data'])) {
      $fields['data'] = $deflate;
      $fields['serialized'] += 2;
    }
  }
  try {

    // Build query.
    $escaped_cid = apdqc_escape_string($cid);
    $escaped_data = apdqc_escape_string($fields['data']);
    $query = Database::getConnection()
      ->prefixTables("INSERT INTO {" . db_escape_table($this->bin) . "}");
    $query .= " (cid, serialized, created, expire, data) VALUES ('{$escaped_cid}', '{$fields['serialized']}', '{$fields['created']}', '{$fields['expire']}', '{$escaped_data}')";
    $query .= " ON DUPLICATE KEY UPDATE serialized = '{$fields['serialized']}', created = '{$fields['created']}', expire = '{$fields['expire']}', data = '{$escaped_data}'";

    // Run query.
    $result = apdqc_query(array(
      $this->bin,
    ), array(
      $cid,
    ), $query, array(
      'async' => TRUE,
    ));
    if (is_string($result) && $result === 'NO DB') {
      return parent::set($cid, $data, $expire);
    }
  } catch (Exception $e) {

    // The database may not be available, so we'll ignore cache_set requests.
  }
}