function add_message($mailbox, $message, $force = false)
    {
        if (!is_object($message) || empty($message->uid)) {
            return;
        }

        if (!($this->mode & self::MODE_MESSAGE)) {
            return;
        }

        $flags = 0;
        $msg   = clone $message;

        if (!empty($message->flags)) {
            foreach ($this->flags as $idx => $flag) {
                if (!empty($message->flags[$flag])) {
                    $flags += $idx;
                }
            }
        }

        unset($msg->flags);
        $msg = $this->db->encode($msg, true);

        // update cache record (even if it exists, the update
        // here will work as select, assume row exist if affected_rows=0)
        if (!$force) {
            $res = $this->db->query(
                "UPDATE {$this->messages_table}"
                ." SET `flags` = ?, `data` = ?, `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
                ." WHERE `user_id` = ?"
                    ." AND `mailbox` = ?"
                    ." AND `uid` = ?",
                $flags, $msg, $this->userid, $mailbox, (int) $message->uid);

            if ($this->db->affected_rows($res)) {
                return;
            }
        }

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

        // insert new record
        $res = $this->db->query(
            "INSERT INTO {$this->messages_table}"
            ." (`user_id`, `mailbox`, `uid`, `flags`, `expires`, `data`)"
            ." VALUES (?, ?, ?, ?, ". ($this->ttl ? $this->db->now($this->ttl) : 'NULL') . ", ?)",
            $this->userid, $mailbox, (int) $message->uid, $flags, $msg);

        // race-condition, insert failed so try update (#1489146)
        // thanks to ignore_key_errors "duplicate row" errors will be ignored
        if ($force && !$res && !$this->db->is_error($res)) {
            $this->db->query(
                "UPDATE {$this->messages_table}"
                ." SET `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL')
                    .", `flags` = ?, `data` = ?"
                ." WHERE `user_id` = ?"
                    ." AND `mailbox` = ?"
                    ." AND `uid` = ?",
                $flags, $msg, $this->userid, $mailbox, (int) $message->uid);
        }

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