Esempio n. 1
0
    def events_query(
        self,
        team: Team,
        filter: SessionsFilter,
        date_filter: Q,
        distinct_ids: List[str],
        start_timestamp: Optional[str],
    ) -> QuerySet:
        events = (
            Event.objects.filter(team=team)
            .filter(date_filter)
            .filter(distinct_id__in=distinct_ids)
            .order_by("-timestamp")
            .only("distinct_id", "timestamp")
            .annotate(current_url=KeyTextTransform("$current_url", "properties"))
        )
        if start_timestamp is not None:
            events = events.filter(timestamp__lt=datetime.fromtimestamp(float(start_timestamp)))

        keys = []
        for i, entity in enumerate(filter.action_filters):
            key = f"entity_{i}"
            events = events.annotate(
                **{key: ExpressionWrapper(entity_to_Q(entity, team.pk), output_field=BooleanField())}
            )
            keys.append(key)

        return events.values_list("distinct_id", "timestamp", "current_url", *keys)
Esempio n. 2
0
    def _get_events_query(self) -> Tuple[str, list]:
        events: Union[EventManager, QuerySet] = Event.objects.filter(team=self._team).order_by("-timestamp").only(
            "distinct_id", "timestamp"
        )
        if self._filter.date_from:
            events = events.filter(timestamp__gte=self._filter.date_from - timedelta(hours=12))
        if self._filter.date_to:
            events = events.filter(timestamp__lte=self._filter.date_to + timedelta(hours=12))

        keys = []
        event_q_filters = []

        for i, entity in enumerate(self._filter.entities):
            key = f"entity_{i}"
            q_filter = entity_to_Q(entity, self._team.pk)
            event_q_filters.append(q_filter)
            events = events.annotate(**{key: ExpressionWrapper(q_filter, output_field=BooleanField())})
            keys.append(key)

        combined_event_q_filter = Q()
        for events_q_filter in event_q_filters:
            combined_event_q_filter |= events_q_filter

        events = events.filter(combined_event_q_filter)
        events = events.values_list("distinct_id", "timestamp", *keys)

        with connection.cursor() as cursor:
            event_query = cursor.mogrify(*events.query.sql_with_params()).decode("utf-8")

        return event_query, keys