private function write_record($key, $data)
    {
        if (!$this->db) {
            return false;
        }

        // don't attempt to write too big data sets
        if (strlen($data) > $this->max_packet_size()) {
            trigger_error("rcube_cache: max_packet_size ($this->max_packet) exceeded for key $key. Tried to write " . strlen($data) . " bytes", E_USER_WARNING);
            return false;
        }

        if ($this->type == 'memcache' || $this->type == 'apc') {
            $result = $this->add_record($this->ckey($key), $data);

            // make sure index will be updated
            if ($result) {
                if (!array_key_exists($key, $this->cache_sums)) {
                    $this->cache_sums[$key] = true;
                }

                $this->load_index();

                if (!$this->index_changed && !in_array($key, $this->index)) {
                    $this->index_changed = true;
                }
            }

            return $result;
        }

        $db_key = $this->prefix . '.' . $key;

        // Remove NULL rows (here we don't need to check if the record exist)
        if ($data == 'N;') {
            $result = $this->db->query(
                "DELETE FROM {$this->table}".
                " WHERE `user_id` = ? AND `cache_key` = ?",
                $this->userid, $db_key);

            return !$this->db->is_error($result);
        }

        $key_exists = array_key_exists($key, $this->cache_sums);
        $expires    = $this->ttl ? $this->db->now($this->ttl) : 'NULL';

        if (!$key_exists) {
            // Try INSERT temporarily ignoring "duplicate key" errors
            $this->db->set_option('ignore_key_errors', true);

            $result = $this->db->query(
                "INSERT INTO {$this->table} (`expires`, `user_id`, `cache_key`, `data`)"
                . " VALUES ($expires, ?, ?, ?)",
                $this->userid, $db_key, $data);

            $this->db->set_option('ignore_key_errors', false);
        }

        // otherwise try UPDATE
        if (!isset($result) || !($count = $this->db->affected_rows($result))) {
            $result = $this->db->query(
                "UPDATE {$this->table} SET `expires` = $expires, `data` = ?"
                . " WHERE `user_id` = ? AND `cache_key` = ?",
                $data, $this->userid, $db_key);

            $count = $this->db->affected_rows($result);
        }

        return $count > 0;
    }