def find_report_instance_by_dt(self, dt, tags=None): """Find a report instance with a creation datetime matching ``dt`` datetime as close as possible.""" ri_prev = self.fetch_prev_instance(util.max_uuid_with_dt(dt), tags) ri_next = self.fetch_next_instance(util.min_uuid_with_dt(dt), tags) return min([ri_prev, ri_next], key=lambda ri: abs((ri.created - dt).total_seconds()) if ri else sys.maxint)
def _delete_ris(self, owner_id, report_id, tags, ris, update_counters): qs = [] tags_days = set() all_tags_subsets = set() with cursor() as cur: for ri in ris: tags_powerset = util.powerset(ri['all_tags']) cur.execute("""DELETE FROM report_instance WHERE report_id=? AND tags IN {in_p} AND report_instance_id=?""".format(in_p=in_params(tags_powerset)), [report_id] + tags_powerset + [ri['report_instance_id']]) day = util.datetime_from_uuid1(ri['report_instance_id']).date() for tags_subset in tags_powerset: tags_days.add((tuple(tags_subset), day)) all_tags_subsets.add(tuple(tags_subset)) if update_counters: total_diskspace = sum(self._compute_ri_diskspace(ri) for ri in ris) cur.execute("""UPDATE report SET report_instance_count = report_instance_count - ? WHERE report_id=?""", [len(ris), report_id]) cur.execute("""UPDATE report SET report_instance_diskspace = report_instance_diskspace - ? WHERE report_id=?""", [total_diskspace, report_id]) cur.execute("""UPDATE report_data_for_owner SET report_instance_count=report_instance_count - ? WHERE owner_id=?""", [len(ris), owner_id]) cur.execute("""UPDATE report_data_for_owner SET report_instance_diskspace=report_instance_diskspace - ? WHERE owner_id=?""", [total_diskspace, owner_id]) ### Delete days for which report instances no longer exist for day_tags, day in tags_days: cur.execute("""SELECT report_instance_id FROM report_instance WHERE report_id=? AND tags=? AND report_instance_id > ? AND report_instance_id < ? LIMIT 1""", [report_id, list(day_tags), util.min_uuid_with_dt(datetime.datetime.combine(day, datetime.datetime.min.time())), util.max_uuid_with_dt(datetime.datetime.combine(day, datetime.datetime.max.time()))]) if not cur.fetchall(): cur.execute("""DELETE FROM report_instance_day WHERE report_id=? AND tags=? AND day=?""", [report_id, list(day_tags), day]) ### Delete tags for which report instances no longer exist tags_present = set() for tags, _ in tags_days: for tag in tags: tags_present.add(tag) for tag in tags_present: cur.execute("""SELECT report_id FROM report_instance_day WHERE report_id=? AND tags=? LIMIT 1""", [report_id, [tag]]) if cur.fetchall(): continue cur.execute("""DELETE FROM report_tag WHERE report_id=? AND tag=?""", [report_id, tag]) return len(ris), [list(ts) for ts in all_tags_subsets]