private function add_index_row($mailbox, $sort_field,
        $data, $mbox_data = array(), $exists = false, $modseq = null)
    {
        $data = array(
            $this->db->encode($data, true),
            $sort_field,
            (int) $this->skip_deleted,
            (int) $mbox_data['UIDVALIDITY'],
            (int) $mbox_data['UIDNEXT'],
            $modseq ? $modseq : $mbox_data['HIGHESTMODSEQ'],
        );

        $data    = implode('@', $data);
        $expires = $this->ttl ? $this->db->now($this->ttl) : 'NULL';

        if ($exists) {
            $res = $this->db->query(
                "UPDATE {$this->index_table}"
                ." SET `data` = ?, `valid` = 1, `expires` = $expires"
                ." WHERE `user_id` = ?"
                    ." AND `mailbox` = ?",
                $data, $this->userid, $mailbox);

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

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

        $res = $this->db->query(
            "INSERT INTO {$this->index_table}"
            ." (`user_id`, `mailbox`, `valid`, `expires`, `data`)"
            ." VALUES (?, ?, 1, $expires, ?)",
            $this->userid, $mailbox, $data);

        // race-condition, insert failed so try update (#1489146)
        // thanks to ignore_key_errors "duplicate row" errors will be ignored
        if (!$exists && !$res && !$this->db->is_error($res)) {
            $res = $this->db->query(
                "UPDATE {$this->index_table}"
                ." SET `data` = ?, `valid` = 1, `expires` = $expires"
                ." WHERE `user_id` = ?"
                    ." AND `mailbox` = ?",
                $data, $this->userid, $mailbox);
        }

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