Returns audit entry counts grouped by user and calendar day.

def CountAPIAuditEntriesByUserAndDay(self,
                                       min_timestamp=None,
                                       max_timestamp=None,
                                       cursor=None):
    """Returns audit entry counts grouped by user and calendar day."""
    query = """
        -- Timestamps are timezone-agnostic whereas dates are not. Hence, we are
        -- forced to pick some timezone, in order to extract the day. We choose
        -- UTC ('+00:00') as it is the most sane default.
        SELECT username,
               CAST(CONVERT_TZ(timestamp, @@SESSION.time_zone, '+00:00')
                    AS DATE) AS day,
               COUNT(*)
        FROM api_audit_entry
        FORCE INDEX (api_audit_entry_by_username_timestamp)
        {WHERE_PLACEHOLDER}
        GROUP BY username, day
    """
    conditions = []
    values = []
    where = ""

    if min_timestamp is not None:
      conditions.append("timestamp >= FROM_UNIXTIME(%s)")
      values.append(mysql_utils.RDFDatetimeToTimestamp(min_timestamp))

    if max_timestamp is not None:
      conditions.append("timestamp <= FROM_UNIXTIME(%s)")
      values.append(mysql_utils.RDFDatetimeToTimestamp(max_timestamp))

    if conditions:
      where = "WHERE " + " AND ".join(conditions)

    query = query.replace("{WHERE_PLACEHOLDER}", where)
    cursor.execute(query, values)

    return {(username, rdfvalue.RDFDatetime.FromDate(day)): count
            for (username, day, count) in cursor.fetchall()}