Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(hogql): route legacy event reads through HogQL (#65348)

Sandy Spicer354af23310a1
diff --git a/ee/benchmarks/benchmarks.py b/ee/benchmarks/benchmarks.py
index 85134a4d3bc7..b6f0772cefcb 100644
--- a/ee/benchmarks/benchmarks.py
+++ b/ee/benchmarks/benchmarks.py
@@ -1,27 +1,21 @@
# isort: skip_file
# Needs to be first to set up django environment
-from .helpers import benchmark_clickhouse, no_materialized_columns, now
+from .helpers import benchmark_clickhouse, no_materialized_columns
from datetime import timedelta
from ee.clickhouse.materialized_columns.analyze import (
backfill_materialized_columns,
materialize,
)
from ee.clickhouse.materialized_columns.columns import MaterializedColumn
-from posthog.queries.funnels import ClickhouseFunnel
from posthog.queries.property_values import (
- get_property_values_for_key,
get_person_property_values_for_key,
)
-from posthog.queries.trends.trends import Trends
-from posthog.queries.session_recordings.session_recording_list import (
- SessionRecordingList,
-)
-from posthog.queries.util import get_earliest_timestamp
+from posthog.hogql_queries.property_values_query_runner import PropertyValuesQueryRunner
+from posthog.hogql_queries.query_runner import ExecutionMode
+from posthog.hogql_queries.utils.timestamp_utils import get_earliest_timestamp_unfiltered
+from posthog.schema import PropertyType, PropertyValuesQuery
from posthog.models import Team, Organization
from products.cohorts.backend.models.cohort import Cohort
-from products.actions.backend.models.action import Action
-from posthog.models.filters.session_recordings_filter import SessionRecordingsFilter
-from posthog.models.filters.filter import Filter
from posthog.models.property import PropertyName, TableWithProperties
MATERIALIZED_PROPERTIES: dict[TableWithProperties, list[PropertyName]] = {
@@ -36,14 +30,6 @@ MATERIALIZED_PROPERTIES: dict[TableWithProperties, list[PropertyName]] = {
],
}
-DATE_RANGE = {"date_from": "2021-01-01", "date_to": "2021-10-01", "interval": "week"}
-SHORT_DATE_RANGE = {
- "date_from": "2021-07-01",
- "date_to": "2021-10-01",
- "interval": "week",
-}
-SESSIONS_DATE_RANGE = {"date_from": "2021-11-17", "date_to": "2021-11-22"}
-
class QuerySuite:
timeout = 3000.0 # Timeout for the whole suite
@@ -52,476 +38,24 @@ class QuerySuite:
team: Team
cohort: Cohort
- @benchmark_clickhouse
- def track_trends_no_filter(self):
- filter = Filter(data={"events": [{"id": "$pageview"}], **DATE_RANGE})
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_event_property_filter(self):
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "properties": [
- {
- "key": "$host",
- "operator": "is_not",
- "value": [
- "localhost:8000",
- "localhost:5000",
- "127.0.0.1:8000",
- "127.0.0.1:3000",
- "localhost:3000",
- ],
- }
- ],
- **SHORT_DATE_RANGE,
- }
- )
-
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_event_property_filter_materialized(self):
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "properties": [
- {
- "key": "$host",
- "operator": "is_not",
- "value": [
- "localhost:8000",
- "localhost:5000",
- "127.0.0.1:8000",
- "127.0.0.1:3000",
- "localhost:3000",
- ],
- }
- ],
- **DATE_RANGE,
- }
- )
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_person_property_filter(self):
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- **DATE_RANGE,
- }
- )
-
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_person_property_filter_materialized(self):
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- **DATE_RANGE,
- }
- )
-
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_event_property_breakdown(self):
- filter = Filter(data={"events": [{"id": "$pageview"}], "breakdown": "$host", **DATE_RANGE})
-
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_event_property_breakdown_materialized(self):
- filter = Filter(data={"events": [{"id": "$pageview"}], "breakdown": "$host", **DATE_RANGE})
-
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_person_property_breakdown(self):
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "breakdown": "$browser",
- "breakdown_type": "person",
- **DATE_RANGE,
- }
- )
-
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_person_property_breakdown_materialized(self):
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "breakdown": "$browser",
- "breakdown_type": "person",
- **DATE_RANGE,
- }
- )
-
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_dau(self):
- filter = Filter(data={"events": [{"id": "$pageview", "math": "dau"}], **DATE_RANGE})
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_dau_person_property_filter(self):
- filter = Filter(
- data={
- "events": [{"id": "$pageview", "math": "dau"}],
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- **DATE_RANGE,
- }
- )
-
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_dau_person_property_filter_materialized(self):
- filter = Filter(
- data={
- "events": [{"id": "$pageview", "math": "dau"}],
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- **DATE_RANGE,
- }
- )
-
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_filter_by_cohort_precalculated(self):
- self.cohort.last_calculation = now()
- self.cohort.save()
-
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "properties": [{"key": "id", "value": self.cohort.pk, "type": "cohort"}],
- **DATE_RANGE,
- },
- team=self.team,
- )
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_filter_by_cohort(self):
- self.cohort.last_calculation = None
- self.cohort.save()
-
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "properties": [{"key": "id", "value": self.cohort.pk, "type": "cohort"}],
- **DATE_RANGE,
- },
- team=self.team,
- )
-
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_filter_by_cohort_materialized(self):
- self.cohort.last_calculation = None
- self.cohort.save()
-
- filter = Filter(
- data={
- "events": [{"id": "$pageview"}],
- "properties": [{"key": "id", "value": self.cohort.pk, "type": "cohort"}],
- **DATE_RANGE,
- },
- team=self.team,
- )
-
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_filter_by_action_current_url_materialized(self):
- action = Action.objects.create(
- team=self.team,
- name="docs view",
- steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
- )
-
- filter = Filter(data={"actions": [{"id": action.id}], **DATE_RANGE}, team=self.team)
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_filter_by_action_current_url(self):
- action = Action.objects.create(
- team=self.team,
- name="docs view",
- steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
- )
-
- filter = Filter(data={"actions": [{"id": action.id}], **DATE_RANGE}, team=self.team)
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_filter_by_action_with_person_filters_materialized(self):
- action = Action.objects.create(
- team=self.team,
- name=".com-users page views",
- steps_json=[
- {
- "event": "$pageview",
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- }
- ],
- )
-
- filter = Filter(data={"actions": [{"id": action.id}], **DATE_RANGE}, team=self.team)
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_trends_filter_by_action_with_person_filters(self):
- action = Action.objects.create(
- team=self.team,
- name=".com-users page views",
- steps_json=[
- {
- "event": "$pageview",
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- }
- ],
- )
-
- filter = Filter(data={"actions": [{"id": action.id}], **DATE_RANGE}, team=self.team)
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_funnel_normal(self):
- filter = Filter(
- data={
- "insight": "FUNNELS",
- "events": [
- {"id": "user signed up", "order": 0},
- {"id": "insight analyzed", "order": 1},
- ],
- **DATE_RANGE,
- },
- team=self.team,
- )
- ClickhouseFunnel(filter, self.team).run()
-
- @benchmark_clickhouse
- def track_session_recordings_list(self):
- filter = SessionRecordingsFilter(data=SESSIONS_DATE_RANGE, team=self.team)
-
- SessionRecordingList(filter, self.team).run()
-
- @benchmark_clickhouse
- def track_session_recordings_list_event_filter(self):
- filter = SessionRecordingsFilter(
- data={"events": [{"id": "$pageview"}], **SESSIONS_DATE_RANGE},
- team=self.team,
- )
-
- SessionRecordingList(filter, self.team).run()
-
- @benchmark_clickhouse
- def track_session_recordings_list_person_property_filter(self):
- filter = SessionRecordingsFilter(
- data={
- "events": [
- {
- "id": "$pageview",
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- }
- ],
- **SESSIONS_DATE_RANGE,
- },
- team=self.team,
- )
-
- SessionRecordingList(filter, self.team).run()
-
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_lifecycle_event_property_filter(self):
- filter = Filter(
- data={
- "insight": "LIFECYCLE",
- "events": [{"id": "$pageview", "type": "events"}],
- "interval": "week",
- "shown_as": "Lifecycle",
- "date_from": "-14d",
- "properties": [
- {
- "key": "$host",
- "operator": "is_not",
- "value": [
- "localhost:8000",
- "localhost:5000",
- "127.0.0.1:8000",
- "127.0.0.1:3000",
- "localhost:3000",
- ],
- }
- ],
- **DATE_RANGE,
- },
- team=self.team,
- )
-
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_lifecycle_event_property_filter_materialized(self):
- filter = Filter(
- data={
- "insight": "LIFECYCLE",
- "events": [{"id": "$pageview", "type": "events"}],
- "interval": "week",
- "shown_as": "Lifecycle",
- "date_from": "-14d",
- "properties": [
- {
- "key": "$host",
- "operator": "is_not",
- "value": [
- "localhost:8000",
- "localhost:5000",
- "127.0.0.1:8000",
- "127.0.0.1:3000",
- "localhost:3000",
- ],
- }
- ],
- **DATE_RANGE,
- },
- team=self.team,
- )
-
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_lifecycle_person_property_filter(self):
- filter = Filter(
- data={
- "insight": "LIFECYCLE",
- "events": [{"id": "$pageview", "type": "events"}],
- "interval": "week",
- "shown_as": "Lifecycle",
- "date_from": "-14d",
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- **DATE_RANGE,
- },
- team=self.team,
- )
-
- with no_materialized_columns():
- Trends().run(filter, self.team)
-
- @benchmark_clickhouse
- def track_lifecycle_person_property_filter_materialized(self):
- filter = Filter(
- data={
- "insight": "LIFECYCLE",
- "events": [{"id": "$pageview", "type": "events"}],
- "interval": "week",
- "shown_as": "Lifecycle",
- "date_from": "-14d",
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- **DATE_RANGE,
- },
- team=self.team,
- )
-
- Trends().run(filter, self.team)
-
@benchmark_clickhouse
def track_earliest_timestamp(self):
- get_earliest_timestamp(2)
+ get_earliest_timestamp_unfiltered(self.team)
@benchmark_clickhouse
def track_event_property_values(self):
with no_materialized_columns():
- get_property_values_for_key("$browser", self.team)
+ self._run_event_property_values("$browser")
@benchmark_clickhouse
def track_event_property_values_materialized(self):
- get_property_values_for_key("$browser", self.team)
+ self._run_event_property_values("$browser")
+
+ def _run_event_property_values(self, key: str) -> None:
+ PropertyValuesQueryRunner(
+ team=self.team,
+ query=PropertyValuesQuery(property_type=PropertyType.EVENT, property_key=key),
+ ).run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
@benchmark_clickhouse
def track_person_property_values(self):
diff --git a/ee/clickhouse/bin/clickhouse-flamegraph b/ee/clickhouse/bin/clickhouse-flamegraph
deleted file mode 100755
index d065d376bc88..000000000000
Binary files a/ee/clickhouse/bin/clickhouse-flamegraph and /dev/null differ
diff --git a/ee/clickhouse/bin/flamegraph.pl b/ee/clickhouse/bin/flamegraph.pl
deleted file mode 100755
index d039dcbc2958..000000000000
--- a/ee/clickhouse/bin/flamegraph.pl
+++ /dev/null
@@ -1,1191 +0,0 @@
-#!/usr/bin/perl -w
-#
-# flamegraph.pl flame stack grapher.
-#
-# This takes stack samples and renders a call graph, allowing hot functions
-# and codepaths to be quickly identified. Stack samples can be generated using
-# tools such as DTrace, perf, SystemTap, and Instruments.
-#
-# USAGE: ./flamegraph.pl [options] input.txt > graph.svg
-#
-# grep funcA input.txt | ./flamegraph.pl [options] > graph.svg
-#
-# Then open the resulting .svg in a web browser, for interactivity: mouse-over
-# frames for info, click to zoom, and ctrl-F to search.
-#
-# Options are listed in the usage message (--help).
-#
-# The input is stack frames and sample counts formatted as single lines. Each
-# frame in the stack is semicolon separated, with a space and count at the end
-# of the line. These can be generated for Linux perf script output using
-# stackcollapse-perf.pl, for DTrace using stackcollapse.pl, and for other tools
-# using the other stackcollapse programs. Example input:
-#
-# swapper;start_kernel;rest_init;cpu_idle;default_idle;native_safe_halt 1
-#
-# An optional extra column of counts can be provided to generate a differential
-# flame graph of the counts, colored red for more, and blue for less. This
-# can be useful when using flame graphs for non-regression testing.
-# See the header comment in the difffolded.pl program for instructions.
-#
-# The input functions can optionally have annotations at the end of each
-# function name, following a precedent by some tools (Linux perf's _[k]):
-# _[k] for kernel
-# _[i] for inlined
-# _[j] for jit
-# _[w] for waker
-# Some of the stackcollapse programs support adding these annotations, eg,
-# stackcollapse-perf.pl --kernel --jit. They are used merely for colors by
-# some palettes, eg, flamegraph.pl --color=java.
-#
-# The output flame graph shows relative presence of functions in stack samples.
-# The ordering on the x-axis has no meaning; since the data is samples, time
-# order of events is not known. The order used sorts function names
-# alphabetically.
-#
-# While intended to process stack samples, this can also process stack traces.
-# For example, tracing stacks for memory allocation, or resource usage. You
-# can use --title to set the title to reflect the content, and --countname
-# to change "samples" to "bytes" etc.
-#
-# There are a few different palettes, selectable using --color. By default,
-# the colors are selected at random (except for differentials). Functions
-# called "-" will be printed gray, which can be used for stack separators (eg,
-# between user and kernel stacks).
-#
-# HISTORY
-#
-# This was inspired by Neelakanth Nadgir's excellent function_call_graph.rb
-# program, which visualized function entry and return trace events. As Neel
-# wrote: "The output displayed is inspired by Roch's CallStackAnalyzer which
-# was in turn inspired by the work on vftrace by Jan Boerhout". See:
-# https://blogs.oracle.com/realneel/entry/visualizing_callstacks_via_dtrace_and
-#
-# Copyright 2016 Netflix, Inc.
-# Copyright 2011 Joyent, Inc. All rights reserved.
-# Copyright 2011 Brendan Gregg. All rights reserved.
-#
-# CDDL HEADER START
-#
-# The contents of this file are subject to the terms of the
-# Common Development and Distribution License (the "License").
-# You may not use this file except in compliance with the License.
-#
-# You can obtain a copy of the license at docs/cddl1.txt or
-# http://opensource.org/licenses/CDDL-1.0.
-# See the License for the specific language governing permissions
-# and limitations under the License.
-#
-# When distributing Covered Code, include this CDDL HEADER in each
-# file and include the License file at docs/cddl1.txt.
-# If applicable, add the following below this CDDL HEADER, with the
-# fields enclosed by brackets "[]" replaced with your own identifying
-# information: Portions Copyright [yyyy] [name of copyright owner]
-#
-# CDDL HEADER END
-#
-# 11-Oct-2014 Adrien Mahieux Added zoom.
-# 21-Nov-2013 Shawn Sterling Added consistent palette file option
-# 17-Mar-2013 Tim Bunce Added options and more tunables.
-# 15-Dec-2011 Dave Pacheco Support for frames with whitespace.
-# 10-Sep-2011 Brendan Gregg Created this.
-
-use strict;
-
-use Getopt::Long;
-
-use open qw(:std :utf8);
-
-# tunables
-my $encoding;
-my $fonttype = "Verdana";
-my $imagewidth = 1200; # max width, pixels
-my $frameheight = 16; # max height is dynamic
-my $fontsize = 12; # base text size
-my $fontwidth = 0.59; # avg width relative to fontsize
-my $minwidth = 0.1; # min function width, pixels
-my $nametype = "Function:"; # what are the names in the data?
-my $countname = "samples"; # what are the counts in the data?
-my $colors = "hot"; # color theme
-my $bgcolors = ""; # background color theme
-my $nameattrfile; # file holding function attributes
-my $timemax; # (override the) sum of the counts
-my $factor = 1; # factor to scale counts by
-my $hash = 0; # color by function name
-my $palette = 0; # if we use consistent palettes (default off)
-my %palette_map; # palette map hash
-my $pal_file = "palette.map"; # palette map file name
-my $stackreverse = 0; # reverse stack order, switching merge end
-my $inverted = 0; # icicle graph
-my $flamechart = 0; # produce a flame chart (sort by time, do not merge stacks)
-my $negate = 0; # switch differential hues
-my $titletext = ""; # centered heading
-my $titledefault = "Flame Graph"; # overwritten by --title
-my $titleinverted = "Icicle Graph"; # " "
-my $searchcolor = "rgb(230,0,230)"; # color for search highlighting
-my $notestext = ""; # embedded notes in SVG
-my $subtitletext = ""; # second level title (optional)
-my $help = 0;
-
-sub usage {
- die <<USAGE_END;
-USAGE: $0 [options] infile > outfile.svg\n
- --title TEXT # change title text
- --subtitle TEXT # second level title (optional)
- --width NUM # width of image (default 1200)
- --height NUM # height of each frame (default 16)
- --minwidth NUM # omit smaller functions (default 0.1 pixels)
- --fonttype FONT # font type (default "Verdana")
- --fontsize NUM # font size (default 12)
- --countname TEXT # count type label (default "samples")
- --nametype TEXT # name type label (default "Function:")
- --colors PALETTE # set color palette. choices are: hot (default), mem,
- # io, wakeup, chain, java, js, perl, red, green, blue,
- # aqua, yellow, purple, orange
- --bgcolors COLOR # set background colors. gradient choices are yellow
- # (default), blue, green, grey; flat colors use "#rrggbb"
- --hash # colors are keyed by function name hash
- --cp # use consistent palette (palette.map)
- --reverse # generate stack-reversed flame graph
- --inverted # icicle graph
- --flamechart # produce a flame chart (sort by time, do not merge stacks)
- --negate # switch differential hues (blue<->red)
- --notes TEXT # add notes comment in SVG (for debugging)
- --help # this message
-
- eg,
- $0 --title="Flame Graph: malloc()" trace.txt > graph.svg
-USAGE_END
-}
-
-GetOptions(
- 'fonttype=s' => \$fonttype,
- 'width=i' => \$imagewidth,
- 'height=i' => \$frameheight,
- 'encoding=s' => \$encoding,
- 'fontsize=f' => \$fontsize,
- 'fontwidth=f' => \$fontwidth,
- 'minwidth=f' => \$minwidth,
- 'title=s' => \$titletext,
- 'subtitle=s' => \$subtitletext,
- 'nametype=s' => \$nametype,
- 'countname=s' => \$countname,
- 'nameattr=s' => \$nameattrfile,
- 'total=s' => \$timemax,
- 'factor=f' => \$factor,
- 'colors=s' => \$colors,
- 'bgcolors=s' => \$bgcolors,
- 'hash' => \$hash,
- 'cp' => \$palette,
- 'reverse' => \$stackreverse,
- 'inverted' => \$inverted,
- 'flamechart' => \$flamechart,
- 'negate' => \$negate,
- 'notes=s' => \$notestext,
- 'help' => \$help,
-) or usage();
-$help && usage();
-
-# internals
-my $ypad1 = $fontsize * 3; # pad top, include title
-my $ypad2 = $fontsize * 2 + 10; # pad bottom, include labels
-my $ypad3 = $fontsize * 2; # pad top, include subtitle (optional)
-my $xpad = 10; # pad lefm and right
-my $framepad = 1; # vertical padding for frames
-my $depthmax = 0;
-my %Events;
-my %nameattr;
-
-if ($flamechart && $titletext eq "") {
- $titletext = "Flame Chart";
-}
-
-if ($titletext eq "") {
- unless ($inverted) {
- $titletext = $titledefault;
- } else {
- $titletext = $titleinverted;
- }
-}
-
-if ($nameattrfile) {
- # The name-attribute file format is a function name followed by a tab then
- # a sequence of tab separated name=value pairs.
- open my $attrfh, $nameattrfile or die "Can't read $nameattrfile: $!\n";
- while (<$attrfh>) {
- chomp;
- my ($funcname, $attrstr) = split /\t/, $_, 2;
- die "Invalid format in $nameattrfile" unless defined $attrstr;
- $nameattr{$funcname} = { map { split /=/, $_, 2 } split /\t/, $attrstr };
- }
-}
-
-if ($notestext =~ /[<>]/) {
- die "Notes string can't contain < or >"
-}
-
-# background colors:
-# - yellow gradient: default (hot, java, js, perl)
-# - green gradient: mem
-# - blue gradient: io, wakeup, chain
-# - gray gradient: flat colors (red, green, blue, ...)
-if ($bgcolors eq "") {
- # choose a default
- if ($colors eq "mem") {
- $bgcolors = "green";
- } elsif ($colors =~ /^(io|wakeup|chain)$/) {
- $bgcolors = "blue";
- } elsif ($colors =~ /^(red|green|blue|aqua|yellow|purple|orange)$/) {
- $bgcolors = "grey";
- } else {
- $bgcolors = "yellow";
- }
-}
-my ($bgcolor1, $bgcolor2);
-if ($bgcolors eq "yellow") {
- $bgcolor1 = "#eeeeee"; # background color gradient start
- $bgcolor2 = "#eeeeb0"; # background color gradient stop
-} elsif ($bgcolors eq "blue") {
- $bgcolor1 = "#eeeeee"; $bgcolor2 = "#e0e0ff";
-} elsif ($bgcolors eq "green") {
- $bgcolor1 = "#eef2ee"; $bgcolor2 = "#e0ffe0";
-} elsif ($bgcolors eq "grey") {
- $bgcolor1 = "#f8f8f8"; $bgcolor2 = "#e8e8e8";
-} elsif ($bgcolors =~ /^#......$/) {
- $bgcolor1 = $bgcolor2 = $bgcolors;
-} else {
- die "Unrecognized bgcolor option \"$bgcolors\""
-}
-
-# SVG functions
-{ package SVG;
- sub new {
- my $class = shift;
- my $self = {};
- bless ($self, $class);
- return $self;
- }
-
- sub header {
- my ($self, $w, $h) = @_;
- my $enc_attr = '';
- if (defined $encoding) {
- $enc_attr = qq{ encoding="$encoding"};
- }
- $self->{svg} .= <<SVG;
-<?xml version="1.0"$enc_attr standalone="no"?>
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
-<svg version="1.1" width="$w" height="$h" onload="init(evt)" viewBox="0 0 $w $h" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
-<!-- Flame graph stack visualization. See https://github.com/brendangregg/FlameGraph for latest version, and http://www.brendangregg.com/flamegraphs.html for examples. -->
-<!-- NOTES: $notestext -->
-SVG
- }
-
- sub include {
- my ($self, $content) = @_;
- $self->{svg} .= $content;
- }
-
- sub colorAllocate {
- my ($self, $r, $g, $b) = @_;
- return "rgb($r,$g,$b)";
- }
-
- sub group_start {
- my ($self, $attr) = @_;
-
- my @g_attr = map {
- exists $attr->{$_} ? sprintf(qq/$_="%s"/, $attr->{$_}) : ()
- } qw(id class);
- push @g_attr, $attr->{g_extra} if $attr->{g_extra};
- if ($attr->{href}) {
- my @a_attr;
- push @a_attr, sprintf qq/xlink:href="%s"/, $attr->{href} if $attr->{href};
- # default target=_top else links will open within SVG <object>
- push @a_attr, sprintf qq/target="%s"/, $attr->{target} || "_top";
- push @a_attr, $attr->{a_extra} if $attr->{a_extra};
- $self->{svg} .= sprintf qq/<a %s>\n/, join(' ', (@a_attr, @g_attr));
- } else {
- $self->{svg} .= sprintf qq/<g %s>\n/, join(' ', @g_attr);
- }
-
- $self->{svg} .= sprintf qq/<title>%s<\/title>/, $attr->{title}
- if $attr->{title}; # should be first element within g container
- }
-
- sub group_end {
- my ($self, $attr) = @_;
- $self->{svg} .= $attr->{href} ? qq/<\/a>\n/ : qq/<\/g>\n/;
- }
-
- sub filledRectangle {
- my ($self, $x1, $y1, $x2, $y2, $fill, $extra) = @_;
- $x1 = sprintf "%0.1f", $x1;
- $x2 = sprintf "%0.1f", $x2;
- my $w = sprintf "%0.1f", $x2 - $x1;
- my $h = sprintf "%0.1f", $y2 - $y1;
- $extra = defined $extra ? $extra : "";
- $self->{svg} .= qq/<rect x="$x1" y="$y1" width="$w" height="$h" fill="$fill" $extra \/>\n/;
- }
-
- sub stringTTF {
- my ($self, $id, $x, $y, $str, $extra) = @_;
- $x = sprintf "%0.2f", $x;
- $id = defined $id ? qq/id="$id"/ : "";
- $extra ||= "";
- $self->{svg} .= qq/<text $id x="$x" y="$y" $extra>$str<\/text>\n/;
- }
-
- sub svg {
- my $self = shift;
- return "$self->{svg}</svg>\n";
- }
- 1;
-}
-
-sub namehash {
- # Generate a vector hash for the name string, weighting early over
- # later characters. We want to pick the same colors for function
- # names across different flame graphs.
- my $name = shift;
- my $vector = 0;
- my $weight = 1;
- my $max = 1;
- my $mod = 10;
- # if module name present, trunc to 1st char
- $name =~ s/.(.*?)`//;
- foreach my $c (split //, $name) {
- my $i = (ord $c) % $mod;
- $vector += ($i / ($mod++ - 1)) * $weight;
- $max += 1 * $weight;
- $weight *= 0.70;
- last if $mod > 12;
- }
- return (1 - $vector / $max)
-}
-
-sub color {
- my ($type, $hash, $name) = @_;
- my ($v1, $v2, $v3);
-
- if ($hash) {
- $v1 = namehash($name);
- $v2 = $v3 = namehash(scalar reverse $name);
- } else {
- $v1 = rand(1);
- $v2 = rand(1);
- $v3 = rand(1);
- }
-
- # theme palettes
- if (defined $type and $type eq "hot") {
- my $r = 205 + int(50 * $v3);
- my $g = 0 + int(230 * $v1);
- my $b = 0 + int(55 * $v2);
- return "rgb($r,$g,$b)";
- }
- if (defined $type and $type eq "mem") {
- my $r = 0;
- my $g = 190 + int(50 * $v2);
- my $b = 0 + int(210 * $v1);
- return "rgb($r,$g,$b)";
- }
- if (defined $type and $type eq "io") {
- my $r = 80 + int(60 * $v1);
- my $g = $r;
- my $b = 190 + int(55 * $v2);
- return "rgb($r,$g,$b)";
- }
-
- # multi palettes
- if (defined $type and $type eq "java") {
- # Handle both annotations (_[j], _[i], ...; which are
- # accurate), as well as input that lacks any annotations, as
- # best as possible. Without annotations, we get a little hacky
- # and match on java|org|com, etc.
- if ($name =~ m:_\[j\]$:) { # jit annotation
- $type = "green";
- } elsif ($name =~ m:_\[i\]$:) { # inline annotation
- $type = "aqua";
- } elsif ($name =~ m:^L?(java|javax|jdk|net|org|com|io|sun)/:) { # Java
- $type = "green";
- } elsif ($name =~ m:_\[k\]$:) { # kernel annotation
- $type = "orange";
- } elsif ($name =~ /::/) { # C++
- $type = "yellow";
- } else { # system
- $type = "red";
- }
- # fall-through to color palettes
- }
- if (defined $type and $type eq "perl") {
- if ($name =~ /::/) { # C++
- $type = "yellow";
- } elsif ($name =~ m:Perl: or $name =~ m:\.pl:) { # Perl
- $type = "green";
- } elsif ($name =~ m:_\[k\]$:) { # kernel
- $type = "orange";
- } else { # system
- $type = "red";
- }
- # fall-through to color palettes
- }
- if (defined $type and $type eq "js") {
- # Handle both annotations (_[j], _[i], ...; which are
- # accurate), as well as input that lacks any annotations, as
- # best as possible. Without annotations, we get a little hacky,
- # and match on a "/" with a ".js", etc.
- if ($name =~ m:_\[j\]$:) { # jit annotation
- if ($name =~ m:/:) {
- $type = "green"; # source
- } else {
- $type = "aqua"; # builtin
- }
- } elsif ($name =~ /::/) { # C++
- $type = "yellow";
- } elsif ($name =~ m:/.*\.js:) { # JavaScript (match "/" in path)
- $type = "green";
- } elsif ($name =~ m/:/) { # JavaScript (match ":" in builtin)
- $type = "aqua";
- } elsif ($name =~ m/^ $/) { # Missing symbol
- $type = "green";
- } elsif ($name =~ m:_\[k\]:) { # kernel
- $type = "orange";
- } else { # system
- $type = "red";
- }
- # fall-through to color palettes
- }
- if (defined $type and $type eq "wakeup") {
- $type = "aqua";
- # fall-through to color palettes
- }
- if (defined $type and $type eq "chain") {
- if ($name =~ m:_\[w\]:) { # waker
- $type = "aqua"
- } else { # off-CPU
- $type = "blue";
- }
- # fall-through to color palettes
- }
-
- # color palettes
- if (defined $type and $type eq "red") {
- my $r = 200 + int(55 * $v1);
- my $x = 50 + int(80 * $v1);
- return "rgb($r,$x,$x)";
- }
- if (defined $type and $type eq "green") {
- my $g = 200 + int(55 * $v1);
- my $x = 50 + int(60 * $v1);
- return "rgb($x,$g,$x)";
- }
- if (defined $type and $type eq "blue") {
- my $b = 205 + int(50 * $v1);
- my $x = 80 + int(60 * $v1);
- return "rgb($x,$x,$b)";
- }
- if (defined $type and $type eq "yellow") {
- my $x = 175 + int(55 * $v1);
- my $b = 50 + int(20 * $v1);
- return "rgb($x,$x,$b)";
- }
- if (defined $type and $type eq "purple") {
- my $x = 190 + int(65 * $v1);
- my $g = 80 + int(60 * $v1);
- return "rgb($x,$g,$x)";
- }
- if (defined $type and $type eq "aqua") {
- my $r = 50 + int(60 * $v1);
- my $g = 165 + int(55 * $v1);
- my $b = 165 + int(55 * $v1);
- return "rgb($r,$g,$b)";
- }
- if (defined $type and $type eq "orange") {
- my $r = 190 + int(65 * $v1);
- my $g = 90 + int(65 * $v1);
- return "rgb($r,$g,0)";
- }
-
- return "rgb(0,0,0)";
-}
-
-sub color_scale {
- my ($value, $max) = @_;
- my ($r, $g, $b) = (255, 255, 255);
- $value = -$value if $negate;
- if ($value > 0) {
- $g = $b = int(210 * ($max - $value) / $max);
- } elsif ($value < 0) {
- $r = $g = int(210 * ($max + $value) / $max);
- }
- return "rgb($r,$g,$b)";
-}
-
-sub color_map {
- my ($colors, $func) = @_;
- if (exists $palette_map{$func}) {
- return $palette_map{$func};
- } else {
- $palette_map{$func} = color($colors, $hash, $func);
- return $palette_map{$func};
- }
-}
-
-sub write_palette {
- open(FILE, ">$pal_file");
- foreach my $key (sort keys %palette_map) {
- print FILE $key."->".$palette_map{$key}."\n";
- }
- close(FILE);
-}
-
-sub read_palette {
- if (-e $pal_file) {
- open(FILE, $pal_file) or die "can't open file $pal_file: $!";
- while ( my $line = <FILE>) {
- chomp($line);
- (my $key, my $value) = split("->",$line);
- $palette_map{$key}=$value;
- }
- close(FILE)
- }
-}
-
-my %Node; # Hash of merged frame data
-my %Tmp;
-
-# flow() merges two stacks, storing the merged frames and value data in %Node.
-sub flow {
- my ($last, $this, $v, $d) = @_;
-
- my $len_a = @$last - 1;
- my $len_b = @$this - 1;
-
- my $i = 0;
- my $len_same;
- for (; $i <= $len_a; $i++) {
- last if $i > $len_b;
- last if $last->[$i] ne $this->[$i];
- }
- $len_same = $i;
-
- for ($i = $len_a; $i >= $len_same; $i--) {
- my $k = "$last->[$i];$i";
- # a unique ID is constructed from "func;depth;etime";
- # func-depth isn't unique, it may be repeated later.
- $Node{"$k;$v"}->{stime} = delete $Tmp{$k}->{stime};
- if (defined $Tmp{$k}->{delta}) {
- $Node{"$k;$v"}->{delta} = delete $Tmp{$k}->{delta};
- }
- delete $Tmp{$k};
- }
-
- for ($i = $len_same; $i <= $len_b; $i++) {
- my $k = "$this->[$i];$i";
- $Tmp{$k}->{stime} = $v;
- if (defined $d) {
- $Tmp{$k}->{delta} += $i == $len_b ? $d : 0;
- }
- }
-
- return $this;
-}
-
-# parse input
-my @Data;
-my @SortedData;
-my $last = [];
-my $time = 0;
-my $delta = undef;
-my $ignored = 0;
-my $line;
-my $maxdelta = 1;
-
-# reverse if needed
-foreach (<>) {
- chomp;
- $line = $_;
- if ($stackreverse) {
- # there may be an extra samples column for differentials
- # XXX todo: redo these REs as one. It's repeated below.
- my($stack, $samples) = (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
- my $samples2 = undef;
- if ($stack =~ /^(.*)\s+?(\d+(?:\.\d*)?)$/) {
- $samples2 = $samples;
- ($stack, $samples) = $stack =~ (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
- unshift @Data, join(";", reverse split(";", $stack)) . " $samples $samples2";
- } else {
- unshift @Data, join(";", reverse split(";", $stack)) . " $samples";
- }
- } else {
- unshift @Data, $line;
- }
-}
-
-if ($flamechart) {
- # In flame chart mode, just reverse the data so time moves from left to right.
- @SortedData = reverse @Data;
-} else {
- @SortedData = sort @Data;
-}
-
-# process and merge frames
-foreach (@SortedData) {
- chomp;
- # process: folded_stack count
- # eg: func_a;func_b;func_c 31
- my ($stack, $samples) = (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
- unless (defined $samples and defined $stack) {
- ++$ignored;
- next;
- }
-
- # there may be an extra samples column for differentials:
- my $samples2 = undef;
- if ($stack =~ /^(.*)\s+?(\d+(?:\.\d*)?)$/) {
- $samples2 = $samples;
- ($stack, $samples) = $stack =~ (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
- }
- $delta = undef;
- if (defined $samples2) {
- $delta = $samples2 - $samples;
- $maxdelta = abs($delta) if abs($delta) > $maxdelta;
- }
-
- # for chain graphs, annotate waker frames with "_[w]", for later
- # coloring. This is a hack, but has a precedent ("_[k]" from perf).
- if ($colors eq "chain") {
- my @parts = split ";--;", $stack;
- my @newparts = ();
- $stack = shift @parts;
- $stack .= ";--;";
- foreach my $part (@parts) {
- $part =~ s/;/_[w];/g;
- $part .= "_[w]";
- push @newparts, $part;
- }
- $stack .= join ";--;", @parts;
- }
-
- # merge frames and populate %Node:
- $last = flow($last, [ '', split ";", $stack ], $time, $delta);
-
- if (defined $samples2) {
- $time += $samples2;
- } else {
- $time += $samples;
- }
-}
-flow($last, [], $time, $delta);
-
-warn "Ignored $ignored lines with invalid format\n" if $ignored;
-unless ($time) {
- warn "ERROR: No stack counts found\n";
- my $im = SVG->new();
- # emit an error message SVG, for tools automating flamegraph use
- my $imageheight = $fontsize * 5;
- $im->header($imagewidth, $imageheight);
- $im->stringTTF(undef, int($imagewidth / 2), $fontsize * 2,
- "ERROR: No valid input provided to flamegraph.pl.");
- print $im->svg;
- exit 2;
-}
-if ($timemax and $timemax < $time) {
- warn "Specified --total $timemax is less than actual total $time, so ignored\n"
- if $timemax/$time > 0.02; # only warn is significant (e.g., not rounding etc)
- undef $timemax;
-}
-$timemax ||= $time;
-
-my $widthpertime = ($imagewidth - 2 * $xpad) / $timemax;
-my $minwidth_time = $minwidth / $widthpertime;
-
-# prune blocks that are too narrow and determine max depth
-while (my ($id, $node) = each %Node) {
- my ($func, $depth, $etime) = split ";", $id;
- my $stime = $node->{stime};
- die "missing start for $id" if not defined $stime;
-
- if (($etime-$stime) < $minwidth_time) {
- delete $Node{$id};
- next;
- }
- $depthmax = $depth if $depth > $depthmax;
-}
-
-# draw canvas, and embed interactive JavaScript program
-my $imageheight = (($depthmax + 1) * $frameheight) + $ypad1 + $ypad2;
-$imageheight += $ypad3 if $subtitletext ne "";
-my $titlesize = $fontsize + 5;
-my $im = SVG->new();
-my ($black, $vdgrey, $dgrey) = (
- $im->colorAllocate(0, 0, 0),
- $im->colorAllocate(160, 160, 160),
- $im->colorAllocate(200, 200, 200),
- );
-$im->header($imagewidth, $imageheight);
-my $inc = <<INC;
-<defs>
- <linearGradient id="background" y1="0" y2="1" x1="0" x2="0" >
- <stop stop-color="$bgcolor1" offset="5%" />
- <stop stop-color="$bgcolor2" offset="95%" />
- </linearGradient>
-</defs>
-<style type="text/css">
- text { font-family:$fonttype; font-size:${fontsize}px; fill:$black; }
- #search, #ignorecase { opacity:0.1; cursor:pointer; }
- #search:hover, #search.show, #ignorecase:hover, #ignorecase.show { opacity:1; }
- #subtitle { text-anchor:middle; font-color:$vdgrey; }
- #title { text-anchor:middle; font-size:${titlesize}px}
- #unzoom { cursor:pointer; }
- #frames > *:hover { stroke:black; stroke-width:0.5; cursor:pointer; }
- .hide { display:none; }
- .parent { opacity:0.5; }
-</style>
-<script type="text/ecmascript">
-<![CDATA[
- "use strict";
- var details, searchbtn, unzoombtn, matchedtxt, svg, searching, currentSearchTerm, ignorecase, ignorecaseBtn;
- function init(evt) {
- details = document.getElementById("details").firstChild;
- searchbtn = document.getElementById("search");
- ignorecaseBtn = document.getElementById("ignorecase");
- unzoombtn = document.getElementById("unzoom");
- matchedtxt = document.getElementById("matched");
- svg = document.getElementsByTagName("svg")[0];
- searching = 0;
- currentSearchTerm = null;
- }
-
- window.addEventListener("click", function(e) {
- var target = find_group(e.target);
- if (target) {
- if (target.nodeName == "a") {
- if (e.ctrlKey === false) return;
- e.preventDefault();
- }
- if (target.classList.contains("parent")) unzoom();
- zoom(target);
- }
- else if (e.target.id == "unzoom") unzoom();
- else if (e.target.id == "search") search_prompt();
- else if (e.target.id == "ignorecase") toggle_ignorecase();
- }, false)
-
- // mouse-over for info
- // show
- window.addEventListener("mouseover", function(e) {
- var target = find_group(e.target);
- if (target) details.nodeValue = "$nametype " + g_to_text(target);
- }, false)
-
- // clear
- window.addEventListener("mouseout", function(e) {
- var target = find_group(e.target);
- if (target) details.nodeValue = ' ';
- }, false)
-
- // ctrl-F for search
- window.addEventListener("keydown",function (e) {
- if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
- e.preventDefault();
- search_prompt();
- }
- }, false)
-
- // ctrl-I to toggle case-sensitive search
- window.addEventListener("keydown",function (e) {
- if (e.ctrlKey && e.keyCode === 73) {
- e.preventDefault();
- toggle_ignorecase();
- }
- }, false)
-
- // functions
- function find_child(node, selector) {
- var children = node.querySelectorAll(selector);
- if (children.length) return children[0];
- return;
- }
- function find_group(node) {
- var parent = node.parentElement;
- if (!parent) return;
- if (parent.id == "frames") return node;
- return find_group(parent);
- }
- function orig_save(e, attr, val) {
- if (e.attributes["_orig_" + attr] != undefined) return;
- if (e.attributes[attr] == undefined) return;
- if (val == undefined) val = e.attributes[attr].value;
- e.setAttribute("_orig_" + attr, val);
- }
- function orig_load(e, attr) {
- if (e.attributes["_orig_"+attr] == undefined) return;
- e.attributes[attr].value = e.attributes["_orig_" + attr].value;
- e.removeAttribute("_orig_"+attr);
- }
- function g_to_text(e) {
- var text = find_child(e, "title").firstChild.nodeValue;
- return (text)
- }
- function g_to_func(e) {
- var func = g_to_text(e);
- // if there's any manipulation we want to do to the function
- // name before it's searched, do it here before returning.
- return (func);
- }
- function update_text(e) {
- var r = find_child(e, "rect");
- var t = find_child(e, "text");
- var w = parseFloat(r.attributes.width.value) -3;
- var txt = find_child(e, "title").textContent.replace(/\\([^(]*\\)\$/,"");
- t.attributes.x.value = parseFloat(r.attributes.x.value) + 3;
-
- // Smaller than this size won't fit anything
- if (w < 2 * $fontsize * $fontwidth) {
- t.textContent = "";
- return;
- }
-
- t.textContent = txt;
- // Fit in full text width
- if (/^ *\$/.test(txt) || t.getSubStringLength(0, txt.length) < w)
- return;
-
- for (var x = txt.length - 2; x > 0; x--) {
- if (t.getSubStringLength(0, x + 2) <= w) {
- t.textContent = txt.substring(0, x) + "..";
- return;
- }
- }
- t.textContent = "";
- }
-
- // zoom
- function zoom_reset(e) {
- if (e.attributes != undefined) {
- orig_load(e, "x");
- orig_load(e, "width");
- }
- if (e.childNodes == undefined) return;
- for (var i = 0, c = e.childNodes; i < c.length; i++) {
- zoom_reset(c[i]);
- }
- }
- function zoom_child(e, x, ratio) {
- if (e.attributes != undefined) {
- if (e.attributes.x != undefined) {
- orig_save(e, "x");
- e.attributes.x.value = (parseFloat(e.attributes.x.value) - x - $xpad) * ratio + $xpad;
- if (e.tagName == "text")
- e.attributes.x.value = find_child(e.parentNode, "rect[x]").attributes.x.value + 3;
- }
- if (e.attributes.width != undefined) {
- orig_save(e, "width");
- e.attributes.width.value = parseFloat(e.attributes.width.value) * ratio;
- }
- }
-
- if (e.childNodes == undefined) return;
- for (var i = 0, c = e.childNodes; i < c.length; i++) {
- zoom_child(c[i], x - $xpad, ratio);
- }
- }
- function zoom_parent(e) {
- if (e.attributes) {
- if (e.attributes.x != undefined) {
- orig_save(e, "x");
- e.attributes.x.value = $xpad;
- }
- if (e.attributes.width != undefined) {
- orig_save(e, "width");
- e.attributes.width.value = parseInt(svg.width.baseVal.value) - ($xpad * 2);
- }
- }
- if (e.childNodes == undefined) return;
- for (var i = 0, c = e.childNodes; i < c.length; i++) {
- zoom_parent(c[i]);
- }
- }
- function zoom(node) {
- var attr = find_child(node, "rect").attributes;
- var width = parseFloat(attr.width.value);
- var xmin = parseFloat(attr.x.value);
- var xmax = parseFloat(xmin + width);
- var ymin = parseFloat(attr.y.value);
- var ratio = (svg.width.baseVal.value - 2 * $xpad) / width;
-
- // XXX: Workaround for JavaScript float issues (fix me)
- var fudge = 0.0001;
-
- unzoombtn.classList.remove("hide");
-
- var el = document.getElementById("frames").children;
- for (var i = 0; i < el.length; i++) {
- var e = el[i];
- var a = find_child(e, "rect").attributes;
- var ex = parseFloat(a.x.value);
- var ew = parseFloat(a.width.value);
- var upstack;
- // Is it an ancestor
- if ($inverted == 0) {
- upstack = parseFloat(a.y.value) > ymin;
- } else {
- upstack = parseFloat(a.y.value) < ymin;
- }
- if (upstack) {
- // Direct ancestor
- if (ex <= xmin && (ex+ew+fudge) >= xmax) {
- e.classList.add("parent");
- zoom_parent(e);
- update_text(e);
- }
- // not in current path
- else
- e.classList.add("hide");
- }
- // Children maybe
- else {
- // no common path
- if (ex < xmin || ex + fudge >= xmax) {
- e.classList.add("hide");
- }
- else {
- zoom_child(e, xmin, ratio);
- update_text(e);
- }
- }
- }
- search();
- }
- function unzoom() {
- unzoombtn.classList.add("hide");
- var el = document.getElementById("frames").children;
- for(var i = 0; i < el.length; i++) {
- el[i].classList.remove("parent");
- el[i].classList.remove("hide");
- zoom_reset(el[i]);
- update_text(el[i]);
- }
- search();
- }
-
- // search
- function toggle_ignorecase() {
- ignorecase = !ignorecase;
- if (ignorecase) {
- ignorecaseBtn.classList.add("show");
- } else {
- ignorecaseBtn.classList.remove("show");
- }
- reset_search();
- search();
- }
- function reset_search() {
- var el = document.querySelectorAll("#frames rect");
- for (var i = 0; i < el.length; i++) {
- orig_load(el[i], "fill")
- }
- }
- function search_prompt() {
- if (!searching) {
- var term = prompt("Enter a search term (regexp " +
- "allowed, eg: ^ext4_)"
- + (ignorecase ? ", ignoring case" : "")
- + "\\nPress Ctrl-i to toggle case sensitivity", "");
- if (term != null) {
- currentSearchTerm = term;
- search();
- }
- } else {
- reset_search();
- searching = 0;
- currentSearchTerm = null;
- searchbtn.classList.remove("show");
- searchbtn.firstChild.nodeValue = "Search"
- matchedtxt.classList.add("hide");
- matchedtxt.firstChild.nodeValue = ""
- }
- }
- function search(term) {
- if (currentSearchTerm === null) return;
- var term = currentSearchTerm;
-
- var re = new RegExp(term, ignorecase ? 'i' : '');
- var el = document.getElementById("frames").children;
- var matches = new Object();
- var maxwidth = 0;
- for (var i = 0; i < el.length; i++) {
- var e = el[i];
- var func = g_to_func(e);
- var rect = find_child(e, "rect");
- if (func == null || rect == null)
- continue;
-
- // Save max width. Only works as we have a root frame
- var w = parseFloat(rect.attributes.width.value);
- if (w > maxwidth)
- maxwidth = w;
-
- if (func.match(re)) {
- // highlight
- var x = parseFloat(rect.attributes.x.value);
- orig_save(rect, "fill");
- rect.attributes.fill.value = "$searchcolor";
-
- // remember matches
- if (matches[x] == undefined) {
- matches[x] = w;
- } else {
- if (w > matches[x]) {
- // overwrite with parent
- matches[x] = w;
- }
- }
- searching = 1;
- }
- }
- if (!searching)
- return;
-
- searchbtn.classList.add("show");
- searchbtn.firstChild.nodeValue = "Reset Search";
-
- // calculate percent matched, excluding vertical overlap
- var count = 0;
- var lastx = -1;
- var lastw = 0;
- var keys = Array();
- for (k in matches) {
- if (matches.hasOwnProperty(k))
- keys.push(k);
- }
- // sort the matched frames by their x location
- // ascending, then width descending
- keys.sort(function(a, b){
- return a - b;
- });
- // Step through frames saving only the biggest bottom-up frames
- // thanks to the sort order. This relies on the tree property
- // where children are always smaller than their parents.
- var fudge = 0.0001; // JavaScript floating point
- for (var k in keys) {
- var x = parseFloat(keys[k]);
- var w = matches[keys[k]];
- if (x >= lastx + lastw - fudge) {
- count += w;
- lastx = x;
- lastw = w;
- }
- }
- // display matched percent
- matchedtxt.classList.remove("hide");
- var pct = 100 * count / maxwidth;
- if (pct != 100) pct = pct.toFixed(1)
- matchedtxt.firstChild.nodeValue = "Matched: " + pct + "%";
- }
-]]>
-</script>
-INC
-$im->include($inc);
-$im->filledRectangle(0, 0, $imagewidth, $imageheight, 'url(#background)');
-$im->stringTTF("title", int($imagewidth / 2), $fontsize * 2, $titletext);
-$im->stringTTF("subtitle", int($imagewidth / 2), $fontsize * 4, $subtitletext) if $subtitletext ne "";
-$im->stringTTF("details", $xpad, $imageheight - ($ypad2 / 2), " ");
-$im->stringTTF("unzoom", $xpad, $fontsize * 2, "Reset Zoom", 'class="hide"');
-$im->stringTTF("search", $imagewidth - $xpad - 100, $fontsize * 2, "Search");
-$im->stringTTF("ignorecase", $imagewidth - $xpad - 16, $fontsize * 2, "ic");
-$im->stringTTF("matched", $imagewidth - $xpad - 100, $imageheight - ($ypad2 / 2), " ");
-
-if ($palette) {
- read_palette();
-}
-
-# draw frames
-$im->group_start({id => "frames"});
-while (my ($id, $node) = each %Node) {
- my ($func, $depth, $etime) = split ";", $id;
- my $stime = $node->{stime};
- my $delta = $node->{delta};
-
- $etime = $timemax if $func eq "" and $depth == 0;
-
- my $x1 = $xpad + $stime * $widthpertime;
- my $x2 = $xpad + $etime * $widthpertime;
- my ($y1, $y2);
- unless ($inverted) {
- $y1 = $imageheight - $ypad2 - ($depth + 1) * $frameheight + $framepad;
- $y2 = $imageheight - $ypad2 - $depth * $frameheight;
- } else {
- $y1 = $ypad1 + $depth * $frameheight;
- $y2 = $ypad1 + ($depth + 1) * $frameheight - $framepad;
- }
-
- my $samples = sprintf "%.0f", ($etime - $stime) * $factor;
- (my $samples_txt = $samples) # add commas per perlfaq5
- =~ s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
-
- my $info;
- if ($func eq "" and $depth == 0) {
- $info = "all ($samples_txt $countname, 100%)";
- } else {
- my $pct = sprintf "%.2f", ((100 * $samples) / ($timemax * $factor));
- my $escaped_func = $func;
- # clean up SVG breaking characters:
- $escaped_func =~ s/&/&amp;/g;
- $escaped_func =~ s/</&lt;/g;
- $escaped_func =~ s/>/&gt;/g;
- $escaped_func =~ s/"/&quot;/g;
- $escaped_func =~ s/_\[[kwij]\]$//; # strip any annotation
- unless (defined $delta) {
- $info = "$escaped_func ($samples_txt $countname, $pct%)";
- } else {
- my $d = $negate ? -$delta : $delta;
- my $deltapct = sprintf "%.2f", ((100 * $d) / ($timemax * $factor));
- $deltapct = $d > 0 ? "+$deltapct" : $deltapct;
- $info = "$escaped_func ($samples_txt $countname, $pct%; $deltapct%)";
- }
- }
-
- my $nameattr = { %{ $nameattr{$func}||{} } }; # shallow clone
- $nameattr->{title} ||= $info;
- $im->group_start($nameattr);
-
- my $color;
- if ($func eq "--") {
- $color = $vdgrey;
- } elsif ($func eq "-") {
- $color = $dgrey;
- } elsif (defined $delta) {
- $color = color_scale($delta, $maxdelta);
- } elsif ($palette) {
- $color = color_map($colors, $func);
- } else {
- $color = color($colors, $hash, $func);
- }
- $im->filledRectangle($x1, $y1, $x2, $y2, $color, 'rx="2" ry="2"');
-
- my $chars = int( ($x2 - $x1) / ($fontsize * $fontwidth));
- my $text = "";
- if ($chars >= 3) { # room for one char plus two dots
- $func =~ s/_\[[kwij]\]$//; # strip any annotation
- $text = substr $func, 0, $chars;
- substr($text, -2, 2) = ".." if $chars < length $func;
- $text =~ s/&/&amp;/g;
- $text =~ s/</&lt;/g;
- $text =~ s/>/&gt;/g;
- }
- $im->stringTTF(undef, $x1 + 3, 3 + ($y1 + $y2) / 2, $text);
-
- $im->group_end($nameattr);
-}
-$im->group_end();
-
-print $im->svg;
-
-if ($palette) {
- write_palette();
-}
-
-# vim: ts=8 sts=8 sw=8 noexpandtab
diff --git a/ee/clickhouse/materialized_columns/util.py b/ee/clickhouse/materialized_columns/util.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/ee/clickhouse/models/group.py b/ee/clickhouse/models/group.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/ee/clickhouse/queries/experiments/utils.py b/ee/clickhouse/queries/experiments/utils.py
index 7703343596fd..357da30fbd76 100644
--- a/ee/clickhouse/queries/experiments/utils.py
+++ b/ee/clickhouse/queries/experiments/utils.py
@@ -1,69 +1,48 @@
from typing import Union
-from posthog.clickhouse.client import sync_execute
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
from posthog.constants import TREND_FILTER_TYPE_ACTIONS
from posthog.models.filters.filter import Filter
from posthog.models.team.team import Team
-from posthog.queries.query_date_range import QueryDateRange
def requires_flag_warning(filter: Filter, team: Team) -> bool:
- date_params = {}
- query_date_range = QueryDateRange(filter=filter, team=team, should_round=False)
- parsed_date_from, date_from_params = query_date_range.date_from
- parsed_date_to, date_to_params = query_date_range.date_to
- date_params.update(date_from_params)
- date_params.update(date_to_params)
-
- date_query = f"""
- {parsed_date_from}
- {parsed_date_to}
- """
-
events: set[Union[int, str]] = set()
- entities_to_use = filter.entities
- for entity in entities_to_use:
+ for entity in filter.entities:
if entity.type == TREND_FILTER_TYPE_ACTIONS:
action = entity.get_action(team.pk)
for step_event in action.get_step_events():
if step_event:
- # TODO: Fix this to detect if "all events" (i.e. None) is in the list and change the entiry query to e.g. AND 1=1
+ # TODO: Fix this to detect if "all events" (i.e. None) is in the list and change the entity query to e.g. AND 1=1
events.add(step_event)
elif entity.id is not None:
events.add(entity.id)
- entity_query = f"AND event IN %(events_list)s"
- entity_params = {"events_list": sorted(events)}
-
- # nosemgrep: clickhouse-fstring-param-audit - internal SQL fragments, values parameterized
- events_result = sync_execute(
- f"""
- SELECT
- event,
- groupArraySample(%(limit)s)(properties)
+ query = parse_select(
+ """
+ SELECT event, groupArraySample({limit})(properties)
FROM events
- WHERE
- team_id = %(team_id)s
- {entity_query}
- {date_query}
+ WHERE event IN {events}
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
GROUP BY event
""",
- {
- "team_id": team.pk,
- "limit": filter.limit or 20,
- **date_params,
- **entity_params,
- **filter.hogql_context.values,
+ placeholders={
+ "limit": ast.Constant(value=filter.limit or 20),
+ "events": ast.Constant(value=sorted(events)),
+ "date_from": ast.Constant(value=filter.date_from),
+ "date_to": ast.Constant(value=filter.date_to),
},
)
+ response = execute_hogql_query(query, team=team)
- requires_flag_warning = True
-
- for _event, property_group_list in events_result:
+ for _event, property_group_list in response.results:
for property_group in property_group_list:
if "$feature/" in property_group:
- requires_flag_warning = False
- break
+ return False
- return requires_flag_warning
+ return True
diff --git a/ee/clickhouse/queries/funnels/__init__.py b/ee/clickhouse/queries/funnels/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/ee/clickhouse/queries/funnels/test/__init__.py b/ee/clickhouse/queries/funnels/test/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel.ambr b/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel.ambr
deleted file mode 100644
index 852a3ce6a1df..000000000000
--- a/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel.ambr
+++ /dev/null
@@ -1,3484 +0,0 @@
-# serializer version: 1
-# name: TestFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group0_properties, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events_poe_v2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group0_properties, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events_poe_v2.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop,
- argMinIf(prop, timestamp, isNotNull(prop)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.3
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('finance'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.4
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.5
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('finance'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.6
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.7
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('technology'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.8
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelGroupBreakdown.test_funnel_breakdown_group.9
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('technology'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group0_properties, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events_poe_v2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group0_properties, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events_poe_v2.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop,
- argMinIf(prop, timestamp, isNotNull(prop)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.3
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (1=1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('finance'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.4
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.5
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (1=1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('finance'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.6
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.7
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (1=1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('technology'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.8
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestStrictFunnelGroupBreakdown.test_funnel_breakdown_group.9
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (1=1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('technology'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group0_properties, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events_poe_v2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group0_properties, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_aggregate_by_groups_breakdown_group_person_on_events_poe_v2.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop,
- argMinIf(prop, timestamp, isNotNull(prop)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2 ,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_3 DESC,
- step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.10
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.11
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.12
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.13
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- prop
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'play movie', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'sign up', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'buy', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'sign up', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'play movie', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('technology'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.14
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.15
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.16
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.17
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- prop
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'play movie', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'sign up', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'buy', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'sign up', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'play movie', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('technology'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.3
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.4
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.5
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- prop
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'play movie', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'sign up', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'buy', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'sign up', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'play movie', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('finance'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.6
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.7
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.8
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestUnorderedFunnelGroupBreakdown.test_funnel_breakdown_group.9
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- prop
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'play movie', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'buy', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'play movie', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'sign up', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2 ,
- if(has(['technology', 'finance'], prop), prop, 'Other') as prop
- FROM
- (SELECT *,
- prop_vals as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'buy', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'sign up', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'play movie', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '') AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, isNotNull(prop_attribution)) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['buy', 'play movie', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- AND arrayFlatten(array(prop)) = arrayFlatten(array('finance'))
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
diff --git a/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel_correlation.ambr b/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel_correlation.ambr
deleted file mode 100644
index 69659f6b91a7..000000000000
--- a/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel_correlation.ambr
+++ /dev/null
@@ -1,4902 +0,0 @@
-# serializer version: 1
-# name: TestClickhouseFunnelCorrelation.test_action_events_are_excluded_from_correlations
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(((event = 'user signed up'
- AND (has(['val'], replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', ''))))) , 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(((event = 'paid'
- AND (has(['val'], replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', ''))))) , 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up', 'user signed up', 'paid']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up', 'user signed up', 'paid']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['paid', 'user signed up'] as funnel_step_names
- SELECT event.event AS name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM events AS event
- JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON pdi.distinct_id = events.distinct_id
- JOIN funnel_actors AS actors ON pdi.person_id = actors.actor_id
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event NOT IN []
- GROUP BY name
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM funnel_actors AS actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(arrayZip(['$browser'], [replaceRegexpAll(JSONExtractRaw(person_props, '$browser'), '^"|"$', '')])) as prop
- FROM funnel_actors
- JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = funnel_actors.actor_id) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties.1
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Positive'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Positive'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties.2
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Positive'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Positive'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties.3
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Negative'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Negative'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties.4
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Negative'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Negative'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties_materialized
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(arrayZip(['$browser'], ["pmat_$browser"])) as prop
- FROM funnel_actors
- JOIN
- (SELECT id,
- argMax(pmat_$browser, version) as pmat_$browser
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = funnel_actors.actor_id) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties_materialized.1
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Positive'], "pmat_$browser")))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Positive'], argMax(person."pmat_$browser", version))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties_materialized.2
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Positive'], "pmat_$browser")))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Positive'], argMax(person."pmat_$browser", version))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties_materialized.3
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Negative'], "pmat_$browser")))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Negative'], argMax(person."pmat_$browser", version))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_basic_funnel_correlation_with_properties_materialized.4
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Negative'], "pmat_$browser")))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Negative'], argMax(person."pmat_$browser", version))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_event_properties_and_groups
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_1" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['paid', 'user signed up'] as funnel_step_names
- SELECT concat(event_name, '::', prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) as success_count,
- countDistinctIf(actor_id, steps <> target_step) as failure_count
- FROM
- (SELECT actors.actor_id as actor_id,
- actors.steps as steps,
- events.event as event_name,
- arrayJoin(JSONExtractKeysAndValues(properties, 'String')) as prop
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_1
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event IN ['positively_related', 'negatively_related'])
- GROUP BY name,
- prop
- HAVING (success_count + failure_count) > 2
- AND prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM funnel_actors AS actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_event_properties_and_groups_materialized
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_1" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['paid', 'user signed up'] as funnel_step_names
- SELECT concat(event_name, '::', prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) as success_count,
- countDistinctIf(actor_id, steps <> target_step) as failure_count
- FROM
- (SELECT actors.actor_id as actor_id,
- actors.steps as steps,
- events.event as event_name,
- arrayJoin(JSONExtractKeysAndValues(properties, 'String')) as prop
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_1
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event IN ['positively_related', 'negatively_related'])
- GROUP BY name,
- prop
- HAVING (success_count + failure_count) > 2
- AND prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM funnel_actors AS actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['paid', 'user signed up'] as funnel_step_names
- SELECT event.event AS name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event NOT IN []
- GROUP BY name
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM funnel_actors AS actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups.1
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'positively_related'
- AND actors.steps = target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups.2
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'positively_related'
- AND actors.steps <> target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups.3
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'negatively_related'
- AND actors.steps = target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups.4
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'negatively_related'
- AND actors.steps <> target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups.5
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['paid', 'user signed up'] as funnel_step_names
- SELECT event.event AS name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event NOT IN []
- GROUP BY name
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM funnel_actors AS actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups.6
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'negatively_related'
- AND actors.steps = target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups.7
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'negatively_related'
- AND actors.steps <> target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups_poe_v2
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['paid', 'user signed up'] as funnel_step_names
- SELECT event.event AS name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event NOT IN []
- GROUP BY name
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM funnel_actors AS actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups_poe_v2.1
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'positively_related'
- AND actors.steps = target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups_poe_v2.2
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'positively_related'
- AND actors.steps <> target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups_poe_v2.3
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'negatively_related'
- AND actors.steps = target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups_poe_v2.4
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'negatively_related'
- AND actors.steps <> target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups_poe_v2.5
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['paid', 'user signed up'] as funnel_step_names
- SELECT event.event AS name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event NOT IN []
- GROUP BY name
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actors.actor_id, actors.steps = target_step) AS success_count,
- countDistinctIf(actors.actor_id, actors.steps <> target_step) AS failure_count
- FROM funnel_actors AS actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups_poe_v2.6
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'negatively_related'
- AND actors.steps = target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_events_and_groups_poe_v2.7
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2020-01-14 23:59:59', 'UTC') AS date_to,
- toDateTime('2020-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['user signed up', 'paid'] as funnel_step_names
- SELECT actors.actor_id AS actor_id
- FROM events AS event
- JOIN funnel_actors AS actors ON actors.actor_id = events.$group_0
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'negatively_related'
- AND actors.steps <> target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(arrayZip(['industry'], [replaceRegexpAll(JSONExtractRaw(groups_0.group_properties_0, 'industry'), '^"|"$', '')])) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups.1
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups.2
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups.3
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups.4
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups.5
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(JSONExtractKeysAndValues(groups_0.group_properties_0, 'String')) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_materialized
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(arrayZip(['industry'], [replaceRegexpAll(JSONExtractRaw(groups_0.group_properties_0, 'industry'), '^"|"$', '')])) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_materialized.1
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_materialized.2
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_materialized.3
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_materialized.4
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_materialized.5
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(JSONExtractKeysAndValues(groups_0.group_properties_0, 'String')) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(arrayZip(['industry'], [replaceRegexpAll(JSONExtractRaw(groups_0.group_properties_0, 'industry'), '^"|"$', '')])) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events.1
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events.2
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events.3
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events.4
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events.5
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(JSONExtractKeysAndValues(groups_0.group_properties_0, 'String')) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_materialized
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(arrayZip(['industry'], [replaceRegexpAll(JSONExtractRaw(groups_0.group_properties_0, 'industry'), '^"|"$', '')])) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_materialized.1
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_materialized.2
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_materialized.3
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_materialized.4
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_materialized.5
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- e.person_id as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(JSONExtractKeysAndValues(groups_0.group_properties_0, 'String')) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_poe_v2
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(arrayZip(['industry'], [replaceRegexpAll(JSONExtractRaw(groups_0.group_properties_0, 'industry'), '^"|"$', '')])) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_poe_v2.1
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_poe_v2.2
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['positive'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_poe_v2.3
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_poe_v2.4
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (has(['negative'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelation.test_funnel_correlation_with_properties_and_groups_person_on_events_poe_v2.5
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT concat(prop.1, '::', prop.2) as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM
- (SELECT actor_id,
- funnel_actors.steps as steps,
- arrayJoin(JSONExtractKeysAndValues(groups_0.group_properties_0, 'String')) as prop
- FROM funnel_actors
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON funnel_actors.actor_id == groups_0.group_key) aggregation_target_with_props
- GROUP BY prop.1,
- prop.2
- HAVING prop.1 NOT IN []
- UNION ALL
- SELECT 'Total_Values_In_Query' as name,
- countDistinctIf(actor_id, steps = target_step) AS success_count,
- countDistinctIf(actor_id, steps <> target_step) AS failure_count
- FROM funnel_actors
- '''
-# ---
diff --git a/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel_correlations_persons.ambr b/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel_correlations_persons.ambr
deleted file mode 100644
index e7fba64b02a2..000000000000
--- a/ee/clickhouse/queries/funnels/test/__snapshots__/test_funnel_correlations_persons.ambr
+++ /dev/null
@@ -1,795 +0,0 @@
-# serializer version: 1
-# name: TestClickhouseFunnelCorrelationsActors.test_funnel_correlation_on_event_with_recordings
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id,
- final_matching_events as matching_events , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, step_1_matching_event)) as final_matching_event ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, step_1_matching_event)) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = '$pageview', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'insight analyzed', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['$pageview', 'insight analyzed']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview', 'insight analyzed']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2021-01-08 23:59:59', 'UTC') AS date_to,
- toDateTime('2021-01-01 00:00:00', 'UTC') AS date_from,
- 2 AS target_step,
- ['$pageview', 'insight analyzed'] as funnel_step_names
- SELECT actors.actor_id AS actor_id ,
- any(actors.matching_events) AS matching_events
- FROM events AS event
- JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON pdi.distinct_id = events.distinct_id
- JOIN funnel_actors AS actors ON pdi.person_id = actors.actor_id
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'insight loaded'
- AND actors.steps = target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_funnel_correlation_on_event_with_recordings.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s2']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_funnel_correlation_on_event_with_recordings.2
- '''
- WITH funnel_actors as
- (SELECT aggregation_target AS actor_id,
- final_matching_events as matching_events , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_2, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event ,
- latest_0,
- latest_2,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2,
- if(latest_2 < latest_1, NULL, "uuid_2") as "uuid_2",
- if(latest_2 < latest_1, NULL, "$session_id_2") as "$session_id_2",
- if(latest_2 < latest_1, NULL, "$window_id_2") as "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = '$pageview', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'insight analyzed', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'insight updated', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['$pageview', 'insight analyzed', 'insight updated']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['$pageview', 'insight analyzed', 'insight updated']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- toDateTime('2021-01-08 23:59:59', 'UTC') AS date_to,
- toDateTime('2021-01-01 00:00:00', 'UTC') AS date_from,
- 3 AS target_step,
- ['$pageview', 'insight analyzed', 'insight updated'] as funnel_step_names
- SELECT actors.actor_id AS actor_id ,
- any(actors.matching_events) AS matching_events
- FROM events AS event
- JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON pdi.distinct_id = events.distinct_id
- JOIN funnel_actors AS actors ON pdi.person_id = actors.actor_id
- WHERE toTimeZone(toDateTime(event.timestamp), 'UTC') >= date_from
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < date_to
- AND event.team_id = 99999
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') > actors.first_timestamp
- AND toTimeZone(toDateTime(event.timestamp), 'UTC') < COALESCE(actors.final_timestamp, actors.first_timestamp + INTERVAL 14 DAY, date_to)
- AND event.event NOT IN funnel_step_names
- AND event.event = 'insight loaded'
- AND actors.steps <> target_step
- GROUP BY actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_funnel_correlation_on_event_with_recordings.3
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s2']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_funnel_correlation_on_properties_with_recordings
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id,
- final_matching_events as matching_events , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, step_1_matching_event)) as final_matching_event ,
- latest_0,
- latest_1,
- latest_0
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, step_1_matching_event)) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = '$pageview', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'insight analyzed', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['$pageview', 'insight analyzed']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['bar'], replaceRegexpAll(JSONExtractRaw(properties, 'foo'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['bar'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'foo'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['$pageview', 'insight analyzed']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id ,
- any(funnel_actors.matching_events) AS matching_events
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_funnel_correlation_on_properties_with_recordings.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s2']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_strict_funnel_correlation_with_recordings
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id,
- final_matching_events as matching_events , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, step_1_matching_event)) as final_matching_event
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, step_1_matching_event)) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- min("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "uuid_1",
- min("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$session_id_1",
- min("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$window_id_1"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = '$pageview', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'insight analyzed', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['bar'], replaceRegexpAll(JSONExtractRaw(properties, 'foo'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['bar'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'foo'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (1=1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id ,
- any(funnel_actors.matching_events) AS matching_events
- FROM funnel_actors
- WHERE funnel_actors.steps = target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_strict_funnel_correlation_with_recordings.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s2']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_strict_funnel_correlation_with_recordings.2
- '''
- WITH funnel_actors AS
- (SELECT aggregation_target AS actor_id,
- final_matching_events as matching_events , timestamp, steps,
- final_timestamp,
- first_timestamp
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- argMax(latest_0, steps) as timestamp,
- argMax(latest_1, steps) as final_timestamp,
- argMax(latest_0, steps) as first_timestamp,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time ,
- latest_0,
- latest_1,
- latest_0,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, step_1_matching_event)) as final_matching_event
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, step_1_matching_event)) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- min("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "uuid_1",
- min("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$session_id_1",
- min("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$window_id_1"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = '$pageview', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'insight analyzed', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['bar'], replaceRegexpAll(JSONExtractRaw(properties, 'foo'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['bar'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'foo'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (1=1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2]
- ORDER BY aggregation_target SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000),
- 2 AS target_step
- SELECT funnel_actors.actor_id AS actor_id ,
- any(funnel_actors.matching_events) AS matching_events
- FROM funnel_actors
- WHERE funnel_actors.steps <> target_step
- GROUP BY funnel_actors.actor_id
- ORDER BY actor_id
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestClickhouseFunnelCorrelationsActors.test_strict_funnel_correlation_with_recordings.3
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s3']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
diff --git a/ee/clickhouse/queries/funnels/test/breakdown_cases.py b/ee/clickhouse/queries/funnels/test/breakdown_cases.py
deleted file mode 100644
index a6d1eefa1813..000000000000
--- a/ee/clickhouse/queries/funnels/test/breakdown_cases.py
+++ /dev/null
@@ -1,414 +0,0 @@
-from datetime import datetime
-from typing import Any
-
-from posthog.test.base import APIBaseTest, also_test_with_person_on_events_v2, snapshot_clickhouse_queries
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.filters import Filter
-from posthog.models.group.util import create_group
-from posthog.models.instance_setting import override_instance_config
-from posthog.queries.funnels.funnel_unordered import ClickhouseFunnelUnordered
-from posthog.queries.funnels.test.breakdown_cases import FunnelStepResult, assert_funnel_results_equal
-from posthog.test.persons import create_group_type_mapping
-from posthog.test.test_journeys import journeys_for
-
-
-def funnel_breakdown_group_test_factory(Funnel, FunnelPerson, _create_event, _create_action, _create_person):
- class TestFunnelBreakdownGroup(APIBaseTest):
- def _get_actor_ids_at_step(self, filter, funnel_step, breakdown_value=None):
- person_filter = filter.shallow_clone({"funnel_step": funnel_step, "funnel_step_breakdown": breakdown_value})
- _, serialized_result, _ = FunnelPerson(person_filter, self.team).get_actors()
-
- return [val["id"] for val in serialized_result]
-
- def _create_groups(self):
- create_group_type_mapping(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group_type_mapping(
- team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=1
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:5",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:6",
- properties={"industry": "technology"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key="org:5",
- properties={"industry": "random"},
- )
-
- def _assert_funnel_breakdown_result_is_correct(self, result, steps: list[FunnelStepResult]):
- def funnel_result(step: FunnelStepResult, order: int) -> dict[str, Any]:
- return {
- "action_id": step.name if step.type == "events" else step.action_id,
- "name": step.name,
- "custom_name": None,
- "order": order,
- "people": [],
- "count": step.count,
- "type": step.type,
- "average_conversion_time": step.average_conversion_time,
- "median_conversion_time": step.median_conversion_time,
- "breakdown": step.breakdown,
- "breakdown_value": step.breakdown,
- **(
- {
- "action_id": None,
- "name": f"Completed {order + 1} step{'s' if order > 0 else ''}",
- }
- if Funnel == ClickhouseFunnelUnordered
- else {}
- ),
- }
-
- step_results = []
- for index, step_result in enumerate(steps):
- step_results.append(funnel_result(step_result, index))
-
- assert_funnel_results_equal(result, step_results)
-
- @snapshot_clickhouse_queries
- def test_funnel_breakdown_group(self):
- self._create_groups()
-
- people = journeys_for(
- {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- }
- ],
- },
- self.team,
- )
-
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown": "industry",
- "breakdown_type": "group",
- "breakdown_group_type_index": 0,
- }
-
- filter = Filter(data=filters, team=self.team)
- result = Funnel(filter, self.team).run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown="finance", count=1),
- FunnelStepResult(
- name="play movie",
- breakdown="finance",
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown="finance",
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
-
- # Querying persons when aggregating by persons should be ok, despite group breakdown
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "finance"),
- [people["person1"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "finance"),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown="technology", count=2),
- FunnelStepResult(
- name="play movie",
- breakdown="technology",
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(name="buy", breakdown="technology", count=0),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "technology"),
- [people["person2"].uuid, people["person3"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "technology"),
- [people["person2"].uuid],
- )
-
- # TODO: Delete this test when moved to person-on-events
- @also_test_with_person_on_events_v2
- def test_funnel_aggregate_by_groups_breakdown_group(self):
- self._create_groups()
-
- journeys_for(
- {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 18),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- }
- ],
- },
- self.team,
- )
-
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown": "industry",
- "breakdown_type": "group",
- "breakdown_group_type_index": 0,
- "aggregation_group_type_index": 0,
- }
-
- result = Funnel(Filter(data=filters, team=self.team), self.team).run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown="finance", count=1),
- FunnelStepResult(
- name="play movie",
- breakdown="finance",
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown="finance",
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown="technology", count=1),
- FunnelStepResult(
- name="play movie",
- breakdown="technology",
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown="technology",
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
-
- @also_test_with_person_on_events_v2
- @snapshot_clickhouse_queries
- def test_funnel_aggregate_by_groups_breakdown_group_person_on_events(self):
- self._create_groups()
-
- journeys_for(
- {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"$group_0": "org:5", "$browser": "Chrome"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 18),
- "properties": {"$group_0": "org:6", "$browser": "Safari"},
- }
- ],
- },
- self.team,
- )
-
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown": "industry",
- "breakdown_type": "group",
- "breakdown_group_type_index": 0,
- "aggregation_group_type_index": 0,
- }
- with override_instance_config("PERSON_ON_EVENTS_ENABLED", True):
- result = Funnel(Filter(data=filters, team=self.team), self.team).run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown="finance", count=1),
- FunnelStepResult(
- name="play movie",
- breakdown="finance",
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown="finance",
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown="technology", count=1),
- FunnelStepResult(
- name="play movie",
- breakdown="technology",
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown="technology",
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
-
- return TestFunnelBreakdownGroup
diff --git a/ee/clickhouse/queries/funnels/test/test_funnel.py b/ee/clickhouse/queries/funnels/test/test_funnel.py
deleted file mode 100644
index 1bae4c40b784..000000000000
--- a/ee/clickhouse/queries/funnels/test/test_funnel.py
+++ /dev/null
@@ -1,203 +0,0 @@
-from datetime import datetime
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.filters import Filter
-from posthog.models.group.util import create_group
-from posthog.queries.funnels.funnel import ClickhouseFunnel
-from posthog.queries.funnels.funnel_persons import ClickhouseFunnelActors
-from posthog.queries.funnels.funnel_strict_persons import ClickhouseFunnelStrictActors
-from posthog.queries.funnels.funnel_unordered_persons import ClickhouseFunnelUnorderedActors
-from posthog.queries.funnels.test.test_funnel import _create_action
-from posthog.test.test_journeys import journeys_for
-from posthog.test.test_utils import create_group_type_mapping_without_created_at
-
-from products.actions.backend.models.action import Action
-from products.cohorts.backend.models.cohort import Cohort
-
-from ee.clickhouse.queries.funnels.test.breakdown_cases import funnel_breakdown_group_test_factory
-
-
-class TestFunnelGroupBreakdown(
- ClickhouseTestMixin,
- funnel_breakdown_group_test_factory( # type: ignore[misc]
- ClickhouseFunnel,
- ClickhouseFunnelActors,
- _create_event,
- _create_action,
- _create_person,
- ),
-):
- pass
-
-
-class TestUnorderedFunnelGroupBreakdown(
- ClickhouseTestMixin,
- funnel_breakdown_group_test_factory( # type: ignore[misc]
- ClickhouseFunnel,
- ClickhouseFunnelUnorderedActors,
- _create_event,
- _create_action,
- _create_person,
- ),
-):
- pass
-
-
-class TestStrictFunnelGroupBreakdown(
- ClickhouseTestMixin,
- funnel_breakdown_group_test_factory( # type: ignore[misc]
- ClickhouseFunnel,
- ClickhouseFunnelStrictActors,
- _create_event,
- _create_action,
- _create_person,
- ),
-):
- pass
-
-
-class TestClickhouseFunnel(ClickhouseTestMixin, APIBaseTest):
- maxDiff = None
-
- def test_funnel_aggregation_with_groups_with_cohort_filtering(self):
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=1
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:5",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:6",
- properties={"industry": "technology"},
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key="company:1",
- properties={},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key="company:2",
- properties={},
- )
-
- _create_person(
- distinct_ids=[f"user_1"],
- team=self.team,
- properties={"email": "[email protected]"},
- )
- _create_person(
- distinct_ids=[f"user_2"],
- team=self.team,
- properties={"email": "[email protected]"},
- )
- _create_person(
- distinct_ids=[f"user_3"],
- team=self.team,
- properties={"email": "[email protected]"},
- )
-
- Action.objects.create(team=self.team, name="action1", steps_json=[{"event": "$pageview"}])
-
- cohort = Cohort.objects.create(
- team=self.team,
- groups=[
- {
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": "[email protected]",
- "type": "person",
- }
- ]
- }
- ],
- )
-
- events_by_person = {
- "user_1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$group_0": "org:5"},
- },
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$group_0": "org:5"},
- },
- {
- "event": "user signed up", # same person, different group, so should count as different step 1 in funnel
- "timestamp": datetime(2020, 1, 10, 14),
- "properties": {"$group_0": "org:6"},
- },
- ],
- "user_2": [
- { # different person, same group, so should count as step two in funnel
- "event": "paid",
- "timestamp": datetime(2020, 1, 3, 14),
- "properties": {"$group_0": "org:5"},
- }
- ],
- "user_3": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$group_0": "org:7"},
- },
- { # person not in cohort so should be filtered out
- "event": "paid",
- "timestamp": datetime(2020, 1, 3, 14),
- "properties": {"$group_0": "org:7"},
- },
- ],
- }
- journeys_for(events_by_person, self.team)
- cohort.calculate_people_ch(pending_version=0)
-
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [
- {
- "type": "precalculated-cohort",
- "key": "id",
- "value": cohort.pk,
- }
- ],
- },
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- "aggregation_group_type_index": 0,
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnel(filter, self.team)
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 1)
diff --git a/ee/clickhouse/queries/related_actors_query.py b/ee/clickhouse/queries/related_actors_query.py
index c38e12f26b01..a59a5df79b0c 100644
--- a/ee/clickhouse/queries/related_actors_query.py
+++ b/ee/clickhouse/queries/related_actors_query.py
@@ -1,12 +1,15 @@
from datetime import timedelta
from functools import cached_property
-from typing import Optional, Union
+from typing import Optional, Union, cast
from django.utils.timezone import now
-from posthog.schema import ProductKey
+from posthog.schema import HogQLQueryModifiers, MaterializationMode, ProductKey
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
-from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.models import Team
from posthog.models.filters.utils import validate_group_type_index
@@ -22,8 +25,6 @@ from posthog.queries.actor_base_query import (
class RelatedActorsQuery:
- DISTINCT_ID_TABLE_ALIAS = "pdi"
-
"""
This query calculates other groups and persons that are related to a person or a group.
@@ -39,6 +40,10 @@ class RelatedActorsQuery:
self.team = team
self.group_type_index = validate_group_type_index("group_type_index", group_type_index)
self.id = id
+ # Treat a missing group key as the empty string (not NULL), matching the legacy raw query
+ # which read the non-nullable materialized `$group_N` column directly. This keeps the
+ # `(index, key)` tuples in the IN-subquery non-nullable.
+ self._modifiers = HogQLQueryModifiers(materializationMode=MaterializationMode.LEGACY_NULL_AS_STRING)
@property
def is_aggregating_by_groups(self) -> bool:
@@ -68,78 +73,112 @@ class RelatedActorsQuery:
with personhog_caller_tag("persons/related-actors"):
return get_serialized_people(self.team, person_ids)
+ def _group_key_field(self, group_index: int) -> ast.Expr:
+ # Read the group key from the raw event JSON rather than the `$group_N` field: the latter is
+ # zeroed for events older than the GroupTypeMapping.created_at, but the legacy raw query
+ # matched all events regardless, so we go to the JSON to preserve that behavior.
+ # JSONExtractString returns a non-nullable String (empty when missing), matching the
+ # materialized column's type so tuple/IN comparisons stay non-nullable.
+ return ast.Call(
+ name="JSONExtractString",
+ args=[ast.Field(chain=["events", "properties"]), ast.Constant(value=f"$group_{group_index}")],
+ )
+
def _query_related_people_ids(self) -> list:
- return self._take_first(
- # nosemgrep: clickhouse-injection-taint - internal SQL fragments, values parameterized
- sync_execute(
- f"""
- SELECT DISTINCT argMax(person_id, version) AS person_id
- FROM person_distinct_id2
- WHERE team_id = %(team_id)s
- AND distinct_id IN (
- SELECT distinct_id
- FROM events
- WHERE team_id = %(team_id)s
- AND timestamp > %(after)s
- AND timestamp < %(before)s
- AND {self._filter_clause}
+ # Resolve distinct_ids seen on events for this group, then map them to persons via
+ # `person_distinct_ids` — that table already applies the argMax(version) dedup and drops
+ # deleted (is_deleted=1) mappings, matching the legacy person_distinct_id2 query.
+ query = parse_select(
+ """
+ SELECT DISTINCT person_id
+ FROM person_distinct_ids
+ WHERE distinct_id IN (
+ SELECT distinct_id
+ FROM events
+ WHERE timestamp > {after}
+ AND timestamp < {before}
+ AND {group_filter}
)
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0
""",
- self._params,
- )
+ placeholders={
+ "after": ast.Constant(value=self._after),
+ "before": ast.Constant(value=self._before),
+ "group_filter": ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=self._group_key_field(cast(int, self.group_type_index)),
+ right=ast.Constant(value=self.id),
+ ),
+ },
)
+ response = execute_hogql_query(query, team=self.team, modifiers=self._modifiers)
+ return [row[0] for row in response.results]
def _query_related_groups(self, group_type_indexes: list[int]) -> list:
if not list(group_type_indexes):
return []
- array_join_tuples = ", ".join(f"(toUInt8({index}), e.$group_{index})" for index in group_type_indexes)
- query = f"""
- SELECT DISTINCT group_type_index, group_key
- FROM groups
- WHERE team_id = %(team_id)s
- AND group_type_index IN {list(group_type_indexes)}
- AND (group_type_index, group_key) IN (
- SELECT tuples.1 AS group_type_index, tuples.2 AS group_key
- FROM events e
- ARRAY JOIN arrayFilter(x -> x.2 != '', [{array_join_tuples}]) AS tuples
- WHERE team_id = %(team_id)s
- AND e.timestamp > %(after)s
- AND e.timestamp < %(before)s
- AND {f"e.$group_{self.group_type_index} = %(id)s" if self.is_aggregating_by_groups else f"e.person_id = %(id)s"}
- )
- ORDER BY group_type_index, group_key
- """
- # nosemgrep: clickhouse-injection-taint - group_type_indexes are ints from DB, values parameterized
- results = sync_execute(query, self._params)
+ # Fan each event out into one (group_type_index, group_key) row per requested group type,
+ # dropping empty keys, and collect the distinct pairs the actor co-occurred with. Existence
+ # against the groups table is enforced later by get_groups (which only returns real groups),
+ # so a key seen on events but missing from groups is dropped — matching the legacy query.
+ array_join_list = ast.Array(
+ exprs=[
+ ast.Tuple(
+ exprs=[
+ ast.Constant(value=index),
+ self._group_key_field(index),
+ ]
+ )
+ for index in group_type_indexes
+ ]
+ )
+
+ if self.is_aggregating_by_groups:
+ actor_filter: ast.Expr = ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=self._group_key_field(cast(int, self.group_type_index)),
+ right=ast.Constant(value=self.id),
+ )
+ else:
+ actor_filter = ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["events", "person_id"]),
+ right=ast.Constant(value=self.id),
+ )
+
+ query = parse_select(
+ """
+ SELECT DISTINCT tuples.1 AS group_type_index, tuples.2 AS group_key
+ FROM events
+ ARRAY JOIN arrayFilter(x -> x.2 != '', {array_join_list}) AS tuples
+ WHERE timestamp > {after}
+ AND timestamp < {before}
+ AND {actor_filter}
+ """,
+ placeholders={
+ "array_join_list": array_join_list,
+ "after": ast.Constant(value=self._after),
+ "before": ast.Constant(value=self._before),
+ "actor_filter": actor_filter,
+ },
+ )
+ response = execute_hogql_query(query, team=self.team, modifiers=self._modifiers)
+ results = response.results
if not results:
return []
serialized_results: list[SerializedGroup] = []
for index in group_type_indexes:
- group_keys = [result[1] for result in results if result[0] == index]
+ group_keys = sorted({result[1] for result in results if result[0] == index and result[1]})
_, serialized_groups = get_groups(self.team.pk, index, group_keys)
serialized_results.extend(serialized_groups)
return serialized_results
- def _take_first(self, rows: list) -> list:
- return [row[0] for row in rows]
-
- @property
- def _filter_clause(self):
- if self.is_aggregating_by_groups:
- return f"$group_{self.group_type_index} = %(id)s"
- else:
- return f"{self.DISTINCT_ID_TABLE_ALIAS}.person_id = %(id)s"
+ @cached_property
+ def _after(self):
+ return now() - timedelta(days=90)
@cached_property
- def _params(self):
- return {
- "team_id": self.team.pk,
- "id": self.id,
- "after": (now() - timedelta(days=90)).strftime("%Y-%m-%dT%H:%M:%S.%f"),
- "before": now().strftime("%Y-%m-%dT%H:%M:%S.%f"),
- }
+ def _before(self):
+ return now()
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_event_query.ambr b/ee/clickhouse/queries/test/__snapshots__/test_event_query.ambr
deleted file mode 100644
index 186076d34cc8..000000000000
--- a/ee/clickhouse/queries/test/__snapshots__/test_event_query.ambr
+++ /dev/null
@@ -1,384 +0,0 @@
-# serializer version: 1
-# name: TestEventQuery.test_account_filters
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestEventQuery.test_account_filters.1
- '''
- SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-01-14 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-21 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Jane'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Jane'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-01-14 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-21 23:59:59', 'UTC')
- '''
-# ---
-# name: TestEventQuery.test_basic_event_filter
- '''
- SELECT e.timestamp as timestamp
- FROM events e
- WHERE team_id = 99999
- AND event = 'viewed'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- '''
-# ---
-# name: TestEventQuery.test_cohort_filter
- '''
- SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'viewed'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'viewed'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')))
- '''
-# ---
-# name: TestEventQuery.test_denormalised_props
- '''
- SELECT e.timestamp as timestamp,
- e."mat_test_prop" as "mat_test_prop"
- FROM events e
- WHERE team_id = 99999
- AND event = 'user signed up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND ((has(['hi'], "mat_test_prop"))
- AND (has(['hi'], "mat_test_prop")))
- '''
-# ---
-# name: TestEventQuery.test_element
- '''
- SELECT e.timestamp as timestamp
- FROM events e
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-01-14 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-21 23:59:59', 'UTC')
- AND ((match(elements_chain, '(^|;)label(\\.|$|;|:)')))
- '''
-# ---
-# name: TestEventQuery.test_element.1
- '''
- SELECT e.timestamp as timestamp
- FROM events e
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-01-14 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-21 23:59:59', 'UTC')
- AND (0 = 191)
- '''
-# ---
-# name: TestEventQuery.test_entity_filtered_by_cohort
- '''
- SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', ''), 'test'), 0)))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(equals(persons.properties___name, 'test'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')))
- '''
-# ---
-# name: TestEventQuery.test_entity_filtered_by_multiple_session_duration_filters
- '''
- SELECT e.timestamp as timestamp,
- sessions.session_duration as session_duration,
- sessions.$session_id as $session_id
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-03 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") as sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-03 23:59:59', 'UTC')
- AND (sessions.session_duration > 90.0
- AND sessions.session_duration < 150.0)
- '''
-# ---
-# name: TestEventQuery.test_entity_filtered_by_session_duration
- '''
- SELECT e.timestamp as timestamp,
- sessions.session_duration as session_duration,
- sessions.$session_id as $session_id
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-03 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") as sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-03 23:59:59', 'UTC')
- AND (sessions.session_duration > 90.0)
- '''
-# ---
-# name: TestEventQuery.test_event_properties_filter
- '''
- SELECT e.timestamp as timestamp,
- e."properties" as "properties"
- FROM events e
- WHERE team_id = 99999
- AND event = 'viewed'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (has(['test_val'], replaceRegexpAll(JSONExtractRaw(e.properties, 'some_key'), '^"|"$', '')))
- '''
-# ---
-# name: TestEventQuery.test_event_properties_filter.1
- '''
- SELECT e.timestamp as timestamp
- FROM events e
- WHERE team_id = 99999
- AND event = 'viewed'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (has(['test_val'], replaceRegexpAll(JSONExtractRaw(e.properties, 'some_key'), '^"|"$', '')))
- '''
-# ---
-# name: TestEventQuery.test_groups_filters
- '''
- SELECT e.timestamp as timestamp
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_1
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 1
- GROUP BY group_key) groups_1 ON "$group_1" == groups_1.group_key
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND ((has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (has(['value'], replaceRegexpAll(JSONExtractRaw(group_properties_1, 'another'), '^"|"$', ''))))
- '''
-# ---
-# name: TestEventQuery.test_groups_filters_mixed
- '''
- SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['test'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['test'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND ((has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', ''))))
- '''
-# ---
-# name: TestEventQuery.test_static_cohort_filter
- '''
- SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'viewed'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'viewed'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2021-05-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN
- (SELECT person_id as id
- FROM person_static_cohort
- WHERE cohort_id = 99999
- AND team_id = 99999))
- '''
-# ---
-# name: TestEventQuery.test_unique_session_math_filtered_by_session_duration
- '''
- SELECT e.timestamp as timestamp,
- e."$session_id" as "$session_id",
- sessions.session_duration as session_duration
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-03 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") as sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-03 23:59:59', 'UTC')
- AND (sessions.session_duration > 30.0)
- '''
-# ---
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_lifecycle.ambr b/ee/clickhouse/queries/test/__snapshots__/test_lifecycle.ambr
deleted file mode 100644
index 37cfd07aa366..000000000000
--- a/ee/clickhouse/queries/test/__snapshots__/test_lifecycle.ambr
+++ /dev/null
@@ -1,672 +0,0 @@
-# serializer version: 1
-# name: TestClickhouseLifecycle.test_interval_dates_days
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2021-05-05 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))) + INTERVAL 1 day
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestClickhouseLifecycle.test_interval_dates_months
- '''
- WITH 'month' AS selected_period,
- periods AS
- (SELECT dateSub(month, number, dateTrunc(selected_period, toDateTime('2021-05-05 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('month', dateTrunc('month', toDateTime('2021-02-04 00:00:00', 'UTC')), dateTrunc('month', toDateTime('2021-05-05 23:59:59', 'UTC') + INTERVAL 1 month))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('month', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('month', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('month', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 month = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 month = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 month, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('month', toDateTime('2021-02-04 00:00:00', 'UTC'))) - INTERVAL 1 month
- AND timestamp < toDateTime(dateTrunc('month', toDateTime('2021-05-05 23:59:59', 'UTC'))) + INTERVAL 1 month
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('month', toDateTime('2021-05-05 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('month', toDateTime('2021-02-04 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestClickhouseLifecycle.test_interval_dates_weeks
- '''
- WITH 'week' AS selected_period,
- periods AS
- (SELECT dateSub(week, number, dateTrunc(selected_period, toDateTime('2021-05-06 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('week', dateTrunc('week', toDateTime('2021-04-06 00:00:00', 'UTC')), dateTrunc('week', toDateTime('2021-05-06 23:59:59', 'UTC') + INTERVAL 1 week))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('week', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('week', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('week', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 week = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 week = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 week, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('week', toDateTime('2021-04-06 00:00:00', 'UTC'))) - INTERVAL 1 week
- AND timestamp < toDateTime(dateTrunc('week', toDateTime('2021-05-06 23:59:59', 'UTC'))) + INTERVAL 1 week
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('week', toDateTime('2021-05-06 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('week', toDateTime('2021-04-06 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestClickhouseLifecycle.test_lifecycle_edge_cases
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2020-01-18 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2020-01-11 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2020-01-18 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2020-01-11 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2020-01-18 23:59:59', 'UTC'))) + INTERVAL 1 day
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2020-01-18 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2020-01-11 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestClickhouseLifecycle.test_lifecycle_hogql_event_properties
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2021-05-05 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))) + INTERVAL 1 day
- AND (ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', ''), '%example%'), 0))
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestClickhouseLifecycle.test_lifecycle_hogql_event_properties_materialized
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2021-05-05 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))) + INTERVAL 1 day
- AND (like(events.`mat_$current_url`, '%example%'))
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestClickhouseLifecycle.test_lifecycle_hogql_person_properties
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2021-05-05 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))) + INTERVAL 1 day
- AND (ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person_props, 'email'), ''), 'null'), '^"|"$', ''), '%test.com'), 0))
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestClickhouseLifecycle.test_lifecycle_hogql_person_properties_materialized
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2021-05-05 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at,
- argMax(pmat_email, version) as pmat_email
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))) + INTERVAL 1 day
- AND (like(pmat_email, '%test.com'))
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2021-05-05 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2021-04-28 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestClickhouseLifecycle.test_test_account_filters_with_groups
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2020-01-19 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC'))) + INTERVAL 1 day
- AND (has(['value'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'key'), '^"|"$', '')))
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
diff --git a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr
index cf9b28f05562..d60304ead56e 100644
--- a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr
+++ b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr
@@ -1,62 +1,78 @@
# serializer version: 1
# name: TestRelatedGroupsQuery.test_query
'''
-
- SELECT DISTINCT group_type_index,
- group_key
- FROM groups
- WHERE team_id = 99999
- AND group_type_index IN [0, 1]
- AND (group_type_index,
- group_key) IN
- (SELECT tuples.1 AS group_type_index,
- tuples.2 AS group_key
- FROM events e ARRAY
- JOIN arrayFilter(x -> x.2 != '', [(toUInt8(0), e.$group_0), (toUInt8(1), e.$group_1)]) AS tuples
- WHERE team_id = 99999
- AND e.timestamp > '2024-12-01T12:00:00.000000'
- AND e.timestamp < '2025-03-01T12:00:00.000000'
- AND e.person_id = '00000000-0000-4000-8000-000000000000')
- ORDER BY group_type_index,
- group_key
+ SELECT DISTINCT tuples.1 AS group_type_index,
+ tuples.2 AS group_key
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, nullIf(events.`$group_0`, '')), tuple(1, nullIf(events.`$group_1`, ''))]) AS tuples
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestRelatedPersonsQuery.test_query_related_people
'''
-
- SELECT DISTINCT argMax(person_id, version) AS person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND timestamp > '2024-12-01T12:00:00.000000'
- AND timestamp < '2025-03-01T12:00:00.000000'
- AND $group_0 = 'org:1')
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0
+ SELECT DISTINCT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,
+ person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE in(person_distinct_ids.distinct_id,
+ (SELECT events.distinct_id AS distinct_id
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2024-12-01 12:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.`$group_0`, 'org:1'))))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestRelatedPersonsQuery.test_query_related_people.1
'''
-
- SELECT DISTINCT group_type_index,
- group_key
- FROM groups
- WHERE team_id = 99999
- AND group_type_index IN [1]
- AND (group_type_index,
- group_key) IN
- (SELECT tuples.1 AS group_type_index,
- tuples.2 AS group_key
- FROM events e ARRAY
- JOIN arrayFilter(x -> x.2 != '', [(toUInt8(1), e.$group_1)]) AS tuples
- WHERE team_id = 99999
- AND e.timestamp > '2024-12-01T12:00:00.000000'
- AND e.timestamp < '2025-03-01T12:00:00.000000'
- AND e.$group_0 = 'org:1')
- ORDER BY group_type_index,
- group_key
+ SELECT DISTINCT tuples.1 AS group_type_index,
+ tuples.2 AS group_key
+ FROM events ARRAY
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, nullIf(events.`$group_1`, ''))]) AS tuples
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2024-12-01 12:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.`$group_0`, 'org:1'))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
diff --git a/ee/clickhouse/queries/test/test_event_query.py b/ee/clickhouse/queries/test/test_event_query.py
deleted file mode 100644
index ef3809785f45..000000000000
--- a/ee/clickhouse/queries/test/test_event_query.py
+++ /dev/null
@@ -1,750 +0,0 @@
-from freezegun import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_event,
- _create_person,
- snapshot_clickhouse_queries,
-)
-
-from posthog.clickhouse.client import sync_execute
-from posthog.models.element import Element
-from posthog.models.entity import Entity
-from posthog.models.filters import Filter
-from posthog.models.group.util import create_group
-from posthog.queries.trends.trends_event_query import TrendsEventQuery
-from posthog.test.persons import create_person
-from posthog.test.test_utils import create_group_type_mapping_without_created_at
-
-from products.actions.backend.models.action import Action
-from products.cohorts.backend.models.cohort import Cohort
-
-from ee.clickhouse.materialized_columns.columns import materialize
-
-
-def _create_cohort(**kwargs):
- team = kwargs.pop("team")
- name = kwargs.pop("name")
- groups = kwargs.pop("groups")
- is_static = kwargs.pop("is_static", False)
- cohort = Cohort.objects.create(team=team, name=name, groups=groups, is_static=is_static)
- return cohort
-
-
-class TestEventQuery(ClickhouseTestMixin, APIBaseTest):
- def setUp(self):
- super().setUp()
- self._create_sample_data()
-
- def _create_sample_data(self):
- distinct_id = "user_one_{}".format(self.team.pk)
- _create_person(distinct_ids=[distinct_id], team=self.team)
-
- _create_event(
- event="viewed",
- distinct_id=distinct_id,
- team=self.team,
- timestamp="2021-05-01 00:00:00",
- )
-
- def _run_query(self, filter: Filter, entity=None):
- entity = entity or filter.entities[0]
-
- query, params = TrendsEventQuery(
- filter=filter,
- entity=entity,
- team=self.team,
- person_on_events_mode=self.team.person_on_events_mode,
- ).get_query()
-
- result = sync_execute(query, {**params, **filter.hogql_context.values})
-
- return result, query
-
- @snapshot_clickhouse_queries
- def test_basic_event_filter(self):
- self._run_query(
- Filter(
- data={
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "events": [{"id": "viewed", "order": 0}],
- }
- )
- )
-
- def test_person_properties_filter(self):
- filter = Filter(
- data={
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "events": [{"id": "viewed", "order": 0}],
- "properties": [
- {
- "key": "email",
- "value": "@posthog.com",
- "operator": "not_icontains",
- "type": "person",
- },
- {"key": "key", "value": "val"},
- ],
- }
- )
-
- entity = Entity({"id": "viewed", "type": "events"})
-
- self._run_query(filter, entity)
-
- entity = Entity(
- {
- "id": "viewed",
- "type": "events",
- "properties": [
- {
- "key": "email",
- "value": "@posthog.com",
- "operator": "not_icontains",
- "type": "person",
- },
- {"key": "key", "value": "val"},
- ],
- }
- )
-
- filter = Filter(
- data={
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "events": [entity.to_dict()],
- }
- )
-
- self._run_query(filter, entity)
-
- @snapshot_clickhouse_queries
- def test_event_properties_filter(self):
- filter = Filter(
- data={
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "events": [{"id": "viewed", "order": 0}],
- "properties": [
- {
- "key": "some_key",
- "value": "test_val",
- "operator": "exact",
- "type": "event",
- }
- ],
- }
- )
-
- entity = Entity({"id": "viewed", "type": "events"})
-
- self._run_query(filter, entity)
-
- filter = Filter(
- data={
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "events": [{"id": "viewed", "order": 0}],
- }
- )
-
- entity = Entity(
- {
- "id": "viewed",
- "type": "events",
- "properties": [
- {
- "key": "some_key",
- "value": "test_val",
- "operator": "exact",
- "type": "event",
- }
- ],
- }
- )
-
- self._run_query(filter, entity)
-
- # just smoke test making sure query runs because no new functions are used here
- @snapshot_clickhouse_queries
- def test_cohort_filter(self):
- cohort = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "test", "type": "person"}]}],
- )
-
- filter = Filter(
- data={
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "events": [{"id": "viewed", "order": 0}],
- "properties": [{"key": "id", "value": cohort.pk, "type": "cohort"}],
- }
- )
-
- self._run_query(filter)
-
- # just smoke test making sure query runs because no new functions are used here
- @snapshot_clickhouse_queries
- def test_entity_filtered_by_cohort(self):
- cohort = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "test", "type": "person"}]}],
- )
-
- filter = Filter(
- data={
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "events": [
- {
- "id": "$pageview",
- "order": 0,
- "properties": [{"key": "id", "type": "cohort", "value": cohort.pk}],
- }
- ],
- }
- )
-
- create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "test"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-02T12:00:00Z",
- )
-
- create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "foo"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-02T12:01:00Z",
- )
-
- self._run_query(filter)
-
- # smoke test make sure query is formatted and runs
- @snapshot_clickhouse_queries
- def test_static_cohort_filter(self):
- cohort = _create_cohort(team=self.team, name="cohort1", groups=[], is_static=True)
-
- filter = Filter(
- data={
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "events": [{"id": "viewed", "order": 0}],
- "properties": [{"key": "id", "value": cohort.pk, "type": "cohort"}],
- },
- team=self.team,
- )
-
- self._run_query(filter)
-
- @snapshot_clickhouse_queries
- @freeze_time("2021-01-21")
- def test_account_filters(self):
- create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})
- create_person(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})
-
- _create_event(event="event_name", team=self.team, distinct_id="person_1")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
-
- cohort = Cohort.objects.create(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "Jane", "type": "person"}]}],
- )
- cohort.calculate_people_ch(pending_version=0)
-
- self.team.test_account_filters = [{"key": "id", "value": cohort.pk, "type": "cohort"}]
- self.team.save()
-
- filter = Filter(
- data={
- "events": [{"id": "event_name", "order": 0}],
- "filter_test_accounts": True,
- },
- team=self.team,
- )
-
- self._run_query(filter)
-
- def test_action_with_person_property_filter(self):
- create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})
- create_person(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})
-
- _create_event(event="event_name", team=self.team, distinct_id="person_1")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
-
- action = Action.objects.create(
- team=self.team,
- name="action1",
- steps_json=[{"event": "event_name", "properties": [{"key": "name", "type": "person", "value": "John"}]}],
- )
-
- filter = Filter(data={"actions": [{"id": action.id, "type": "actions", "order": 0}]})
-
- self._run_query(filter)
-
- @snapshot_clickhouse_queries
- def test_denormalised_props(self):
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [{"key": "test_prop", "value": "hi"}],
- }
- ],
- "date_from": "2020-01-01",
- "properties": [{"key": "test_prop", "value": "hi"}],
- "date_to": "2020-01-14",
- }
-
- materialize("events", "test_prop")
-
- create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"key": "value"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-02T12:00:00Z",
- properties={"test_prop": "hi"},
- )
-
- create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"key_2": "value_2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-02T12:00:00Z",
- properties={"test_prop": "hi"},
- )
-
- filter = Filter(data=filters)
- _, query = self._run_query(filter)
- self.assertIn("mat_test_prop", query)
-
- @snapshot_clickhouse_queries
- @freeze_time("2021-01-21")
- def test_element(self):
- _create_event(
- event="$autocapture",
- team=self.team,
- distinct_id="whatever",
- properties={"attr": "some_other_val"},
- elements=[
- Element(
- tag_name="a",
- href="/a-url",
- attr_class=["small"],
- text="bla bla",
- attributes={},
- nth_child=1,
- nth_of_type=0,
- ),
- Element(
- tag_name="button",
- attr_class=["btn", "btn-primary"],
- nth_child=0,
- nth_of_type=0,
- ),
- Element(tag_name="div", nth_child=0, nth_of_type=0),
- Element(tag_name="label", nth_child=0, nth_of_type=0, attr_id="nested"),
- ],
- )
- _create_event(
- event="$pageview",
- team=self.team,
- distinct_id="whatever",
- properties={"attr": "some_val"},
- elements=[
- Element(
- tag_name="a",
- href="/a-url",
- attr_class=["small"],
- text="bla bla",
- attributes={},
- nth_child=1,
- nth_of_type=0,
- ),
- Element(
- tag_name="button",
- attr_class=["btn", "btn-secondary"],
- nth_child=0,
- nth_of_type=0,
- ),
- Element(tag_name="div", nth_child=0, nth_of_type=0),
- Element(tag_name="img", nth_child=0, nth_of_type=0, attr_id="nested"),
- ],
- )
-
- filter = Filter(
- data={
- "events": [{"id": "event_name", "order": 0}],
- "properties": [
- {
- "key": "tag_name",
- "value": ["label"],
- "operator": "exact",
- "type": "element",
- }
- ],
- }
- )
-
- self._run_query(filter)
-
- self._run_query(
- filter.shallow_clone(
- {
- "properties": [
- {
- "key": "tag_name",
- "value": [],
- "operator": "exact",
- "type": "element",
- }
- ]
- }
- )
- )
-
- def _create_groups_test_data(self):
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=1
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:5",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:6",
- properties={"industry": "technology"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key="company:1",
- properties={"another": "value"},
- )
-
- create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"$browser": "test"})
- create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"$browser": "foobar"})
- create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"$browser": "test"})
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-02T12:00:00Z",
- properties={"$group_0": "org:5", "$group_1": "company:1"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-02T12:00:00Z",
- properties={"$group_0": "org:6", "$group_1": "company:1"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-02T12:00:00Z",
- properties={"$group_0": "org:6"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p3",
- timestamp="2020-01-02T12:00:00Z",
- properties={"$group_0": "org:5"},
- )
-
- @snapshot_clickhouse_queries
- def test_groups_filters(self):
- self._create_groups_test_data()
-
- filter = Filter(
- {
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "properties": [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- },
- {
- "key": "another",
- "value": "value",
- "type": "group",
- "group_type_index": 1,
- },
- ],
- },
- team=self.team,
- )
-
- results, _ = self._run_query(filter)
- self.assertEqual(len(results), 1)
-
- @snapshot_clickhouse_queries
- def test_groups_filters_mixed(self):
- self._create_groups_test_data()
-
- filter = Filter(
- {
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "properties": [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- },
- {"key": "$browser", "value": "test", "type": "person"},
- ],
- },
- team=self.team,
- )
-
- results, _ = self._run_query(filter)
- self.assertEqual(len(results), 2)
-
- @snapshot_clickhouse_queries
- def test_entity_filtered_by_session_duration(self):
- filter = Filter(
- data={
- "date_from": "2021-05-02 00:00:00",
- "date_to": "2021-05-03 00:00:00",
- "events": [
- {
- "id": "$pageview",
- "order": 0,
- "properties": [
- {
- "key": "$session_duration",
- "type": "session",
- "operator": "gt",
- "value": 90,
- }
- ],
- }
- ],
- }
- )
-
- event_timestamp_str = "2021-05-02 00:01:00"
-
- # Session starts before the date_from
- _create_event(
- team=self.team,
- event="start",
- distinct_id="p1",
- timestamp="2021-05-01 23:59:00",
- properties={"$session_id": "1abc"},
- )
- # Event that should be returned
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp=event_timestamp_str,
- properties={"$session_id": "1abc"},
- )
-
- # Event in a session that's too short
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2021-05-02 00:02:00",
- properties={"$session_id": "2abc"},
- )
- _create_event(
- team=self.team,
- event="final_event",
- distinct_id="p2",
- timestamp="2021-05-02 00:02:01",
- properties={"$session_id": "2abc"},
- )
-
- # Event with no session
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2021-05-02 00:02:00",
- )
-
- results, _ = self._run_query(filter)
- self.assertEqual(len(results), 1)
- self.assertEqual(results[0][0].strftime("%Y-%m-%d %H:%M:%S"), event_timestamp_str)
-
- @snapshot_clickhouse_queries
- def test_entity_filtered_by_multiple_session_duration_filters(self):
- filter = Filter(
- data={
- "date_from": "2021-05-02 00:00:00",
- "date_to": "2021-05-03 00:00:00",
- "events": [
- {
- "id": "$pageview",
- "order": 0,
- "properties": [
- {
- "key": "$session_duration",
- "type": "session",
- "operator": "gt",
- "value": 90,
- },
- {
- "key": "$session_duration",
- "type": "session",
- "operator": "lt",
- "value": 150,
- },
- ],
- }
- ],
- }
- )
-
- event_timestamp_str = "2021-05-02 00:01:00"
-
- # 120s session
- _create_event(
- team=self.team,
- event="start",
- distinct_id="p1",
- timestamp="2021-05-01 23:59:00",
- properties={"$session_id": "1abc"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp=event_timestamp_str,
- properties={"$session_id": "1abc"},
- )
-
- # 1s session (too short)
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2021-05-02 00:02:00",
- properties={"$session_id": "2abc"},
- )
- _create_event(
- team=self.team,
- event="final_event",
- distinct_id="p2",
- timestamp="2021-05-02 00:02:01",
- properties={"$session_id": "2abc"},
- )
-
- # 600s session (too long)
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2021-05-02 00:02:00",
- properties={"$session_id": "3abc"},
- )
- _create_event(
- team=self.team,
- event="final_event",
- distinct_id="p2",
- timestamp="2021-05-02 00:07:00",
- properties={"$session_id": "3abc"},
- )
-
- results, _ = self._run_query(filter)
- self.assertEqual(len(results), 1)
- self.assertEqual(results[0][0].strftime("%Y-%m-%d %H:%M:%S"), event_timestamp_str)
-
- @snapshot_clickhouse_queries
- def test_unique_session_math_filtered_by_session_duration(self):
- filter = Filter(
- data={
- "date_from": "2021-05-02 00:00:00",
- "date_to": "2021-05-03 00:00:00",
- "events": [
- {
- "id": "$pageview",
- "math": "unique_session",
- "order": 0,
- "properties": [
- {
- "key": "$session_duration",
- "type": "session",
- "operator": "gt",
- "value": 30,
- }
- ],
- }
- ],
- }
- )
-
- event_timestamp_str = "2021-05-02 00:01:00"
-
- # Session that should be returned
- _create_event(
- team=self.team,
- event="start",
- distinct_id="p1",
- timestamp="2021-05-02 00:00:00",
- properties={"$session_id": "1abc"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp=event_timestamp_str,
- properties={"$session_id": "1abc"},
- )
-
- # Session that's too short
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2021-05-02 00:02:00",
- properties={"$session_id": "2abc"},
- )
- _create_event(
- team=self.team,
- event="final_event",
- distinct_id="p2",
- timestamp="2021-05-02 00:02:01",
- properties={"$session_id": "2abc"},
- )
-
- results, _ = self._run_query(filter)
- self.assertEqual(len(results), 1)
- self.assertEqual(results[0][0].strftime("%Y-%m-%d %H:%M:%S"), event_timestamp_str)
diff --git a/ee/clickhouse/queries/test/test_lifecycle.py b/ee/clickhouse/queries/test/test_lifecycle.py
deleted file mode 100644
index 8fd982307bc0..000000000000
--- a/ee/clickhouse/queries/test/test_lifecycle.py
+++ /dev/null
@@ -1,296 +0,0 @@
-from datetime import datetime, timedelta
-
-from freezegun.api import freeze_time
-from posthog.test.base import also_test_with_materialized_columns, snapshot_clickhouse_queries
-
-from django.utils.timezone import now
-
-from posthog.constants import FILTER_TEST_ACCOUNTS, TRENDS_LIFECYCLE
-from posthog.models.filters.filter import Filter
-from posthog.models.group.util import create_group
-from posthog.queries.test.test_lifecycle import TestLifecycleBase
-from posthog.queries.trends.trends import Trends
-from posthog.test.persons import create_person
-from posthog.test.test_journeys import journeys_for
-from posthog.test.test_utils import create_group_type_mapping_without_created_at
-
-
-class TestClickhouseLifecycle(TestLifecycleBase):
- @snapshot_clickhouse_queries
- def test_test_account_filters_with_groups(self):
- self.team.test_account_filters = [{"key": "key", "type": "group", "value": "value", "group_type_index": 0}]
- self.team.save()
-
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group(
- self.team.pk,
- group_type_index=0,
- group_key="in",
- properties={"key": "value"},
- )
- create_group(
- self.team.pk,
- group_type_index=0,
- group_key="out",
- properties={"key": "othervalue"},
- )
-
- with freeze_time("2020-01-11T12:00:00Z"):
- create_person(distinct_ids=["person1"], team_id=self.team.pk)
-
- with freeze_time("2020-01-09T12:00:00Z"):
- create_person(distinct_ids=["person2"], team_id=self.team.pk)
-
- journeys_for(
- {
- "person1": [
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 11, 12),
- "properties": {"$group_0": "out"},
- }
- ],
- "person2": [
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 9, 12),
- "properties": {"$group_0": "in"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 12, 12),
- "properties": {"$group_0": "in"},
- },
- {
- "event": "$pageview",
- "timestamp": datetime(2020, 1, 15, 12),
- "properties": {"$group_0": "in"},
- },
- ],
- },
- self.team,
- )
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- FILTER_TEST_ACCOUNTS: True,
- },
- team=self.team,
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -1, 0, 0, -1, 0, 0, 0]},
- {"status": "new", "data": [0, 0, 0, 0, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "returning", "data": [0, 0, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_lifecycle_edge_cases(self):
- # This test tests behavior when created_at is different from first matching event and dormant/resurrecting/returning logic
- with freeze_time("2020-01-11T12:00:00Z"):
- create_person(distinct_ids=["person1"], team_id=self.team.pk)
-
- journeys_for(
- {
- "person1": [
- {"event": "$pageview", "timestamp": datetime(2020, 1, 12, 12)},
- {"event": "$pageview", "timestamp": datetime(2020, 1, 13, 12)},
- {"event": "$pageview", "timestamp": datetime(2020, 1, 15, 12)},
- {"event": "$pageview", "timestamp": datetime(2020, 1, 16, 12)},
- ]
- },
- self.team,
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-11T00:00:00Z",
- "date_to": "2020-01-18T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- },
- team=self.team,
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, 0, 0, -1, 0, 0, -1, 0]},
- {"status": "new", "data": [0, 0, 0, 0, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [0, 1, 0, 0, 1, 0, 0, 0]},
- {"status": "returning", "data": [0, 0, 1, 0, 0, 1, 0, 0]},
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_interval_dates_days(self):
- with freeze_time("2021-05-05T12:00:00Z"):
- self._setup_returning_lifecycle_data(20)
-
- result = self._run_lifecycle({"date_from": "-7d", "interval": "day"})
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0] * 8},
- {"status": "new", "data": [0] * 8},
- {"status": "resurrecting", "data": [0] * 8},
- {"status": "returning", "data": [1] * 8},
- ],
- )
- self.assertEqual(
- result[0]["days"],
- [
- "2021-04-28",
- "2021-04-29",
- "2021-04-30",
- "2021-05-01",
- "2021-05-02",
- "2021-05-03",
- "2021-05-04",
- "2021-05-05",
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_interval_dates_weeks(self):
- with freeze_time("2021-05-06T12:00:00Z"):
- self._setup_returning_lifecycle_data(50)
-
- result = self._run_lifecycle({"date_from": "-30d", "interval": "week"})
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0] * 5},
- {"status": "new", "data": [0] * 5},
- {"status": "resurrecting", "data": [0] * 5},
- {"status": "returning", "data": [1] * 5},
- ],
- )
- self.assertEqual(
- result[0]["days"],
- ["2021-04-05", "2021-04-12", "2021-04-19", "2021-04-26", "2021-05-03"],
- )
-
- @snapshot_clickhouse_queries
- def test_interval_dates_months(self):
- with freeze_time("2021-05-05T12:00:00Z"):
- self._setup_returning_lifecycle_data(120)
-
- result = self._run_lifecycle({"date_from": "-90d", "interval": "month"})
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0] * 4},
- {"status": "new", "data": [0] * 4},
- {"status": "resurrecting", "data": [0] * 4},
- {"status": "returning", "data": [1] * 4},
- ],
- )
- self.assertEqual(result[0]["days"], ["2021-02-01", "2021-03-01", "2021-04-01", "2021-05-01"])
-
- @also_test_with_materialized_columns(event_properties=["$current_url"])
- @snapshot_clickhouse_queries
- def test_lifecycle_hogql_event_properties(self):
- with freeze_time("2021-05-05T12:00:00Z"):
- self._setup_returning_lifecycle_data(20)
- result = self._run_lifecycle(
- {
- "date_from": "-7d",
- "interval": "day",
- "properties": [
- {
- "key": "like(properties.$current_url, '%example%') and 'bla' != 'a%sd'",
- "type": "hogql",
- },
- ],
- }
- )
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0] * 8},
- {"status": "new", "data": [0] * 8},
- {"status": "resurrecting", "data": [0] * 8},
- {"status": "returning", "data": [1] * 8},
- ],
- )
-
- @also_test_with_materialized_columns(event_properties=[], person_properties=["email"])
- @snapshot_clickhouse_queries
- def test_lifecycle_hogql_person_properties(self):
- with freeze_time("2021-05-05T12:00:00Z"):
- self._setup_returning_lifecycle_data(20)
- result = self._run_lifecycle(
- {
- "date_from": "-7d",
- "interval": "day",
- "properties": [
- {
- "key": "like(person.properties.email, '%test.com')",
- "type": "hogql",
- },
- ],
- }
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0] * 8},
- {"status": "new", "data": [0] * 8},
- {"status": "resurrecting", "data": [0] * 8},
- {"status": "returning", "data": [1] * 8},
- ],
- )
-
- def _setup_returning_lifecycle_data(self, days):
- with freeze_time("2019-01-01T12:00:00Z"):
- create_person(
- distinct_ids=["person1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
-
- journeys_for(
- {
- "person1": [
- {
- "event": "$pageview",
- "timestamp": (now() - timedelta(days=n)).strftime("%Y-%m-%d %H:%M:%S.%f"),
- "properties": {"$current_url": "http://example.com"},
- }
- for n in range(days)
- ]
- },
- self.team,
- create_people=False,
- )
-
- def _run_lifecycle(self, data):
- filter = Filter(
- data={
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- **data,
- },
- team=self.team,
- )
- return Trends().run(filter, self.team)
diff --git a/ee/clickhouse/queries/test/test_util.py b/ee/clickhouse/queries/test/test_util.py
index 47bbbbd52216..da9a96afb5d4 100644
--- a/ee/clickhouse/queries/test/test_util.py
+++ b/ee/clickhouse/queries/test/test_util.py
@@ -1,62 +1,10 @@
-from datetime import datetime, timedelta
-from zoneinfo import ZoneInfo
-
-from freezegun.api import freeze_time
-from posthog.test.base import _create_event
-
from posthog.clickhouse.client import sync_execute
from posthog.queries.breakdown_props import _parse_breakdown_cohorts
-from posthog.queries.util import get_earliest_timestamp
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
-def test_get_earliest_timestamp(db, team):
- with freeze_time("2021-01-21") as frozen_time:
- _create_event(
- team=team,
- event="sign up",
- distinct_id="1",
- timestamp="2020-01-04T14:10:00Z",
- )
- _create_event(
- team=team,
- event="sign up",
- distinct_id="1",
- timestamp="2020-01-06T14:10:00Z",
- )
-
- assert get_earliest_timestamp(team.id) == datetime(2020, 1, 4, 14, 10, tzinfo=ZoneInfo("UTC"))
-
- frozen_time.tick(timedelta(seconds=1))
- _create_event(
- team=team,
- event="sign up",
- distinct_id="1",
- timestamp="1984-01-06T14:10:00Z",
- )
- _create_event(
- team=team,
- event="sign up",
- distinct_id="1",
- timestamp="2014-01-01T01:00:00Z",
- )
- _create_event(
- team=team,
- event="sign up",
- distinct_id="1",
- timestamp="2015-01-01T01:00:00Z",
- )
-
- assert get_earliest_timestamp(team.id) == datetime(2015, 1, 1, 1, tzinfo=ZoneInfo("UTC"))
-
-
-@freeze_time("2021-01-21")
-def test_get_earliest_timestamp_with_no_events(db, team):
- assert get_earliest_timestamp(team.id) == datetime(2021, 1, 14, tzinfo=ZoneInfo("UTC"))
-
-
def test_parse_breakdown_cohort_query(db, team):
action = Action.objects.create(team=team, name="$pageview", steps_json=[{"event": "$pageview"}])
cohort1 = Cohort.objects.create(team=team, groups=[{"action_id": action.pk, "days": 3}], name="cohort1")
diff --git a/ee/clickhouse/views/groups.py b/ee/clickhouse/views/groups.py
index 25364924ff11..a6e9bda292e3 100644
--- a/ee/clickhouse/views/groups.py
+++ b/ee/clickhouse/views/groups.py
@@ -17,13 +17,15 @@ from rest_framework.exceptions import NotFound, ValidationError
from posthog.schema import ProductKey
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
from posthog.api.capture import CaptureInternalError, capture_internal
from posthog.api.documentation import extend_schema
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
-from posthog.clickhouse.client import sync_execute
-from posthog.clickhouse.kafka_engine import trim_quotes_expr
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard
from posthog.models import GroupUsageMetric, PropertyDefinition
@@ -803,17 +805,16 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
@action(methods=["GET"], detail=False, required_scopes=["group:read"])
def property_definitions(self, request: request.Request, **kw):
tag_queries(product=ProductKey.GROUP_ANALYTICS, feature=Feature.QUERY)
- rows = sync_execute(
- f"""
- SELECT group_type_index, tupleElement(keysAndValues, 1) as key, count(*) as count
+ query = parse_select(
+ """
+ SELECT index, tupleElement(keysAndValues, 1) AS key, count(*) AS count
FROM groups
- ARRAY JOIN JSONExtractKeysAndValuesRaw(group_properties) as keysAndValues
- WHERE team_id = %(team_id)s
- GROUP BY group_type_index, tupleElement(keysAndValues, 1)
- ORDER BY group_type_index ASC, count DESC, key ASC
- """,
- {"team_id": self.team.pk},
+ ARRAY JOIN JSONExtractKeysAndValuesRaw(properties) AS keysAndValues
+ GROUP BY index, key
+ ORDER BY index ASC, count DESC, key ASC
+ """
)
+ rows = execute_hogql_query(query, team=self.team).results
group_type_index_to_properties = defaultdict(list)
for group_type_index, key, count in rows:
@@ -840,30 +841,34 @@ class GroupsViewSet(TeamAndOrgViewSetMixin, mixins.ListModelMixin, mixins.Create
span.set_attribute("property_key", key)
span.set_attribute("has_value_filter", value_filter is not None)
- query = f"""
- SELECT {trim_quotes_expr("tupleElement(keysAndValues, 2)")} as value, count(*) as count
- FROM groups
- ARRAY JOIN JSONExtractKeysAndValuesRaw(group_properties) as keysAndValues
- WHERE team_id = %(team_id)s
- AND group_type_index = %(group_type_index)s
- AND tupleElement(keysAndValues, 1) = %(key)s
- {f"AND {trim_quotes_expr('tupleElement(keysAndValues, 2)')} ILIKE %(value_filter)s" if value_filter else ""}
- GROUP BY value
- ORDER BY count DESC, value ASC
- LIMIT 20
- """
-
- params = {
- "team_id": self.team.pk,
- "group_type_index": group_type_index,
- "key": key,
+ value_expr = "replaceRegexpAll(tupleElement(keysAndValues, 2), '^\"|\"$', '') AS value"
+ where_extra = ""
+ placeholders: dict[str, ast.Expr] = {
+ "group_type_index": ast.Constant(value=int(group_type_index)),
+ "key": ast.Constant(value=key),
}
-
if value_filter:
- params["value_filter"] = f"%{value_filter}%"
+ where_extra = "AND value ILIKE {value_filter}"
+ placeholders["value_filter"] = ast.Constant(value=f"%{value_filter}%")
+
+ # nosemgrep: hogql-fstring-audit (only constant SQL fragments value_expr/where_extra are interpolated; key/value/index go through parse_select placeholders)
+ query = parse_select(
+ f"""
+ SELECT {value_expr}, count(*) AS count
+ FROM groups
+ ARRAY JOIN JSONExtractKeysAndValuesRaw(properties) AS keysAndValues
+ WHERE index = {{group_type_index}}
+ AND tupleElement(keysAndValues, 1) = {{key}}
+ {where_extra}
+ GROUP BY value
+ ORDER BY count DESC, value ASC
+ LIMIT 20
+ """,
+ placeholders=placeholders,
+ )
tag_queries(product=ProductKey.GROUP_ANALYTICS, feature=Feature.QUERY)
- rows = sync_execute(query, params)
+ rows = execute_hogql_query(query, team=self.team).results
span.set_attribute("result_count", len(rows))
return response.Response(
diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr
index a43c1add6a93..325e5374846a 100644
--- a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr
+++ b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr
@@ -2,62 +2,81 @@
# name: GroupsViewSetTestCase.test_related_groups
'''
/* user_id:0 request:_snapshot_ */
- SELECT DISTINCT argMax(person_id, version) AS person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND timestamp > '2021-02-09T00:00:00.000000'
- AND timestamp < '2021-05-10T00:00:00.000000'
- AND $group_0 = '0::0')
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0
+ SELECT DISTINCT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id,
+ person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE in(person_distinct_ids.distinct_id,
+ (SELECT events.distinct_id AS distinct_id
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2021-02-09 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.`$group_0`, '0::0'))))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: GroupsViewSetTestCase.test_related_groups.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT DISTINCT group_type_index,
- group_key
- FROM groups
- WHERE team_id = 99999
- AND group_type_index IN [1]
- AND (group_type_index,
- group_key) IN
- (SELECT tuples.1 AS group_type_index,
- tuples.2 AS group_key
- FROM events e ARRAY
- JOIN arrayFilter(x -> x.2 != '', [(toUInt8(1), e.$group_1)]) AS tuples
- WHERE team_id = 99999
- AND e.timestamp > '2021-02-09T00:00:00.000000'
- AND e.timestamp < '2021-05-10T00:00:00.000000'
- AND e.$group_0 = '0::0')
- ORDER BY group_type_index,
- group_key
+ SELECT DISTINCT tuples.1 AS group_type_index,
+ tuples.2 AS group_key
+ FROM events ARRAY
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(1, nullIf(events.`$group_1`, ''))]) AS tuples
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2021-02-09 00:00:00.000000', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(events.`$group_0`, '0::0'))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: GroupsViewSetTestCase.test_related_groups_person
'''
/* user_id:0 request:_snapshot_ */
- SELECT DISTINCT group_type_index,
- group_key
- FROM groups
- WHERE team_id = 99999
- AND group_type_index IN [0, 1]
- AND (group_type_index,
- group_key) IN
- (SELECT tuples.1 AS group_type_index,
- tuples.2 AS group_key
- FROM events e ARRAY
- JOIN arrayFilter(x -> x.2 != '', [(toUInt8(0), e.$group_0), (toUInt8(1), e.$group_1)]) AS tuples
- WHERE team_id = 99999
- AND e.timestamp > '2021-02-09T00:00:00.000000'
- AND e.timestamp < '2021-05-10T00:00:00.000000'
- AND e.person_id = '01795392-cc00-0003-7dc7-67a694604d72')
- ORDER BY group_type_index,
- group_key
+ SELECT DISTINCT tuples.1 AS group_type_index,
+ tuples.2 AS group_key
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY
+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, nullIf(events.`$group_0`, '')), tuple(1, nullIf(events.`$group_1`, ''))]) AS tuples
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: GroupsViewSetTestCase.test_related_groups_person.1
diff --git a/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_person.ambr b/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_person.ambr
index 77b378fb1582..495d1ccb37a6 100644
--- a/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_person.ambr
+++ b/ee/clickhouse/views/test/funnel/__snapshots__/test_clickhouse_funnel_person.ambr
@@ -2,116 +2,81 @@
# name: TestFunnelPerson.test_funnel_actors_with_groups_search
'''
/* user_id:0 request:_snapshot_ */
- SELECT aggregation_target AS actor_id
+ SELECT source.actor_id AS actor_id
FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
+ (SELECT aggregation_target AS actor_id,
+ actor_id AS key
FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, '', arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1), multiply(3, step_2)])))) AS events_array,
+ [''] AS prop,
+ arrayJoin(aggregate_funnel(3, 1209600, 'first_touch', 'ordered', prop, [], arrayFilter((x, x_before, x_after) -> not(and(lessOrEquals(length(x.4), 1), ifNull(equals(x.4, x_before.4), isNull(x.4)
+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)
+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)
+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)
+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,
+ af_tuple.1 AS step_reached,
+ plus(af_tuple.1, 1) AS steps,
+ af_tuple.2 AS breakdown,
+ af_tuple.3 AS timings,
+ af_tuple.5 AS steps_bitfield,
+ aggregation_target AS aggregation_target
FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- person.person_props as person_props,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-10 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-10 23:59:59', 'UTC')
- AND ((replaceRegexpAll(JSONExtractRaw(person_props, 'email'), '^"|"$', '') ILIKE '%g0%'
- OR replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', '') ILIKE '%g0%'
- OR replaceRegexpAll(JSONExtractRaw(e.properties, 'distinct_id'), '^"|"$', '') ILIKE '%g0%'
- OR replaceRegexpAll(JSONExtractRaw(group_properties_0, 'name'), '^"|"$', '') ILIKE '%g0%'
- OR replaceRegexpAll(JSONExtractRaw(group_properties_0, 'slug'), '^"|"$', '') ILIKE '%g0%')
- AND (NOT has([''], "$group_0")))
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,
+ e.`$group_0` AS aggregation_target,
+ e.uuid AS uuid,
+ e.`$session_id` AS `$session_id`,
+ e.`$window_id` AS `$window_id`,
+ if(equals(e.event, 'step one'), 1, 0) AS step_0,
+ if(equals(e.event, 'step two'), 1, 0) AS step_1,
+ if(equals(e.event, 'step three'), 1, 0) AS step_2
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, 'name'), ''), 'null'), '^"|"$', '')), toTimeZone(groups._timestamp, 'UTC')), 1) AS properties___name,
+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, 'slug'), ''), 'null'), '^"|"$', '')), toTimeZone(groups._timestamp, 'UTC')), 1) AS properties___slug,
+ groups.group_type_index AS index,
+ groups.group_key AS key
+ FROM groups
+ WHERE and(equals(groups.team_id, 99999), equals(index, 0))
+ GROUP BY groups.group_type_index,
+ groups.group_key) AS e__group_0 ON equals(e.`$group_0`, e__group_0.key)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('step one', 'step three', 'step two')), and(or(ifNull(ilike(toString(e__person.properties___email), '%g0%'), 0), ifNull(ilike(toString(e__person.properties___name), '%g0%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'distinct_id'), ''), 'null'), '^"|"$', '')), '%g0%'), 0), ifNull(ilike(toString(e__group_0.properties___name), '%g0%'), 0), ifNull(ilike(toString(e__group_0.properties___slug), '%g0%'), 0)), ifNull(notEquals(nullIf(nullIf(e.`$group_0`, ''), 'null'), ''), 1)), and(notEquals(toString(aggregation_target), ''), isNotNull(aggregation_target))), or(equals(step_0, 1), equals(step_1, 1), equals(step_2, 1))))
+ GROUP BY aggregation_target
+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
+ WHERE bitTest(steps_bitfield, 0)
+ ORDER BY aggregation_target ASC SETTINGS join_algorithm='auto') AS source
+ ORDER BY source.actor_id ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
diff --git a/ee/tasks/auto_rollback_feature_flag.py b/ee/tasks/auto_rollback_feature_flag.py
index 596257739d74..ee1d0cfed163 100644
--- a/ee/tasks/auto_rollback_feature_flag.py
+++ b/ee/tasks/auto_rollback_feature_flag.py
@@ -1,12 +1,16 @@
from datetime import UTC, datetime, timedelta
+from typing import cast
from zoneinfo import ZoneInfo
from celery import shared_task
+from posthog.schema import TrendsQuery
+
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.models.filters.filter import Filter
+from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
+from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
+from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models.team import Team
-from posthog.queries.trends.trends import Trends
from posthog.scoping_audit import skip_team_scope_audit
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -45,21 +49,24 @@ def calculate_rolling_average(threshold_metric: dict, team: Team, timezone: str)
rolling_average_days = 7
- filter = Filter(
- data={
- **threshold_metric,
- "date_from": (curr - timedelta(days=rolling_average_days)).strftime("%Y-%m-%d %H:%M:%S.%f"),
- "date_to": curr.strftime("%Y-%m-%d %H:%M:%S.%f"),
- },
- team=team,
- )
- trends_query = Trends()
- result = trends_query.run(filter, team)
-
- if not len(result):
+ metric = {
+ **threshold_metric,
+ "date_from": (curr - timedelta(days=rolling_average_days)).strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "date_to": curr.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ }
+ # Stored rollback metrics use the lowercase legacy insight value; filter_to_query keys on the
+ # uppercase insight constants (e.g. "TRENDS").
+ if isinstance(metric.get("insight"), str):
+ metric["insight"] = metric["insight"].upper()
+
+ query = filter_to_query(metric)
+ response = TrendsQueryRunner(query=cast(TrendsQuery, query), team=team).run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+
+ results = getattr(response, "results", None)
+ if not results:
return False
- data = result[0]["data"]
+ data = results[0]["data"]
return sum(data) / rolling_average_days
diff --git a/ee/tasks/test/test_auto_rollback_feature_flag.py b/ee/tasks/test/test_auto_rollback_feature_flag.py
index f012616240f0..692f0febc621 100644
--- a/ee/tasks/test/test_auto_rollback_feature_flag.py
+++ b/ee/tasks/test/test_auto_rollback_feature_flag.py
@@ -1,5 +1,5 @@
from freezegun import freeze_time
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import patch
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -35,6 +35,7 @@ class AutoRollbackTest(ClickhouseTestMixin, APIBaseTest):
timestamp="2021-08-22 05:00:00",
properties={"prop": 1},
)
+ flush_persons_and_events()
with freeze_time("2021-08-21T21:00:00.000Z"):
self.assertEqual(
calculate_rolling_average(
@@ -102,6 +103,8 @@ class AutoRollbackTest(ClickhouseTestMixin, APIBaseTest):
properties={"prop": 1},
)
+ flush_persons_and_events()
+
with freeze_time("2021-08-21T20:00:00.000Z"):
flag = FeatureFlag.objects.create(
team=self.team,
@@ -144,6 +147,8 @@ class AutoRollbackTest(ClickhouseTestMixin, APIBaseTest):
properties={"prop": 1},
)
+ flush_persons_and_events()
+
with freeze_time("2021-08-21T00:00:00.000Z"):
flag = FeatureFlag.objects.create(
team=self.team,
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index fd7d690f5ad0..88ceed9a0c7e 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -41,11 +41,12 @@ from posthog.api.services.flags_service import FlagVersionConflictError, batch_e
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
from posthog.cdp.filters import build_behavioral_event_expr
-from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.constants import LIMIT, OFFSET
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
+from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
+from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.metrics import LABEL_TEAM_ID
from posthog.models import User
from posthog.models.activity_logging.activity_log import (
@@ -58,6 +59,7 @@ from posthog.models.activity_logging.activity_log import (
from posthog.models.activity_logging.activity_page import activity_page_response
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.filters.filter import Filter
+from posthog.models.filters.utils import earliest_timestamp_func
from posthog.models.person.util import get_person_by_uuid, validate_person_uuids_exist
from posthog.models.property.property import Property
from posthog.models.team.team import Team
@@ -65,8 +67,6 @@ from posthog.models.utils import UUIDT
from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.queries.actor_base_query import get_serialized_people
from posthog.queries.base import determine_parsed_date_for_property_matching
-from posthog.queries.person_query import PersonQuery
-from posthog.queries.util import get_earliest_timestamp
from posthog.renderers import SafeJSONRenderer
from posthog.utils import format_query_params_absolute_url, str_to_bool
@@ -517,7 +517,7 @@ class CohortFiltersField(serializers.JSONField):
class CohortSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
- earliest_timestamp_func = get_earliest_timestamp
+ earliest_timestamp_func = earliest_timestamp_func
_create_in_folder = serializers.CharField(required=False, allow_blank=True, write_only=True)
_create_static_person_ids = serializers.ListField(
required=False, child=serializers.CharField(), write_only=True, default=[]
@@ -1514,14 +1514,29 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
elif not filter.limit:
filter = filter.shallow_clone({LIMIT: 100})
- query, params = PersonQuery(filter, team.pk, cohort=cohort).get_query(paginate=True)
tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
- raw_result = sync_execute(
- query,
- {**params, **filter.hogql_context.values},
- # workload=Workload.OFFLINE, # this endpoint is only used by external API requests
+ cohort_properties: list[dict] = [{"type": "cohort", "key": "id", "value": cohort.pk}]
+ request_properties = request.GET.get("properties")
+ if request_properties:
+ for prop in json.loads(request_properties):
+ # Legacy person filters default to the "exact" operator when none is given;
+ # ActorsQuery's PersonPropertyFilter requires it explicitly.
+ if prop.get("type") != "cohort":
+ prop.setdefault("operator", "exact")
+ cohort_properties.append(prop)
+
+ actors_query = ActorsQuery(
+ select=["id"],
+ properties=cohort_properties,
+ search=request.GET.get("search") or None,
+ # Match the legacy PersonQuery ordering (created_at DESC, id DESC) so pagination
+ # leads with the newest members; ActorsQuery otherwise defaults to id ASC.
+ orderBy=["created_at DESC", "id DESC"],
+ limit=filter.limit,
+ offset=filter.offset,
)
- actor_ids = [row[0] for row in raw_result]
+ actors_response = ActorsQueryRunner(team=team, query=actors_query).run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ actor_ids = [row[0] for row in actors_response.results]
with personhog_caller_tag("cohorts/persons"):
serialized_actors = get_serialized_people(team, actor_ids, distinct_id_limit=10)
diff --git a/posthog/api/person.py b/posthog/api/person.py
index a84d97ecda75..54176e2ab7ad 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -1,7 +1,7 @@
+import json
import uuid
import builtins
-from collections.abc import Callable
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any, List, Optional, TypeVar, Union, cast # noqa: UP035
import structlog
@@ -26,7 +26,7 @@ from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework_csv import renderers as csvrenderers
-from posthog.schema import ProductKey
+from posthog.schema import ActorsQuery, ProductKey
from posthog.hogql.constants import CSV_EXPORT_LIMIT
@@ -64,15 +64,8 @@ from posthog.models.person.util import (
get_persons_mapped_by_distinct_id,
)
from posthog.personhog_client.caller_tag import personhog_caller_tag
-from posthog.queries.actor_base_query import ActorBaseQuery, get_serialized_people
-from posthog.queries.funnels import ClickhouseFunnelActors, ClickhouseFunnelTrendsActors
-from posthog.queries.funnels.funnel_strict_persons import ClickhouseFunnelStrictActors
-from posthog.queries.funnels.funnel_unordered_persons import ClickhouseFunnelUnorderedActors
-from posthog.queries.insight import insight_sync_execute
-from posthog.queries.person_query import PersonQuery
+from posthog.queries.actor_base_query import get_serialized_people
from posthog.queries.properties_timeline import PropertiesTimeline
-from posthog.queries.trends.lifecycle import Lifecycle
-from posthog.queries.trends.trends_actors import TrendsActors
from posthog.rate_limit import ClickHouseBurstRateThrottle, PersonalApiKeyRateThrottle, UserOrEmailRateThrottle
from posthog.renderers import SafeJSONRenderer
from posthog.tasks.split_person import split_person
@@ -397,22 +390,6 @@ class PersonPropertiesAtTimeResponseSerializer(serializers.Serializer):
)
-def get_funnel_actor_class(filter: Filter) -> Callable:
- funnel_actor_class: type[ActorBaseQuery]
-
- if filter.funnel_viz_type == FunnelVizType.TRENDS:
- funnel_actor_class = ClickhouseFunnelTrendsActors
- else:
- if filter.funnel_order_type == "unordered":
- funnel_actor_class = ClickhouseFunnelUnorderedActors
- elif filter.funnel_order_type == "strict":
- funnel_actor_class = ClickhouseFunnelStrictActors
- else:
- funnel_actor_class = ClickhouseFunnelActors
-
- return funnel_actor_class
-
-
_PERSON_ID_PARAMETER = OpenApiParameter(
"id",
OpenApiTypes.STR,
@@ -460,7 +437,6 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
queryset = Person.objects.none()
serializer_class = PersonSerializer
pagination_class = PersonLimitOffsetPagination
- lifecycle_class = Lifecycle
def get_throttles(self):
# API is commonly used for data deletion, so we want to throttle that less aggressively
@@ -543,18 +519,39 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
elif not filter.limit:
filter = filter.shallow_clone({LIMIT: DEFAULT_PAGE_LIMIT})
- person_query = PersonQuery(filter, team.pk)
- paginated_query, paginated_params = person_query.get_query(paginate=True, filter_future_persons=True)
-
- raw_paginated_result = insight_sync_execute(
- paginated_query,
- {**paginated_params, **filter.hogql_context.values},
- filter=filter,
- query_type="person_list",
- team_id=team.pk,
- # workload=Workload.OFFLINE, # this endpoint is only used by external API requests
+ from posthog.hogql import ast # noqa: PLC0415 — deferred to avoid a circular import at module load
+ from posthog.hogql.query import execute_hogql_query # noqa: PLC0415
+
+ from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner # noqa: PLC0415
+ from posthog.models.person.util import get_person_by_distinct_id # noqa: PLC0415
+
+ person_properties: list[dict] = []
+ raw_properties = request.GET.get("properties")
+ if raw_properties:
+ for prop in json.loads(raw_properties):
+ # Legacy person filters default to the "exact" operator; ActorsQuery requires it explicitly.
+ if prop.get("type") != "cohort":
+ prop.setdefault("operator", "exact")
+ person_properties.append(prop)
+ if filter.email:
+ person_properties.append({"type": "person", "key": "email", "value": filter.email, "operator": "exact"})
+ if filter.distinct_id:
+ # Exact match on any of the person's distinct IDs; no matching person => no results.
+ matched = get_person_by_distinct_id(team.pk, filter.distinct_id)
+ person_properties.append({"type": "hogql", "key": f"id = toUUID('{matched.uuid}')" if matched else "1 = 2"})
+ actors_query = ActorsQuery(
+ select=["id"],
+ properties=person_properties,
+ search=filter.search or None,
+ orderBy=["created_at DESC", "id DESC"],
+ limit=filter.limit,
+ offset=filter.offset,
)
- actor_ids = [row[0] for row in raw_paginated_result]
+ # Use .calculate() (not .run()) — it applies the limit/offset paginator but skips the
+ # insight-caching wrapper. With an id-only select there's no actor-column hydration, so
+ # we still hydrate the person objects ourselves via get_serialized_people.
+ actors_runner = ActorsQueryRunner(team=team, query=actors_query)
+ actor_ids = [row[0] for row in actors_runner.calculate().results]
with personhog_caller_tag("persons/list"):
serialized_actors = get_serialized_people(team, actor_ids)
@@ -574,16 +571,14 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
# TODO: Use a more scalable solution before PostHog 3000 navigation is released, and remove this param
total_count: Optional[int] = None
if "include_total" in request.GET:
- total_query, total_params = person_query.get_query(paginate=False, filter_future_persons=True)
- total_query_aggregated = f"SELECT count() FROM ({total_query})"
- raw_paginated_result = insight_sync_execute(
- total_query_aggregated,
- {**total_params, **filter.hogql_context.values},
- filter=filter,
- query_type="person_list_total",
- team_id=team.pk,
+ count_inner = actors_runner.to_query()
+ count_inner.limit = None
+ count_inner.offset = None
+ count_query = ast.SelectQuery(
+ select=[ast.Call(name="count", args=[])],
+ select_from=ast.JoinExpr(table=count_inner),
)
- total_count = raw_paginated_result[0][0]
+ total_count = execute_hogql_query(count_query, team=team).results[0][0]
next_url = format_query_params_absolute_url(request, filter.offset + filter.limit) if _should_paginate else None
previous_url = (
@@ -1192,6 +1187,128 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
}
)
+ def _legacy_session_ids_with_recordings(self, session_ids: set[str], filter: Filter) -> set[str]:
+ """Filter session ids to those with a (non-deleted) recording, mirroring the legacy actor endpoint.
+ Unlike the modern RecordingsHelper this does not apply a retention/expiry window, preserving the
+ long-standing response shape of these public endpoints.
+ """
+ if not session_ids:
+ return set()
+
+ from posthog.clickhouse.client import sync_execute # noqa: PLC0415
+
+ query = """
+ SELECT session_id
+ FROM session_replay_events
+ WHERE team_id = %(team_id)s AND session_id IN %(session_ids)s
+ """
+ params: dict[str, Any] = {"team_id": self.team.pk, "session_ids": sorted(session_ids)}
+ if filter.date_from:
+ query += " AND min_first_timestamp >= %(date_from)s"
+ params["date_from"] = filter.date_from - timedelta(days=1)
+ if filter.date_to:
+ query += " AND max_last_timestamp <= %(date_to)s"
+ params["date_to"] = filter.date_to + timedelta(days=1)
+ query += " GROUP BY session_id HAVING max(is_deleted) = 0"
+
+ return {row[0] for row in sync_execute(query, params)}
+
+ @staticmethod
+ def _legacy_breakdown_value(filter: Filter) -> Optional[Union[str, int]]:
+ """Translate the legacy `breakdown_value` request param into the value the HogQL trends actors path
+ expects: an empty string means the null/none bucket, a cohort breakdown value is an int cohort id.
+ """
+ from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL # noqa: PLC0415
+
+ value = filter.breakdown_value
+ if value is None:
+ return None
+ if filter.breakdown_type == "cohort":
+ return value if value == "all" else int(value)
+ if value == "":
+ return BREAKDOWN_NULL_STRING_LABEL
+ return value
+
+ def _run_legacy_actors_query(
+ self,
+ source: Any,
+ filter: Filter,
+ *,
+ aggregation_group_type_index: Optional[int],
+ include_value: bool,
+ include_recordings: bool,
+ ) -> tuple[builtins.list, int]:
+ """Run an ActorsQuery (the HogQL actor path used by the modern /query route) and reshape the
+ results into the legacy SerializedPerson/SerializedGroup envelope these endpoints have always
+ returned. `source` is an InsightActorsQuery or FunnelsActorsQuery.
+ """
+ from posthog.schema import HogQLQueryModifiers, InlineCohortCalculation # noqa: PLC0415
+
+ from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner # noqa: PLC0415
+ from posthog.queries.actor_base_query import get_groups # noqa: PLC0415
+
+ # Raw id-only select (plus value/recordings columns) — we hydrate actors ourselves below, matching
+ # the legacy SerializedPerson shape rather than the ActorsQuery strategy dict.
+ select: list[str] = ["actor_id"]
+ if include_value:
+ select.append("event_count")
+ if include_recordings:
+ select.append("matched_recordings")
+
+ actors_query = ActorsQuery(
+ source=source,
+ select=select,
+ limit=filter.limit,
+ offset=filter.offset,
+ )
+ # Inline cohort definitions instead of reading precomputed membership — the legacy actor queries
+ # expanded cohorts inline, so a cohort breakdown/filter works without a prior cohort calculation.
+ # The modifiers must live on the inner insight query: ActorsQueryRunner inherits its modifiers from
+ # the source query runner, which derives them from `source.source.modifiers`.
+ source.source.modifiers = (source.source.modifiers or HogQLQueryModifiers()).model_copy(
+ update={"inlineCohortCalculation": InlineCohortCalculation.ALWAYS}
+ )
+ runner = ActorsQueryRunner(team=self.team, query=actors_query)
+ results = list(runner.calculate().results)
+ raw_count = len(results)
+
+ actor_ids = [str(row[0]) for row in results]
+ value_per_actor_id: Optional[dict[str, float]] = (
+ {str(row[0]): row[1] for row in results} if include_value else None
+ )
+
+ serialized_actors: list[Any]
+ if aggregation_group_type_index is not None:
+ _, serialized_actors = get_groups(self.team.pk, aggregation_group_type_index, actor_ids, value_per_actor_id)
+ else:
+ serialized_actors = get_serialized_people(self.team, actor_ids, value_per_actor_id)
+
+ if include_recordings:
+ recordings_column_index = select.index("matched_recordings")
+ all_session_ids = {event[2] for row in results for event in row[recordings_column_index] if event[2]}
+ valid_session_ids = self._legacy_session_ids_with_recordings(all_session_ids, filter)
+ recordings_by_actor_id: dict[str, builtins.list] = {}
+ for row in results:
+ events_by_session: dict[str, builtins.list] = {}
+ for event in row[recordings_column_index]:
+ session_id = event[2]
+ if session_id and session_id in valid_session_ids:
+ events_by_session.setdefault(session_id, []).append(
+ {"timestamp": event[0], "uuid": event[1], "window_id": event[3]}
+ )
+ recordings_by_actor_id[str(row[0])] = [
+ {"session_id": session_id, "events": events} for session_id, events in events_by_session.items()
+ ]
+ for actor in serialized_actors:
+ actor["matched_recordings"] = recordings_by_actor_id.get(str(actor["id"]), [])
+
+ if include_value:
+ # get_serialized_people / get_groups fetch actors out of order, so restore the
+ # descending-by-value ordering the legacy endpoint guaranteed.
+ serialized_actors.sort(key=lambda actor: cast(float, actor["value_at_data_point"]), reverse=True)
+
+ return serialized_actors, raw_count
+
@action(methods=["GET", "POST"], detail=False)
def funnel(self, request: request.Request, **kwargs) -> response.Response:
capture_legacy_api_call(request, self.team)
@@ -1205,11 +1322,42 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def calculate_funnel_persons(
self, request: request.Request
) -> dict[str, tuple[List, Optional[str], Optional[str], int]]: # noqa: UP006
+ from posthog.schema import FunnelsActorsQuery, FunnelsQuery # noqa: PLC0415
+
+ from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query # noqa: PLC0415
+
filter = Filter(request=request, data={"insight": INSIGHT_FUNNELS}, team=self.team)
filter = prepare_actor_query_filter(filter)
- funnel_actor_class = get_funnel_actor_class(filter)
- actors, serialized_actors, raw_count = funnel_actor_class(filter, self.team).get_actors()
+ funnels_query = cast(FunnelsQuery, filter_to_query(filter.to_dict()))
+ if filter.funnel_viz_type == FunnelVizType.TRENDS:
+ # Funnel-trends actors are addressed by an entrance period + converted/dropped-off flag,
+ # not by a step index.
+ source = FunnelsActorsQuery(
+ source=funnels_query,
+ funnelTrendsDropOff=bool(filter.drop_off),
+ funnelTrendsEntrancePeriodStart=request.GET.get("entrance_period_start"),
+ funnelStepBreakdown=filter.funnel_step_breakdown,
+ includeRecordings=filter.include_recordings,
+ )
+ else:
+ funnel_step = filter.funnel_step
+ if funnel_step is None and filter.funnel_custom_steps:
+ funnel_step = filter.funnel_custom_steps[0]
+ source = FunnelsActorsQuery(
+ source=funnels_query,
+ funnelStep=funnel_step,
+ funnelStepBreakdown=filter.funnel_step_breakdown,
+ includeRecordings=filter.include_recordings,
+ )
+
+ serialized_actors, raw_count = self._run_legacy_actors_query(
+ source,
+ filter,
+ aggregation_group_type_index=funnels_query.aggregation_group_type_index,
+ include_value=False,
+ include_recordings=bool(filter.include_recordings),
+ )
initial_url = format_query_params_absolute_url(request, 0)
next_url = paginated_result(request, raw_count, filter.offset, filter.limit)
@@ -1236,11 +1384,45 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def calculate_trends_persons(
self, request: request.Request
) -> dict[str, tuple[List, Optional[str], Optional[str], int]]: # noqa: UP006
+ from posthog.schema import ChartDisplayType, InsightActorsQuery, TrendsFilter, TrendsQuery # noqa: PLC0415
+
+ from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query # noqa: PLC0415
+
filter = Filter(request=request, team=self.team)
filter = prepare_actor_query_filter(filter)
entity = get_target_entity(filter)
- actors, serialized_actors, raw_count = TrendsActors(self.team, entity, filter).get_actors()
+ # The trends person endpoint identifies its target series via the entity params (entity_id/type),
+ # not an events/actions list, so inject the resolved entity as the single series before converting.
+ filter_dict = {**filter.to_dict(), "insight": "TRENDS"}
+ entity_dict = {**entity.to_dict(), "order": 0}
+ if entity.type == "actions":
+ filter_dict["actions"] = [entity_dict]
+ filter_dict["events"] = []
+ else:
+ filter_dict["events"] = [entity_dict]
+ filter_dict["actions"] = []
+
+ trends_query = cast(TrendsQuery, filter_to_query(filter_dict))
+ # The legacy endpoint returns every actor that performed the series anywhere in the filter's date
+ # range (no per-interval `day`). A total-value display gives exactly that aggregation, so the actors
+ # builder doesn't require a `day`.
+ trends_query.trendsFilter = trends_query.trendsFilter or TrendsFilter()
+ trends_query.trendsFilter.display = ChartDisplayType.ACTIONS_BAR_VALUE
+ source = InsightActorsQuery(
+ source=trends_query,
+ series=0,
+ breakdown=self._legacy_breakdown_value(filter),
+ includeRecordings=filter.include_recordings,
+ )
+
+ serialized_actors, raw_count = self._run_legacy_actors_query(
+ source,
+ filter,
+ aggregation_group_type_index=entity.math_group_type_index,
+ include_value=True,
+ include_recordings=bool(filter.include_recordings),
+ )
next_url = paginated_result(request, raw_count, filter.offset, filter.limit)
initial_url = format_query_params_absolute_url(request, 0)
@@ -1297,15 +1479,25 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=400,
)
+ from posthog.schema import InsightActorsQuery, LifecycleQuery # noqa: PLC0415
+
+ from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query # noqa: PLC0415
+
filter = LifecycleFilter(request=request, data=request.GET.dict(), team=self.team)
filter = prepare_actor_query_filter(filter)
+ lifecycle_query = cast(LifecycleQuery, filter_to_query({**filter.to_dict(), "insight": "LIFECYCLE"}))
+ source = InsightActorsQuery(source=lifecycle_query, day=target_date, status=lifecycle_type)
+
with personhog_caller_tag("persons/lifecycle"):
- people = self.lifecycle_class().get_people(
- filter=filter,
- team=team,
+ people, raw_count = self._run_legacy_actors_query(
+ source,
+ filter,
+ aggregation_group_type_index=lifecycle_query.aggregation_group_type_index,
+ include_value=False,
+ include_recordings=False,
)
- next_url = paginated_result(request, len(people), filter.offset, filter.limit)
+ next_url = paginated_result(request, raw_count, filter.offset, filter.limit)
return response.Response({"results": [{"people": people, "count": len(people)}], "next": next_url})
@extend_schema(
diff --git a/posthog/api/test/__snapshots__/test_person.ambr b/posthog/api/test/__snapshots__/test_person.ambr
index 57ff6181986e..6268df541736 100644
--- a/posthog/api/test/__snapshots__/test_person.ambr
+++ b/posthog/api/test/__snapshots__/test_person.ambr
@@ -2,131 +2,247 @@
# name: TestPerson.test_filter_person_email
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_filter_person_list
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- where distinct_id = 'distinct_id')
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(where_optimization.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(where_optimization.id)
+ and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(persons.id)
+ and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_filter_person_list.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- where distinct_id = 'another_one')
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(where_optimization.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(where_optimization.id)
+ and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(persons.id)
+ and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_filter_person_list.2
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_filter_person_list.3
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND has(['inexistent'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', ''), 'inexistent'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.properties___email, 'inexistent'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_filter_person_list.4
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- where distinct_id = 'inexistent')
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT person.id AS id,
+ toTimeZone(person.created_at, 'UTC') AS created_at
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ WHERE 0
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_filter_person_prop
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['some_value'], replaceRegexpAll(JSONExtractRaw(properties, 'some_prop'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND (has(['some_value'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'some_prop'), '^"|"$', '')))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'some_prop'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___some_prop,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'some_prop'), ''), 'null'), '^"|"$', ''), 'some_value'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.properties___some_prop, 'some_value'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_person_property_values
@@ -173,288 +289,473 @@
# name: TestPerson.test_properties
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (JSONHas(properties, 'email')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND (JSONHas(argMax(person.properties, version), 'email'))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', ''))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE isNotNull(persons.properties___email)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_properties.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%another@gm%'))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND (replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%another@gm%')
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%another@gm%'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(ilike(toString(persons.properties___email), '%another@gm%'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_search
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%another@gm%')
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = 'another@gm')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%another@gm%')
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = 'another@gm'))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), or(ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%another@gm%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', '')), '%another@gm%'), 0), ilike(toString(where_optimization.id), '%another@gm%'), in(where_optimization.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%another@gm%'))))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE or(ifNull(ilike(toString(persons.properties___email), '%another@gm%'), 0), ifNull(ilike(toString(persons.properties___name), '%another@gm%'), 0), ilike(toString(persons.id), '%another@gm%'), in(persons.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%another@gm%'))))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_search.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%distinct_id_3%')
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = 'distinct_id_3')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%distinct_id_3%')
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = 'distinct_id_3'))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), or(ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%distinct_id_3%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', '')), '%distinct_id_3%'), 0), ilike(toString(where_optimization.id), '%distinct_id_3%'), in(where_optimization.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%distinct_id_3%'))))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE or(ifNull(ilike(toString(persons.properties___email), '%distinct_id_3%'), 0), ifNull(ilike(toString(persons.properties___name), '%distinct_id_3%'), 0), ilike(toString(persons.id), '%distinct_id_3%'), in(persons.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%distinct_id_3%'))))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPerson.test_search_person_id
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%00000000-0000-4000-8000-000000000000%')
- OR (id = '00000000-0000-4000-8000-000000000000'
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = '00000000-0000-4000-8000-000000000000'))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%00000000-0000-4000-8000-000000000000%')
- OR (id = '00000000-0000-4000-8000-000000000000'
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = '00000000-0000-4000-8000-000000000000')))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), or(ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%00000000-0000-4000-8000-000000000000%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', '')), '%00000000-0000-4000-8000-000000000000%'), 0), ilike(toString(where_optimization.id), '%00000000-0000-4000-8000-000000000000%'), in(where_optimization.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%00000000-0000-4000-8000-000000000000%'))))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE or(ifNull(ilike(toString(persons.properties___email), '%00000000-0000-4000-8000-000000000000%'), 0), ifNull(ilike(toString(persons.properties___name), '%00000000-0000-4000-8000-000000000000%'), 0), ilike(toString(persons.id), '%00000000-0000-4000-8000-000000000000%'), in(persons.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%00000000-0000-4000-8000-000000000000%'))))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_filter_person_email
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_filter_person_list
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- where distinct_id = 'distinct_id')
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(where_optimization.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(where_optimization.id)
+ and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(persons.id)
+ and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_filter_person_list.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- where distinct_id = 'another_one')
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(where_optimization.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(where_optimization.id)
+ and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.id, accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')), isNull(persons.id)
+ and isNull(accurateCastOrNull('00000000-0000-4000-8000-000000000000', 'UUID')))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_filter_person_list.2
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND has(['[email protected]'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', ''), '[email protected]'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.properties___email, '[email protected]'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_filter_person_list.3
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND has(['inexistent'], replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', ''))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', ''), 'inexistent'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.properties___email, 'inexistent'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_filter_person_list.4
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- where distinct_id = 'inexistent')
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT person.id AS id,
+ toTimeZone(person.created_at, 'UTC') AS created_at
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ WHERE 0
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_filter_person_prop
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['some_value'], replaceRegexpAll(JSONExtractRaw(properties, 'some_prop'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND (has(['some_value'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'some_prop'), '^"|"$', '')))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'some_prop'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___some_prop,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'some_prop'), ''), 'null'), '^"|"$', ''), 'some_value'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(equals(persons.properties___some_prop, 'some_value'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_person_property_values
@@ -501,157 +802,226 @@
# name: TestPersonFromClickhouse.test_properties
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (JSONHas(properties, 'email')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND (JSONHas(argMax(person.properties, version), 'email'))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', ''))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE isNotNull(persons.properties___email)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_properties.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%another@gm%'))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND (replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%another@gm%')
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%another@gm%'), 0)))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE ifNull(ilike(toString(persons.properties___email), '%another@gm%'), 0)
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_search
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%another@gm%')
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = 'another@gm')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%another@gm%')
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = 'another@gm'))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), or(ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%another@gm%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', '')), '%another@gm%'), 0), ilike(toString(where_optimization.id), '%another@gm%'), in(where_optimization.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%another@gm%'))))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE or(ifNull(ilike(toString(persons.properties___email), '%another@gm%'), 0), ifNull(ilike(toString(persons.properties___name), '%another@gm%'), 0), ilike(toString(persons.id), '%another@gm%'), in(persons.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%another@gm%'))))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_search.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%distinct_id_3%')
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = 'distinct_id_3')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%distinct_id_3%')
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = 'distinct_id_3'))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), or(ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%distinct_id_3%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', '')), '%distinct_id_3%'), 0), ilike(toString(where_optimization.id), '%distinct_id_3%'), in(where_optimization.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%distinct_id_3%'))))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE or(ifNull(ilike(toString(persons.properties___email), '%distinct_id_3%'), 0), ifNull(ilike(toString(persons.properties___name), '%distinct_id_3%'), 0), ilike(toString(persons.id), '%distinct_id_3%'), in(persons.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%distinct_id_3%'))))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonFromClickhouse.test_search_person_id
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%00000000-0000-4000-8000-000000000000%')
- OR (id = '00000000-0000-4000-8000-000000000000'
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = '00000000-0000-4000-8000-000000000000'))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%00000000-0000-4000-8000-000000000000%')
- OR (id = '00000000-0000-4000-8000-000000000000'
- OR id IN
- (SELECT person_id
- FROM
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0)
- WHERE distinct_id = '00000000-0000-4000-8000-000000000000')))
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email,
+ tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
+ argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), or(ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%00000000-0000-4000-8000-000000000000%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', '')), '%00000000-0000-4000-8000-000000000000%'), 0), ilike(toString(where_optimization.id), '%00000000-0000-4000-8000-000000000000%'), in(where_optimization.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%00000000-0000-4000-8000-000000000000%'))))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE or(ifNull(ilike(toString(persons.properties___email), '%00000000-0000-4000-8000-000000000000%'), 0), ifNull(ilike(toString(persons.properties___name), '%00000000-0000-4000-8000-000000000000%'), 0), ilike(toString(persons.id), '%00000000-0000-4000-8000-000000000000%'), in(persons.id,
+ (SELECT person_distinct_ids.person_id AS person_id
+ FROM
+ (SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS person_distinct_ids
+ WHERE ilike(person_distinct_ids.distinct_id, '%00000000-0000-4000-8000-000000000000%'))))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
diff --git a/posthog/api/test/__snapshots__/test_persons_trends.ambr b/posthog/api/test/__snapshots__/test_persons_trends.ambr
index 3dbb74fc3290..011b48a1e185 100644
--- a/posthog/api/test/__snapshots__/test_persons_trends.ambr
+++ b/posthog/api/test/__snapshots__/test_persons_trends.ambr
@@ -2,58 +2,110 @@
# name: TestPersonTrends.test_trends_people_endpoint_filters_search
'''
/* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value ,
- groupUniqArray(100)((timestamp, uuid,
- $session_id,
- $window_id)) as matching_events
+ SELECT source.actor_id AS actor_id,
+ source.event_count AS event_count,
+ source.matching_events AS matching_events,
+ source.event_distinct_ids AS event_distinct_ids
FROM
- (SELECT e.timestamp as timestamp,
- e."properties" as "properties",
- e."$window_id" as $window_id,
- e."$session_id" as $session_id,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id,
- e.uuid as uuid
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-08 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-08 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (has([''], replaceRegexpAll(JSONExtractRaw(e.properties, 'key'), '^"|"$', ''))))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
+ (SELECT actor_id AS actor_id,
+ count() AS event_count,
+ groupUniqArray(distinct_id) AS event_distinct_ids,
+ groupUniqArray(100)(tuple(timestamp, uuid, `$session_id`, `$window_id`)) AS matching_events,
+ max(timestamp) AS last_seen,
+ actor_id AS id
+ FROM
+ (SELECT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id,
+ toTimeZone(e.timestamp, 'UTC') AS timestamp,
+ e.uuid AS uuid,
+ e.`$session_id` AS `$session_id`,
+ e.`$window_id` AS `$window_id`,
+ e.distinct_id AS distinct_id
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), or(isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), ifNull(equals(ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$'), '$$_posthog_breakdown_null_$$'), 0)), equals(e.event, '$pageview')))
+ GROUP BY actor_id) AS source
+ ORDER BY source.actor_id ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonTrends.test_trends_people_endpoint_filters_search.1
'''
/* user_id:0 request:_snapshot_ */
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in []
- AND min_first_timestamp >= '2020-01-07 00:00:00'
- AND max_last_timestamp <= '2020-01-13 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
+ SELECT source.actor_id AS actor_id,
+ source.event_count AS event_count,
+ source.matching_events AS matching_events,
+ source.event_distinct_ids AS event_distinct_ids
+ FROM
+ (SELECT actor_id AS actor_id,
+ count() AS event_count,
+ groupUniqArray(distinct_id) AS event_distinct_ids,
+ groupUniqArray(100)(tuple(timestamp, uuid, `$session_id`, `$window_id`)) AS matching_events,
+ max(timestamp) AS last_seen,
+ actor_id AS id
+ FROM
+ (SELECT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id,
+ toTimeZone(e.timestamp, 'UTC') AS timestamp,
+ e.uuid AS uuid,
+ e.`$session_id` AS `$session_id`,
+ e.`$window_id` AS `$window_id`,
+ e.distinct_id AS distinct_id
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), or(ifNull(ilike(toString(e__person.properties___email), '%ben%'), 0), ifNull(ilike(toString(e__person.properties___name), '%ben%'), 0), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'distinct_id'), ''), 'null'), '^"|"$', '')), '%ben%'), 0)), greaterOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), or(isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), ifNull(equals(ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$'), '$$_posthog_breakdown_null_$$'), 0)), equals(e.event, '$pageview')))
+ GROUP BY actor_id) AS source
+ ORDER BY source.actor_id ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonTrends.test_trends_people_endpoint_filters_search.2
@@ -126,45 +178,50 @@
# name: TestPersonTrends.test_trends_people_endpoint_includes_recordings
'''
/* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value ,
- groupUniqArray(100)((timestamp, uuid,
- $session_id,
- $window_id)) as matching_events
+ SELECT source.actor_id AS actor_id,
+ source.event_count AS event_count,
+ source.matching_events AS matching_events,
+ source.event_distinct_ids AS event_distinct_ids
FROM
- (SELECT e.timestamp as timestamp,
- e."properties" as "properties",
- e."$window_id" as $window_id,
- e."$session_id" as $session_id,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id,
- e.uuid as uuid
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-08 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-08 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (has([''], replaceRegexpAll(JSONExtractRaw(e.properties, 'key'), '^"|"$', ''))))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
+ (SELECT actor_id AS actor_id,
+ count() AS event_count,
+ groupUniqArray(distinct_id) AS event_distinct_ids,
+ groupUniqArray(100)(tuple(timestamp, uuid, `$session_id`, `$window_id`)) AS matching_events,
+ max(timestamp) AS last_seen,
+ actor_id AS id
+ FROM
+ (SELECT if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS actor_id,
+ toTimeZone(e.timestamp, 'UTC') AS timestamp,
+ e.uuid AS uuid,
+ e.`$session_id` AS `$session_id`,
+ e.`$window_id` AS `$window_id`,
+ e.distinct_id AS distinct_id
+ FROM events AS e
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), or(isNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), ifNull(equals(ifNull(nullIf(leftUTF8(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'key'), ''), 'null'), '^"|"$', '')), 400), ''), '$$_posthog_breakdown_null_$$'), '$$_posthog_breakdown_null_$$'), 0)), equals(e.event, '$pageview')))
+ GROUP BY actor_id) AS source
+ ORDER BY source.actor_id ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonTrends.test_trends_people_endpoint_includes_recordings.1
@@ -173,7 +230,7 @@
SELECT session_id
FROM session_replay_events
WHERE team_id = 99999
- and session_id in ['s1']
+ AND session_id IN ['s1']
AND min_first_timestamp >= '2020-01-07 00:00:00'
AND max_last_timestamp <= '2020-01-13 23:59:59'
GROUP BY session_id
diff --git a/posthog/api/test/__snapshots__/test_properties_timeline.ambr b/posthog/api/test/__snapshots__/test_properties_timeline.ambr
index 891f01057411..dedc6e682ce8 100644
--- a/posthog/api/test/__snapshots__/test_properties_timeline.ambr
+++ b/posthog/api/test/__snapshots__/test_properties_timeline.ambr
@@ -2,324 +2,361 @@
# name: TestPersonPropertiesTimeline.test_timeline_for_existing_actor_with_six_events_but_only_two_relevant_changes
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-05 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_existing_actor_with_six_events_but_only_two_relevant_changes_without_events
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-05 23:59:59.999999', 6, 'UTC'))))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_existing_actor_with_six_events_but_only_two_relevant_changes_without_filters
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array() AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ '' AS relevant_property_values,
+ lagInFrame('') OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-05 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_existing_actor_with_three_events_and_return_to_previous_value
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-05 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_existing_person_with_three_events_and_return_to_previous_value_at_single_day_point
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-02 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-02 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_existing_person_with_three_events_and_return_to_previous_value_at_single_hour_point
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 01:00:00', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-02 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-02 01:00:00.000000', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_existing_person_with_three_events_and_return_to_previous_value_at_single_month_point
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfMonth(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-31 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-31 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_existing_person_with_three_events_and_return_to_previous_value_using_relative_date_from
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-09 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-02 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-09 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_new_actor_with_one_event_before_range
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-05 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_new_actor_with_one_event_before_range_materialized
@@ -363,37 +400,41 @@
# name: TestPersonPropertiesTimeline.test_timeline_for_new_actor_with_one_event_in_range
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-05 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_for_new_actor_with_one_event_in_range_materialized
@@ -437,37 +478,41 @@
# name: TestPersonPropertiesTimeline.test_timeline_with_two_events_in_range_using_breakdown
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(person_properties, 'foo'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'foo'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'foo'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-05 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_with_two_events_in_range_using_breakdown_materialized
@@ -513,37 +558,41 @@
# name: TestPersonPropertiesTimeline.test_timeline_with_two_events_in_range_using_filter_on_series
'''
/* user_id:0 request:_snapshot_ */
- SELECT timestamp, properties,
- end_event_number - start_event_number AS relevant_event_count
+ SELECT timestamp AS timestamp,
+ properties AS properties,
+ minus(end_event_number, start_event_number) AS relevant_event_count
FROM
- (SELECT timestamp, properties,
- start_event_number,
- leadInFrame(start_event_number) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ (SELECT timestamp AS timestamp,
+ properties AS properties,
+ start_event_number AS start_event_number,
+ leadInFrame(start_event_number, 1, plus(total_events, 1)) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
FROM
- (SELECT timestamp, person_properties AS properties,
- array(replaceRegexpAll(JSONExtractRaw(person_properties, 'bar'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(person_properties, 'foo'), '^"|"$', '')) AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (
- ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (
- ORDER BY timestamp ASC) AS start_event_number
- FROM (
- (SELECT e.timestamp AS timestamp,
- e."person_properties" AS "person_properties"
- FROM events e
- WHERE team_id = 99999
- AND person_id = '00000000-0000-0000-0000-000000000000'
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- ORDER BY timestamp ASC)
- UNION ALL
- (SELECT NULL AS timestamp,
- '' AS "person_properties")))
- WHERE start_event_number = 1
- OR relevant_property_values != previous_relevant_property_values
- OR timestamp IS NULL)
- WHERE timestamp IS NOT NULL
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.person_properties AS properties,
+ toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'foo'), ''), 'null'), '^"|"$', ''))) AS relevant_property_values,
+ lagInFrame(toString(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'bar'), ''), 'null'), '^"|"$', ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'foo'), ''), 'null'), '^"|"$', '')))) OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.person_id, toUUIDOrNull('12345678-0000-0000-0000-000000000001')), greaterOrEquals(events.timestamp, toDateTime64('2020-01-01 00:00:00.000000', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('2020-01-05 23:59:59.999999', 6, 'UTC')), equals(events.event, '$pageview')))
+ WHERE or(equals(start_event_number, 1), ifNull(notEquals(relevant_property_values, previous_relevant_property_values), isNotNull(relevant_property_values)
+ or isNotNull(previous_relevant_property_values))))
+ ORDER BY timestamp ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestPersonPropertiesTimeline.test_timeline_with_two_events_in_range_using_filter_on_series_materialized
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 83a48d17117d..9ba4290d8c2f 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -2,6 +2,7 @@ import json
from datetime import datetime, timedelta
from typing import Any, Optional
+from freezegun import freeze_time
from posthog.test.base import (
APIBaseTest,
ClickhouseTestMixin,
@@ -2498,6 +2499,35 @@ [email protected],
response = self.client.get(f"/api/cohort/{cohort.pk}/persons")
self.assertEqual(len(response.json()["results"]), 2, response)
+ def test_cohort_persons_paginate_newest_created_first(self):
+ # Members must paginate by created_at DESC (newest first), matching the legacy PersonQuery order.
+ # `created_at` order is deliberately decorrelated from insertion order (id) so that the
+ # ActorsQuery default (id ASC) produces a different first page than the required order —
+ # otherwise this regression is invisible (get_serialized_people re-sorts each page by
+ # created_at DESC, so a single page always *looks* correctly ordered).
+ created_at_by_label = {"a": "2021-01-02", "b": "2021-01-04", "c": "2021-01-01", "d": "2021-01-03"}
+ uuid_by_label = {}
+ for label in ["a", "b", "c", "d"]: # insertion order → ascending id
+ with freeze_time(created_at_by_label[label]):
+ person = create_person(team=self.team, distinct_ids=[label], properties={"$os": "Chrome"})
+ uuid_by_label[label] = str(person.uuid)
+
+ cohort = Cohort.objects.create(
+ team=self.team,
+ groups=[{"properties": [{"key": "$os", "value": "Chrome", "type": "person"}]}],
+ )
+ cohort.calculate_people_ch(pending_version=0)
+
+ paged_ids: list[str] = []
+ url: Optional[str] = f"/api/cohort/{cohort.pk}/persons?limit=2"
+ while url:
+ page = self.client.get(url).json()
+ paged_ids += [row["id"] for row in page["results"]]
+ url = page["next"]
+
+ expected = [uuid_by_label[label] for label in ["b", "d", "a", "c"]] # created_at DESC
+ self.assertEqual(paged_ids, expected)
+
@patch("django.db.transaction.on_commit", side_effect=lambda func: func())
@patch("posthog.api.cohort.report_user_action")
@patch("posthog.tasks.calculate_cohort.chain")
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 87207b14bb9d..14a549cd2993 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -1,6 +1,6 @@
import json
from typing import Optional, cast
-from uuid import uuid4
+from uuid import UUID, uuid4
import pytest
from freezegun.api import freeze_time
@@ -1656,7 +1656,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
create_person_in_ch(team_id=self.team.pk, version=0)
returned_ids = []
- with self.assertNumQueries(9):
+ with self.assertNumQueries(16):
response = self.client.get("/api/person/?limit=10").json()
self.assertEqual(len(response["results"]), 9)
returned_ids += [x["distinct_ids"][0] for x in response["results"]]
@@ -1667,10 +1667,35 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
created_ids.reverse() # ids are returned in desc order
self.assertEqual(returned_ids, created_ids, returned_ids)
- with self.assertNumQueries(9):
+ with self.assertNumQueries(20):
response_include_total = self.client.get("/api/person/?limit=10&include_total").json()
self.assertEqual(response_include_total["count"], 20) # With `include_total`, the total count is returned too
+ @freeze_time("2021-08-25T22:09:14.252Z")
+ def test_pagination_no_gaps_or_duplicates_when_created_at_is_tied(self):
+ # Bulk-created persons can share an identical created_at, so the `created_at DESC` ordering
+ # falls to the `id DESC` tiebreaker. Page boundaries must stay disjoint and complete: every
+ # person returned exactly once, with no gaps or duplicates across pages — the failure mode
+ # that actually matters on this high-traffic paginated endpoint.
+ uuids = [UUID(f"00000000-0000-0000-0000-0000000000{i:02d}") for i in range(1, 8)]
+ for person_uuid in uuids:
+ create_person(team=self.team, distinct_ids=[str(person_uuid)], uuid=person_uuid)
+
+ expected = {str(person_uuid) for person_uuid in uuids}
+ full = [row["id"] for row in self.client.get("/api/person/?limit=100").json()["results"]]
+ self.assertEqual(set(full), expected)
+ self.assertEqual(len(full), len(uuids)) # complete in a single page
+
+ # Paging with a small limit must cover exactly the same set, once each.
+ paged: list[str] = []
+ url: Optional[str] = "/api/person/?limit=2"
+ while url:
+ page = self.client.get(url).json()
+ paged += [row["id"] for row in page["results"]]
+ url = page["next"]
+ self.assertEqual(len(paged), len(uuids)) # no person lost or repeated at a page boundary
+ self.assertEqual(set(paged), expected) # union of pages == full set, gapless and dup-free
+
def test_retrieve_person(self):
person = create_person( # creating without _create_person to guarentee created_at ordering
team=self.team, distinct_ids=["123456789"]
diff --git a/posthog/hogql_queries/insights/funnels/funnel_trends.py b/posthog/hogql_queries/insights/funnels/funnel_trends.py
index 83c9fbb8f37e..85d479e9f6fd 100644
--- a/posthog/hogql_queries/insights/funnels/funnel_trends.py
+++ b/posthog/hogql_queries/insights/funnels/funnel_trends.py
@@ -16,9 +16,9 @@ from posthog.hogql_queries.insights.funnels.funnel_query_context import FunnelQu
from posthog.hogql_queries.insights.utils.breakdowns import NOT_IN_COHORT_ID
from posthog.hogql_queries.insights.utils.utils import get_start_of_interval_hogql, get_start_of_interval_hogql_str
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.hogql_queries.utils.timestamp_utils import format_label_date
+from posthog.hogql_queries.utils.timestamp_utils import format_label_date, get_earliest_timestamp_unfiltered
from posthog.queries.breakdown_props import get_breakdown_cohort_name
-from posthog.queries.util import correct_result_for_sampling, get_earliest_timestamp, get_interval_func_ch
+from posthog.queries.util import correct_result_for_sampling, get_interval_func_ch
from posthog.utils import DATERANGE_MAP, relative_date_parse
@@ -456,7 +456,7 @@ class FunnelTrendsUDF(FunnelUDFMixin, FunnelBase):
date_range = self._date_range()
if date_range.date_from() is None:
- _date_from = get_earliest_timestamp(team.pk)
+ _date_from = get_earliest_timestamp_unfiltered(team)
else:
_date_from = date_range.date_from()
diff --git a/posthog/hogql_queries/utils/query_date_range.py b/posthog/hogql_queries/utils/query_date_range.py
index b71ac54323db..924606043763 100644
--- a/posthog/hogql_queries/utils/query_date_range.py
+++ b/posthog/hogql_queries/utils/query_date_range.py
@@ -10,7 +10,7 @@ from posthog.schema import DateRange, IntervalType
from posthog.hogql.parser import ast
from posthog.models.team import Team, WeekStartDay
-from posthog.queries.util import get_earliest_timestamp, get_trunc_func_ch
+from posthog.queries.util import get_trunc_func_ch
from posthog.utils import DEFAULT_DATE_FROM_DAYS, relative_date_parse, relative_date_parse_with_delta_mapping
IntervalLiteral = Literal["second", "minute", "hour", "day", "week", "month"]
@@ -129,7 +129,10 @@ class QueryDateRange:
if self._earliest_timestamp_fallback:
return self._earliest_timestamp_fallback
- return get_earliest_timestamp(self._team.pk)
+ # Imported here to break the cycle: timestamp_utils imports QueryDateRange.
+ from posthog.hogql_queries.utils.timestamp_utils import get_earliest_timestamp_unfiltered # noqa: PLC0415
+
+ return get_earliest_timestamp_unfiltered(self._team)
def date_from(self) -> datetime:
date_from: datetime
diff --git a/posthog/hogql_queries/utils/test/test_timestamp_utils.py b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
index caed96961db6..106a327322fc 100644
--- a/posthog/hogql_queries/utils/test/test_timestamp_utils.py
+++ b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
@@ -1,6 +1,7 @@
import datetime
from zoneinfo import ZoneInfo
+from freezegun.api import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from unittest.mock import MagicMock, patch
@@ -20,6 +21,7 @@ from posthog.hogql_queries.utils.timestamp_utils import (
_get_earliest_timestamp_cache_key,
format_label_date,
get_earliest_timestamp_from_series,
+ get_earliest_timestamp_unfiltered,
)
from posthog.models.team import WeekStartDay
@@ -350,6 +352,45 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):
cached_earliest_timestamp = get_earliest_timestamp_from_series(self.team, series)
self.assertEqual(cached_earliest_timestamp, earliest_timestamp)
+ @freeze_time("2021-01-21")
+ def test_unfiltered_earliest_timestamp_returns_earliest_event(self):
+ _create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2020-01-04T14:10:00Z")
+ _create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2020-01-06T14:10:00Z")
+ flush_persons_and_events()
+
+ assert get_earliest_timestamp_unfiltered(self.team) == datetime.datetime(
+ 2020, 1, 4, 14, 10, tzinfo=datetime.UTC
+ )
+
+ @freeze_time("2021-01-21")
+ def test_unfiltered_earliest_timestamp_floors_at_2015(self):
+ # Events before 2015-01-01 are treated as corrupt and ignored.
+ _create_event(team=self.team, event="sign up", distinct_id="1", timestamp="1984-01-06T14:10:00Z")
+ _create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2014-01-01T01:00:00Z")
+ _create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2015-01-01T01:00:00Z")
+ _create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2020-01-04T14:10:00Z")
+ flush_persons_and_events()
+
+ assert get_earliest_timestamp_unfiltered(self.team) == datetime.datetime(2015, 1, 1, 1, tzinfo=datetime.UTC)
+
+ @freeze_time("2021-01-21")
+ def test_unfiltered_earliest_timestamp_falls_back_when_no_events(self):
+ # No events: fall back to now - DEFAULT_EARLIEST_TIME_DELTA (one week).
+ assert get_earliest_timestamp_unfiltered(self.team) == datetime.datetime(2021, 1, 14, tzinfo=datetime.UTC)
+
+ @freeze_time("2021-01-21")
+ def test_unfiltered_earliest_timestamp_caches_real_result(self):
+ _create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2021-01-01T12:00:00Z")
+ flush_persons_and_events()
+
+ earliest_timestamp = get_earliest_timestamp_unfiltered(self.team)
+
+ # A later-added earlier event should not change the cached value within the TTL.
+ _create_event(team=self.team, event="sign up", distinct_id="1", timestamp="2020-01-01T12:00:00Z")
+ flush_persons_and_events()
+
+ assert get_earliest_timestamp_unfiltered(self.team) == earliest_timestamp
+
@parameterized.expand(
[
# Naive inputs are interpreted in the passed (team) timezone, not UTC.
diff --git a/posthog/hogql_queries/utils/timestamp_utils.py b/posthog/hogql_queries/utils/timestamp_utils.py
index fc4534bf0691..50c42c24697c 100644
--- a/posthog/hogql_queries/utils/timestamp_utils.py
+++ b/posthog/hogql_queries/utils/timestamp_utils.py
@@ -7,6 +7,7 @@ from typing import Any, Union
from django.conf import settings
from django.core.cache import cache
+from django.utils import timezone
from dateutil.parser import parse as parse_datetime
from dateutil.relativedelta import MO, SU, relativedelta
@@ -28,6 +29,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_context
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
+from posthog.models.event import DEFAULT_EARLIEST_TIME_DELTA
from posthog.models.team import WeekStartDay
from posthog.utils import get_safe_cache
@@ -35,6 +37,8 @@ from products.actions.backend.models.action import Action
EARLIEST_TIMESTAMP_CACHE_TTL = 24 * 60 * 60
EARLIEST_EVENT_TIMESTAMP = datetime.fromisoformat("1980-01-01T00:00:00Z")
+# Floor for the team-wide unfiltered earliest timestamp: events before 2015 are treated as corrupt.
+UNFILTERED_EARLIEST_TIMESTAMP_FLOOR = datetime.fromisoformat("2015-01-01T00:00:00Z")
def _get_data_warehouse_earliest_timestamp_query(
@@ -257,6 +261,43 @@ def get_earliest_timestamp_from_series(
return min(timestamps)
+def get_earliest_timestamp_unfiltered(team: Team) -> datetime:
+ """
+ Get the team-wide, unfiltered earliest event timestamp (the earliest event of any kind).
+
+ Used for "all time" date filtering when no specific series is given. Mirrors the value of the
+ legacy raw-SQL earliest-timestamp helper: floored at 2015-01-01, falling back to
+ now - DEFAULT_EARLIEST_TIME_DELTA when the team has no events.
+ """
+ cache_key = f"earliest_timestamp_unfiltered_{team.pk}"
+ cached_result = get_safe_cache(cache_key)
+ if cached_result is not None:
+ return _coerce_to_datetime(cached_result, team.timezone_info)
+
+ query = ast.SelectQuery(
+ select=[ast.Field(chain=["timestamp"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.Gt,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value=UNFILTERED_EARLIEST_TIMESTAMP_FLOOR),
+ ),
+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["timestamp"]), order="ASC")],
+ limit=ast.Constant(value=1),
+ )
+
+ with _earliest_timestamp_query_tags():
+ result = execute_hogql_query(query=query, team=team)
+ if result and len(result.results) > 0 and len(result.results[0]) > 0 and result.results[0][0] is not None:
+ earliest_timestamp = _coerce_to_datetime(result.results[0][0], team.timezone_info)
+ # Only cache real results: a team with no events yet should keep re-checking rather than
+ # pinning a "now - delta" fallback for the full TTL.
+ cache.set(cache_key, earliest_timestamp, timeout=EARLIEST_TIMESTAMP_CACHE_TTL)
+ return earliest_timestamp
+
+ return timezone.now() - DEFAULT_EARLIEST_TIME_DELTA
+
+
def _get_week_boundaries(input_date: date, week_start_day: WeekStartDay) -> tuple[date, date]:
"""
Get the start and end dates of the week for a given date, considering the week start day.
diff --git a/posthog/models/event/sql.py b/posthog/models/event/sql.py
index e2d2aac4d41b..e3fbed8e3096 100644
--- a/posthog/models/event/sql.py
+++ b/posthog/models/event/sql.py
@@ -565,22 +565,6 @@ VALUES
)
-SELECT_PROP_VALUES_SQL_WITH_FILTER = """
-SELECT
- DISTINCT {property_field}
-FROM
- events
-WHERE
- team_id = %(team_id)s
- {property_exists_filter}
- {parsed_date_from}
- {parsed_date_to}
- {event_filter}
- {value_filter}
-{order_by_clause}
-LIMIT 10
-"""
-
NULL_SQL = """
-- Creates zero values for all date axis ticks for the given date_from, date_to range
SELECT toUInt16(0) AS total, {date_to_truncated} - {interval_func}(number) AS day_start
diff --git a/posthog/models/filters/test/test_stickiness_filter.py b/posthog/models/filters/test/test_stickiness_filter.py
index e5731b625608..48aa6d66914f 100644
--- a/posthog/models/filters/test/test_stickiness_filter.py
+++ b/posthog/models/filters/test/test_stickiness_filter.py
@@ -1,7 +1,7 @@
from posthog.test.base import BaseTest
from posthog.models.filters.stickiness_filter import StickinessFilter
-from posthog.queries.util import get_earliest_timestamp
+from posthog.models.filters.utils import earliest_timestamp_func
class TestStickinessFilter(BaseTest):
@@ -16,7 +16,7 @@ class TestStickinessFilter(BaseTest):
"sampling_factor": 0.1,
},
team=self.team,
- get_earliest_timestamp=get_earliest_timestamp,
+ get_earliest_timestamp=earliest_timestamp_func,
)
self.assertEqual(
filter.to_dict(),
diff --git a/posthog/models/filters/utils.py b/posthog/models/filters/utils.py
index bb5b77cd600b..3da0db1cbaf9 100644
--- a/posthog/models/filters/utils.py
+++ b/posthog/models/filters/utils.py
@@ -16,9 +16,11 @@ GroupTypeIndex = Literal[0, 1, 2, 3, 4]
def earliest_timestamp_func(team_id: int):
- from posthog.queries.util import get_earliest_timestamp
+ # Imported here to break a circular import: hogql_queries pulls in filter machinery.
+ from posthog.hogql_queries.utils.timestamp_utils import get_earliest_timestamp_unfiltered # noqa: PLC0415
+ from posthog.models.team import Team # noqa: PLC0415
- return get_earliest_timestamp(team_id)
+ return get_earliest_timestamp_unfiltered(Team.objects.get(pk=team_id))
def get_filter(team, data: Optional[dict] = None, request: Optional[Request] = None):
diff --git a/posthog/queries/actor_base_query.py b/posthog/queries/actor_base_query.py
index 9de555769f6d..94c0185e210e 100644
--- a/posthog/queries/actor_base_query.py
+++ b/posthog/queries/actor_base_query.py
@@ -1,6 +1,6 @@
import uuid
-from datetime import datetime, timedelta
-from typing import Any, Literal, Optional, TypedDict, Union, cast
+from datetime import datetime
+from typing import Any, Literal, Optional, TypedDict, Union
from django.db.models import OuterRef, Subquery
from django.db.models.query import Prefetch, QuerySet
@@ -9,21 +9,15 @@ import structlog
from posthog.schema import ActorsQuery
-from posthog.constants import INSIGHT_FUNNELS, INSIGHT_PATHS, INSIGHT_TRENDS
from posthog.hogql_queries.actor_strategies import PersonStrategy
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-from posthog.models import Entity, Filter, PersonDistinctId, Team
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.models.filters.retention_filter import RetentionFilter
-from posthog.models.filters.stickiness_filter import StickinessFilter
+from posthog.models import PersonDistinctId, Team
from posthog.models.group import Group
from posthog.models.person import Person
from posthog.models.person.person import READ_DB_FOR_PERSONS
from posthog.models.person.util import _batched_get_distinct_ids_for_persons, _batched_get_persons_by_uuids
-from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.personhog_client.converters import proto_person_to_model
from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name
-from posthog.queries.insight import insight_sync_execute
logger = structlog.get_logger(__name__)
@@ -65,189 +59,6 @@ class SerializedGroup(CommonActor):
SerializedActor = Union[SerializedGroup, SerializedPerson]
-class ActorBaseQuery:
- # Whether actor values are included as the second column of the actors query
- ACTOR_VALUES_INCLUDED = False
- # What query type to report
- QUERY_TYPE = "actors"
-
- entity: Optional[Entity] = None
-
- def __init__(
- self,
- team: Team,
- filter: Union[Filter, StickinessFilter, RetentionFilter],
- entity: Optional[Entity] = None,
- **kwargs,
- ):
- self._team = team
- self.entity = entity
- self._filter = filter
-
- def actor_query(self, limit_actors: Optional[bool] = True) -> tuple[str, dict]:
- """Implemented by subclasses. Must provide query and params. The query must return list of uuids. Can be group uuids (group_key) or person uuids"""
- raise NotImplementedError()
-
- @cached_property
- def aggregation_group_type_index(self) -> Optional[int]:
- """Override in child class with insight specific logic to determine group aggregation"""
- return None
-
- @property
- def is_aggregating_by_groups(self) -> bool:
- return self.aggregation_group_type_index is not None
-
- def get_actors(
- self,
- ) -> tuple[
- Union[QuerySet[Person], QuerySet[Group], list[Person], list[Group]],
- Union[list[SerializedGroup], list[SerializedPerson]],
- int,
- ]:
- """Get actors in data model and dict formats. Builds query and executes"""
- self._filter.team = self._team
- query, params = self.actor_query()
- raw_result = insight_sync_execute(
- query,
- {**params, **self._filter.hogql_context.values},
- query_type=self.QUERY_TYPE,
- filter=self._filter,
- team_id=self._team.pk,
- )
- actors, serialized_actors = self.get_actors_from_result(raw_result)
-
- if (
- hasattr(self._filter, "include_recordings")
- and self._filter.include_recordings
- and self._filter.insight in [INSIGHT_PATHS, INSIGHT_TRENDS, INSIGHT_FUNNELS]
- ):
- serialized_actors = self.add_matched_recordings_to_serialized_actors(serialized_actors, raw_result)
-
- return actors, serialized_actors, len(raw_result)
-
- def query_for_session_ids_with_recordings(
- self,
- session_ids: set[str],
- date_from: datetime | None,
- date_to: datetime | None,
- ) -> set[str]:
- """Filters a list of session_ids to those that actually have recordings"""
- query = """
- SELECT session_id
- FROM session_replay_events
- WHERE
- team_id = %(team_id)s
- and session_id in %(session_ids)s
- """
-
- # constrain by date range to help limit the work ClickHouse has to do scanning these tables
- # really we should constrain by TTL too
- # but, we're already not doing that, and this adds the benefit without needing too much change
- if date_from:
- query += " AND min_first_timestamp >= %(date_from)s"
-
- if date_to:
- query += " AND max_last_timestamp <= %(date_to)s"
-
- query += " GROUP BY session_id HAVING max(is_deleted) = 0"
-
- params = {
- "team_id": self._team.pk,
- "session_ids": sorted(session_ids), # Sort for stable queries
- # widen the date range a little
- # we don't want to exclude sessions that start or end within a
- # reasonable time of the query date range
- "date_from": date_from - timedelta(days=1) if date_from else None,
- "date_to": date_to + timedelta(days=1) if date_to else None,
- }
- raw_result = insight_sync_execute(
- query,
- params,
- query_type="actors_session_ids_with_recordings",
- filter=self._filter,
- team_id=self._team.pk,
- )
- return {row[0] for row in raw_result}
-
- def add_matched_recordings_to_serialized_actors(
- self,
- serialized_actors: Union[list[SerializedGroup], list[SerializedPerson]],
- raw_result,
- ) -> Union[list[SerializedGroup], list[SerializedPerson]]:
- all_session_ids = set()
-
- session_events_column_index = 2 if self.ACTOR_VALUES_INCLUDED else 1
- for row in raw_result:
- if len(row) > session_events_column_index: # Session events are in the last column
- for event in row[session_events_column_index]:
- if event[2]:
- all_session_ids.add(event[2])
-
- session_ids_with_recordings = self.query_for_session_ids_with_recordings(
- all_session_ids, self._filter.date_from, self._filter.date_to
- )
-
- matched_recordings_by_actor_id: dict[Union[uuid.UUID, str], list[MatchedRecording]] = {}
- for row in raw_result:
- recording_events_by_session_id: dict[str, list[EventInfoForRecording]] = {}
- if len(row) > session_events_column_index - 1:
- for event in row[session_events_column_index]:
- event_session_id = event[2]
- if event_session_id and event_session_id in session_ids_with_recordings:
- recording_events_by_session_id.setdefault(event_session_id, []).append(
- EventInfoForRecording(timestamp=event[0], uuid=event[1], window_id=event[3])
- )
- recordings = [
- MatchedRecording(session_id=session_id, events=events)
- for session_id, events in recording_events_by_session_id.items()
- ]
-
- matched_recordings_by_actor_id[row[0]] = recordings
-
- # Casting Union[SerializedActor, SerializedGroup] as SerializedPerson because mypy yells
- # when you do an indexed assignment on a Union even if all items in the Union support it
- serialized_actors = cast(list[SerializedPerson], serialized_actors)
- serialized_actors_with_recordings = []
- for actor in serialized_actors:
- actor["matched_recordings"] = matched_recordings_by_actor_id[actor["id"]]
- serialized_actors_with_recordings.append(actor)
-
- return serialized_actors_with_recordings
-
- def get_actors_from_result(
- self, raw_result
- ) -> tuple[
- Union[QuerySet[Person], QuerySet[Group], list[Person], list[Group]],
- Union[list[SerializedGroup], list[SerializedPerson]],
- ]:
- actors: Union[QuerySet[Person], QuerySet[Group], list[Person], list[Group]]
- serialized_actors: Union[list[SerializedGroup], list[SerializedPerson]]
-
- actor_ids = [row[0] for row in raw_result]
- value_per_actor_id = {str(row[0]): row[1] for row in raw_result} if self.ACTOR_VALUES_INCLUDED else None
-
- if self.is_aggregating_by_groups:
- actors, serialized_actors = get_groups(
- self._team.pk,
- cast(int, self.aggregation_group_type_index),
- actor_ids,
- value_per_actor_id,
- )
- else:
- with personhog_caller_tag("persons/actor-query"):
- actors, serialized_actors = get_people(self._team, actor_ids, value_per_actor_id)
-
- if self.ACTOR_VALUES_INCLUDED:
- # We fetched actors from Postgres in get_groups/get_people, so `ORDER BY actor_value DESC` no longer holds
- # We need .sort() to restore this order
- serialized_actors.sort(
- key=lambda actor: cast(float, actor["value_at_data_point"]),
- reverse=True,
- )
-
- return actors, serialized_actors
-
-
def get_groups(
team_id: int,
group_type_index: int,
diff --git a/posthog/queries/funnels/__init__.py b/posthog/queries/funnels/__init__.py
index ad3d8a5625b9..e69de29bb2d1 100644
--- a/posthog/queries/funnels/__init__.py
+++ b/posthog/queries/funnels/__init__.py
@@ -1,11 +0,0 @@
-# flake8: noqa
-from .base import ClickhouseFunnelBase
-from .funnel import ClickhouseFunnel
-from .funnel_persons import ClickhouseFunnelActors
-from .funnel_strict import ClickhouseFunnelStrict
-from .funnel_strict_persons import ClickhouseFunnelStrictActors
-from .funnel_time_to_convert import ClickhouseFunnelTimeToConvert
-from .funnel_trends import ClickhouseFunnelTrends
-from .funnel_trends_persons import ClickhouseFunnelTrendsActors
-from .funnel_unordered import ClickhouseFunnelUnordered
-from .funnel_unordered_persons import ClickhouseFunnelUnorderedActors
diff --git a/posthog/queries/funnels/base.py b/posthog/queries/funnels/base.py
deleted file mode 100644
index c8eecf6ac7d7..000000000000
--- a/posthog/queries/funnels/base.py
+++ /dev/null
@@ -1,923 +0,0 @@
-import uuid
-import urllib.parse
-from abc import ABC
-from typing import Any, Optional, Union, cast
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.hogql.database.database import Database
-
-from posthog.clickhouse.materialized_columns import ColumnName
-from posthog.constants import (
- FUNNEL_WINDOW_INTERVAL,
- FUNNEL_WINDOW_INTERVAL_UNIT,
- LIMIT,
- OFFSET,
- TREND_FILTER_TYPE_ACTIONS,
- BreakdownAttributionType,
- FunnelOrderType,
-)
-from posthog.models import Entity, Filter, Team
-from posthog.models.property import PropertyName
-from posthog.models.property.util import (
- box_value,
- get_property_string_expr,
- get_single_or_multi_property_string_expr,
- parse_prop_grouped_clauses,
-)
-from posthog.queries.breakdown_props import (
- format_breakdown_cohort_join_query,
- get_breakdown_cohort_name,
- get_breakdown_prop_values,
-)
-from posthog.queries.funnels.funnel_event_query import FunnelEventQuery
-from posthog.queries.insight import insight_sync_execute
-from posthog.queries.util import alias_poe_mode_for_legacy, correct_result_for_sampling, get_person_properties_mode
-from posthog.utils import generate_short_id, relative_date_parse
-
-from products.actions.backend.models.util import format_action_filter
-
-
-class ClickhouseFunnelBase(ABC):
- QUERY_TYPE = "funnel_base" # should be overridden in subclasses
-
- _filter: Filter
- _team: Team
- _include_timestamp: Optional[bool]
- _include_preceding_timestamp: Optional[bool]
- _extra_event_fields: list[ColumnName]
- _extra_event_properties: list[PropertyName]
- _include_properties: list[str]
-
- def __init__(
- self,
- filter: Filter,
- team: Team,
- include_timestamp: Optional[bool] = None,
- include_preceding_timestamp: Optional[bool] = None,
- base_uri: str = "/",
- include_properties: Optional[list[str]] = None,
- ) -> None:
- self._filter = filter
- self._team = team
- self._base_uri = base_uri
- self.params = {
- "team_id": self._team.pk,
- "timezone": self._team.timezone,
- "events": [], # purely a speed optimization, don't need this for filtering
- }
- self._include_timestamp = include_timestamp
- self._include_preceding_timestamp = include_preceding_timestamp
- self._include_properties = include_properties or []
-
- # HACK: Because we're in a legacy query, we need to override hogql_context with the legacy-alised PoE mode
- self._filter.hogql_context.modifiers.personsOnEventsMode = alias_poe_mode_for_legacy(team.person_on_events_mode)
-
- # Recreate the database with the legacy-alised PoE mode
- self._filter.hogql_context.database = Database.create_for(
- team=self._team, modifiers=self._filter.hogql_context.modifiers
- )
-
- # handle default if window isn't provided
- if not self._filter.funnel_window_days and not self._filter.funnel_window_interval:
- self._filter = self._filter.shallow_clone({FUNNEL_WINDOW_INTERVAL: 14, FUNNEL_WINDOW_INTERVAL_UNIT: "day"})
-
- if self._filter.funnel_window_days:
- self._filter = self._filter.shallow_clone(
- {
- FUNNEL_WINDOW_INTERVAL: self._filter.funnel_window_days,
- FUNNEL_WINDOW_INTERVAL_UNIT: "day",
- }
- )
-
- if not self._filter.limit:
- new_limit = {LIMIT: 100}
- self._filter = self._filter.shallow_clone(new_limit)
- self.params.update(new_limit)
- else:
- self.params.update({LIMIT: self._filter.limit})
-
- self.params.update({OFFSET: self._filter.offset})
-
- self._extra_event_fields: list[ColumnName] = []
- self._extra_event_properties: list[PropertyName] = []
- if self._filter.include_recordings:
- self._extra_event_fields = ["uuid"]
- self._extra_event_properties = ["$session_id", "$window_id"]
-
- self._update_filters()
-
- def run(self, *args, **kwargs):
- if len(self._filter.entities) == 0:
- return []
-
- results = self._exec_query()
- return self._format_results(results)
-
- def _serialize_step(
- self,
- step: Entity,
- count: int,
- people: Optional[list[uuid.UUID]] = None,
- sampling_factor: Optional[float] = None,
- ) -> dict[str, Any]:
- if step.type == TREND_FILTER_TYPE_ACTIONS:
- name = step.get_action(self._team.pk).name
- else:
- name = str(step.id) if step.id is not None else None
-
- return {
- "action_id": step.id,
- "name": name,
- "custom_name": step.custom_name,
- "order": step.index,
- "people": people if people else [],
- "count": correct_result_for_sampling(count, sampling_factor),
- "type": step.type,
- }
-
- @property
- def extra_event_fields_and_properties(self):
- return self._extra_event_fields + self._extra_event_properties
-
- def _update_filters(self):
- # format default dates
- data: dict[str, Any] = {}
- if not self._filter._date_from:
- data.update({"date_from": relative_date_parse("-7d", self._team.timezone_info)})
-
- if self._filter.breakdown and not self._filter.breakdown_type:
- data.update({"breakdown_type": "event"})
-
- # the API accepts either:
- # a string (single breakdown) in parameter "breakdown"
- # a list of numbers (one or more cohorts) in parameter "breakdown"
- # a list of strings (multiple breakdown) in parameter "breakdowns"
- # if the breakdown is a string, box it as a list to reduce paths through the code
- #
- # The code below ensures that breakdown is always an array
- # without it affecting the multiple areas of the code outside of funnels that use breakdown
- #
- # Once multi property breakdown is implemented in Trends this becomes unnecessary
-
- if isinstance(self._filter.breakdowns, list) and self._filter.breakdown_type in [
- "person",
- "event",
- "hogql",
- None,
- ]:
- data.update({"breakdown": [b.get("property") for b in self._filter.breakdowns]})
-
- if isinstance(self._filter.breakdown, str) and self._filter.breakdown_type in [
- "person",
- "event",
- "hogql",
- None,
- ]:
- boxed_breakdown: list[Union[str, int]] = box_value(self._filter.breakdown)
- data.update({"breakdown": boxed_breakdown})
-
- for exclusion in self._filter.exclusions:
- if exclusion.funnel_from_step is None or exclusion.funnel_to_step is None:
- raise ValidationError("Exclusion event needs to define funnel steps")
-
- if exclusion.funnel_from_step >= exclusion.funnel_to_step:
- raise ValidationError("Exclusion event range is invalid. End of range should be greater than start.")
-
- if exclusion.funnel_from_step >= len(self._filter.entities) - 1:
- raise ValidationError(
- "Exclusion event range is invalid. Start of range is greater than number of steps."
- )
-
- if exclusion.funnel_to_step > len(self._filter.entities) - 1:
- raise ValidationError("Exclusion event range is invalid. End of range is greater than number of steps.")
-
- for entity in self._filter.entities[exclusion.funnel_from_step : exclusion.funnel_to_step + 1]:
- if entity.equals(exclusion) or exclusion.is_superset(entity):
- raise ValidationError("Exclusion steps cannot contain an event that's part of funnel steps.")
-
- self._filter = self._filter.shallow_clone(data)
-
- def _format_single_funnel(self, results, with_breakdown=False):
- # Format of this is [step order, person count (that reached that step), array of person uuids]
- steps = []
- total_people = 0
-
- num_entities = len(self._filter.entities)
- breakdown_value = results[-1]
-
- cache_invalidation_key = generate_short_id()
-
- for step in reversed(self._filter.entities):
- if results and len(results) > 0:
- total_people += results[step.index]
-
- serialized_result = self._serialize_step(
- step, total_people, [], self._filter.sampling_factor
- ) # persons not needed on initial return
- if cast(int, step.index) > 0:
- serialized_result.update(
- {
- "average_conversion_time": results[cast(int, step.index) + num_entities - 1],
- "median_conversion_time": results[cast(int, step.index) + num_entities * 2 - 2],
- }
- )
- else:
- serialized_result.update({"average_conversion_time": None, "median_conversion_time": None})
-
- # Construct converted and dropped people URLs
- funnel_step = step.index + 1
- converted_people_filter = self._filter.shallow_clone({"funnel_step": funnel_step})
- dropped_people_filter = self._filter.shallow_clone({"funnel_step": -funnel_step})
-
- if with_breakdown:
- # breakdown will return a display ready value
- # breakdown_value will return the underlying id if different from display ready value (ex: cohort id)
- serialized_result.update(
- {
- "breakdown": (
- get_breakdown_cohort_name(breakdown_value, self._team)
- if self._filter.breakdown_type == "cohort"
- else breakdown_value
- ),
- "breakdown_value": breakdown_value,
- }
- )
- # important to not try and modify this value any how - as these
- # are keys for fetching persons
-
- # Add in the breakdown to people urls as well
- converted_people_filter = converted_people_filter.shallow_clone(
- {"funnel_step_breakdown": breakdown_value}
- )
- dropped_people_filter = dropped_people_filter.shallow_clone({"funnel_step_breakdown": breakdown_value})
-
- serialized_result.update(
- {
- "converted_people_url": f"{self._base_uri}api/person/funnel/?{urllib.parse.urlencode(converted_people_filter.to_params())}&cache_invalidation_key={cache_invalidation_key}",
- "dropped_people_url": (
- f"{self._base_uri}api/person/funnel/?{urllib.parse.urlencode(dropped_people_filter.to_params())}&cache_invalidation_key={cache_invalidation_key}"
- # NOTE: If we are looking at the first step, there is no drop off,
- # everyone converted, otherwise they would not have been
- # included in the funnel.
- if step.index > 0
- else None
- ),
- }
- )
-
- steps.append(serialized_result)
-
- return steps[::-1] # reverse
-
- def _format_results(self, results):
- if not results or len(results) == 0:
- return []
-
- if self._filter.breakdown:
- return [self._format_single_funnel(res, with_breakdown=True) for res in results]
- else:
- return self._format_single_funnel(results[0])
-
- def _exec_query(self) -> list[tuple]:
- self._filter.team = self._team
- query = self.get_query()
- return insight_sync_execute(
- query,
- {**self.params, **self._filter.hogql_context.values},
- query_type=self.QUERY_TYPE,
- filter=self._filter,
- team_id=self._team.pk,
- )
-
- def _get_timestamp_outer_select(self) -> str:
- if self._include_preceding_timestamp:
- return ", max_timestamp, min_timestamp"
- elif self._include_timestamp:
- return ", timestamp"
- else:
- return ""
-
- def _get_timestamp_selects(self) -> tuple[str, str]:
- """
- Returns timestamp selectors for the target step and optionally the preceding step.
- In the former case, always returns the timestamp for the first and last step as well.
- """
- target_step = self._filter.funnel_step
- final_step = len(self._filter.entities) - 1
- first_step = 0
-
- if not target_step:
- return "", ""
-
- if target_step < 0:
- # the first valid dropoff argument for funnel_step is -2
- # -2 refers to persons who performed the first step but never made it to the second
- if target_step == -1:
- raise ValueError("To request dropoff of initial step use -2")
-
- target_step = abs(target_step) - 2
- else:
- target_step -= 1
-
- if self._include_preceding_timestamp:
- if target_step == 0:
- raise ValueError("Cannot request preceding step timestamp if target funnel step is the first step")
-
- return (
- f", latest_{target_step}, latest_{target_step - 1}",
- f", argMax(latest_{target_step}, steps) as max_timestamp, argMax(latest_{target_step - 1}, steps) as min_timestamp",
- )
- elif self._include_timestamp:
- return (
- f", latest_{target_step}, latest_{final_step}, latest_{first_step}",
- f", argMax(latest_{target_step}, steps) as timestamp, argMax(latest_{final_step}, steps) as final_timestamp, argMax(latest_{first_step}, steps) as first_timestamp",
- )
- else:
- return "", ""
-
- def _get_step_times(self, max_steps: int):
- conditions: list[str] = []
- for i in range(1, max_steps):
- conditions.append(
- f"if(isNotNull(latest_{i}) AND latest_{i} <= latest_{i - 1} + INTERVAL {self._filter.funnel_window_interval} {self._filter.funnel_window_interval_unit_ch()}, "
- f"dateDiff('second', toDateTime(latest_{i - 1}), toDateTime(latest_{i})), NULL) step_{i}_conversion_time"
- )
-
- formatted = ", ".join(conditions)
- return f", {formatted}" if formatted else ""
-
- def _get_partition_cols(self, level_index: int, max_steps: int):
- cols: list[str] = []
- for i in range(0, max_steps):
- cols.append(f"step_{i}")
- if i < level_index:
- cols.append(f"latest_{i}")
- for field in self.extra_event_fields_and_properties:
- cols.append(f'"{field}_{i}"')
- for exclusion_id, exclusion in enumerate(self._filter.exclusions):
- if cast(int, exclusion.funnel_from_step) + 1 == i:
- cols.append(f"exclusion_{exclusion_id}_latest_{exclusion.funnel_from_step}")
- else:
- duplicate_event = 0
- if i > 0 and (
- self._filter.entities[i].equals(self._filter.entities[i - 1])
- or self._filter.entities[i].is_superset(self._filter.entities[i - 1])
- ):
- duplicate_event = 1
- cols.append(
- f"min(latest_{i}) over (PARTITION by aggregation_target {self._get_breakdown_prop()} ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND {duplicate_event} PRECEDING) latest_{i}"
- )
-
- for field in self.extra_event_fields_and_properties:
- cols.append(
- f'last_value("{field}_{i}") over (PARTITION by aggregation_target {self._get_breakdown_prop()} ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND {duplicate_event} PRECEDING) "{field}_{i}"'
- )
-
- for exclusion_id, exclusion in enumerate(self._filter.exclusions):
- # exclusion starting at step i follows semantics of step i+1 in the query (since we're looking for exclusions after step i)
- if cast(int, exclusion.funnel_from_step) + 1 == i:
- cols.append(
- f"min(exclusion_{exclusion_id}_latest_{exclusion.funnel_from_step}) over (PARTITION by aggregation_target {self._get_breakdown_prop()} ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) exclusion_{exclusion_id}_latest_{exclusion.funnel_from_step}"
- )
- return ", ".join(cols)
-
- def _get_exclusion_condition(self):
- if not self._filter.exclusions:
- return ""
-
- conditions = []
- for exclusion_id, exclusion in enumerate(self._filter.exclusions):
- from_time = f"latest_{exclusion.funnel_from_step}"
- to_time = f"latest_{exclusion.funnel_to_step}"
- exclusion_time = f"exclusion_{exclusion_id}_latest_{exclusion.funnel_from_step}"
- condition = (
- f"if( {exclusion_time} > {from_time} AND {exclusion_time} < "
- f"if(isNull({to_time}), {from_time} + INTERVAL {self._filter.funnel_window_interval} {self._filter.funnel_window_interval_unit_ch()}, {to_time}), 1, 0)"
- )
- conditions.append(condition)
-
- if conditions:
- return f", arraySum([{','.join(conditions)}]) as exclusion"
- else:
- return ""
-
- def _get_sorting_condition(self, curr_index: int, max_steps: int):
- if curr_index == 1:
- return "1"
-
- conditions: list[str] = []
- for i in range(1, curr_index):
- duplicate_event = (
- True
- if (
- self._filter.entities[i].equals(self._filter.entities[i - 1])
- or self._filter.entities[i].is_superset(self._filter.entities[i - 1])
- )
- else False
- )
-
- conditions.append(f"latest_{i - 1} {'<' if duplicate_event else '<='} latest_{i}")
- conditions.append(
- f"latest_{i} <= latest_0 + INTERVAL {self._filter.funnel_window_interval} {self._filter.funnel_window_interval_unit_ch()}"
- )
-
- return f"if({' AND '.join(conditions)}, {curr_index}, {self._get_sorting_condition(curr_index - 1, max_steps)})"
-
- def _get_inner_event_query(
- self,
- entities=None,
- entity_name="events",
- skip_entity_filter=False,
- skip_step_filter=False,
- ) -> str:
- entities_to_use = entities or self._filter.entities
-
- extra_fields = []
-
- for prop in self._include_properties:
- extra_fields.append(prop)
-
- funnel_events_query, params = FunnelEventQuery(
- filter=self._filter,
- team=self._team,
- extra_fields=[*self._extra_event_fields, *extra_fields],
- extra_event_properties=self._extra_event_properties,
- person_on_events_mode=alias_poe_mode_for_legacy(self._team.person_on_events_mode),
- ).get_query(entities_to_use, entity_name, skip_entity_filter=skip_entity_filter)
-
- self.params.update(params)
-
- if skip_step_filter:
- steps_conditions = "1=1"
- else:
- steps_conditions = self._get_steps_conditions(length=len(entities_to_use))
-
- all_step_cols: list[str] = []
- for index, entity in enumerate(entities_to_use):
- step_cols = self._get_step_col(entity, index, entity_name)
- all_step_cols.extend(step_cols)
-
- for exclusion_id, entity in enumerate(self._filter.exclusions):
- if entity.funnel_from_step is None:
- continue
- step_cols = self._get_step_col(
- entity,
- entity.funnel_from_step,
- entity_name,
- f"exclusion_{exclusion_id}_",
- )
- # every exclusion entity has the form: exclusion_<id>_step_i & timestamp exclusion_<id>_latest_i
- # where i is the starting step for exclusion on that entity
- all_step_cols.extend(step_cols)
-
- breakdown_select_prop, breakdown_select_prop_params = self._get_breakdown_select_prop()
- self.params.update(breakdown_select_prop_params)
-
- if breakdown_select_prop:
- all_step_cols.append(breakdown_select_prop)
-
- extra_join = ""
-
- if self._filter.breakdown:
- if self._filter.breakdown_type == "cohort":
- extra_join = self._get_cohort_breakdown_join()
- else:
- values = self._get_breakdown_conditions()
- self.params.update({"breakdown_values": values})
-
- extra_select_fields = f", {', '.join(all_step_cols)}" if all_step_cols else ""
-
- funnel_events_query = funnel_events_query.format(
- extra_select_fields=extra_select_fields,
- extra_join=extra_join,
- step_filter="AND ({})".format(steps_conditions),
- )
-
- if self._filter.breakdown and self._filter.breakdown_attribution_type != BreakdownAttributionType.ALL_EVENTS:
- # ALL_EVENTS attribution is the old default, which doesn't need the subquery
- return self._add_breakdown_attribution_subquery(funnel_events_query)
-
- return funnel_events_query
-
- def _add_breakdown_attribution_subquery(self, inner_query: str) -> str:
- if self._filter.breakdown_attribution_type in [
- BreakdownAttributionType.FIRST_TOUCH,
- BreakdownAttributionType.LAST_TOUCH,
- ]:
- # When breaking down by first/last touch, each person can only have one prop value
- # so just select that. Except for the empty case, where select the default
-
- if self._query_has_array_breakdown():
- default_breakdown_value = f"""[{",".join(["''" for _ in range(len(self._filter.breakdown or []))])}]"""
- # default is [''] when dealing with a single breakdown array, otherwise ['', '', ...., '']
- breakdown_selector = (
- f"if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, {default_breakdown_value})"
- )
- else:
- breakdown_selector = "prop_vals"
-
- return f"""
- SELECT *, {breakdown_selector} as prop
- FROM ({inner_query})
- """
-
- # When breaking down by specific step, each person can have multiple prop values
- # so array join those to each event
- return f"""
- SELECT *, prop
- FROM ({inner_query})
- ARRAY JOIN prop_vals as prop
- {"WHERE prop != []" if self._query_has_array_breakdown() else ""}
- """
-
- def _get_steps_conditions(self, length: int) -> str:
- step_conditions: list[str] = []
-
- for index in range(length):
- step_conditions.append(f"step_{index} = 1")
-
- for exclusion_id, entity in enumerate(self._filter.exclusions):
- step_conditions.append(f"exclusion_{exclusion_id}_step_{entity.funnel_from_step} = 1")
-
- return " OR ".join(step_conditions)
-
- def _get_step_col(self, entity: Entity, index: int, entity_name: str, step_prefix: str = "") -> list[str]:
- # step prefix is used to distinguish actual steps, and exclusion steps
- # without the prefix, we get the same parameter binding for both, which borks things up
- step_cols: list[str] = []
- condition = self._build_step_query(entity, index, entity_name, step_prefix)
- step_cols.append(f"if({condition}, 1, 0) as {step_prefix}step_{index}")
- step_cols.append(f"if({step_prefix}step_{index} = 1, timestamp, null) as {step_prefix}latest_{index}")
-
- for field in self.extra_event_fields_and_properties:
- step_cols.append(f'if({step_prefix}step_{index} = 1, "{field}", null) as "{step_prefix}{field}_{index}"')
-
- return step_cols
-
- def _build_step_query(self, entity: Entity, index: int, entity_name: str, step_prefix: str) -> str:
- filters = self._build_filters(entity, index, entity_name)
- if entity.type == TREND_FILTER_TYPE_ACTIONS:
- action = entity.get_action(self._team.pk)
- for action_step_event in action.get_step_events():
- if entity_name not in self.params[entity_name]:
- self.params[entity_name].append(action_step_event)
-
- action_query, action_params = format_action_filter(
- team_id=self._team.pk,
- action=action,
- prepend=f"{entity_name}_{step_prefix}step_{index}",
- person_properties_mode=get_person_properties_mode(self._team),
- person_id_joined_alias="person_id",
- hogql_context=self._filter.hogql_context,
- )
- if action_query == "":
- return ""
-
- self.params.update(action_params)
- content_sql = "{actions_query} {filters}".format(actions_query=action_query, filters=filters)
- elif entity.id is None:
- content_sql = f"1 = 1 {filters}"
- else:
- if entity_name not in self.params:
- self.params[entity_name] = []
- if entity.id not in self.params[entity_name]:
- self.params[entity_name].append(entity.id)
- event_param_key = f"{entity_name}_{step_prefix}event_{index}"
- self.params[event_param_key] = entity.id
- content_sql = f"event = %({event_param_key})s {filters}"
- return content_sql
-
- def _build_filters(self, entity: Entity, index: int, entity_name: str) -> str:
- prop_filters, prop_filter_params = parse_prop_grouped_clauses(
- team_id=self._team.pk,
- property_group=entity.property_groups,
- prepend=f"_{entity_name}_{index}",
- person_properties_mode=get_person_properties_mode(self._team),
- person_id_joined_alias="person_id",
- hogql_context=self._filter.hogql_context,
- )
- self.params.update(prop_filter_params)
- return prop_filters
-
- def _get_funnel_person_step_condition(self):
- step_num = self._filter.funnel_step
- custom_steps = self._filter.funnel_custom_steps
- max_steps = len(self._filter.entities)
-
- conditions = []
-
- if custom_steps:
- self.params.update({"custom_step_num": custom_steps})
- conditions.append("steps IN %(custom_step_num)s")
- elif step_num is not None:
- if step_num >= 0:
- self.params.update({"step_num": list(range(step_num, max_steps + 1))})
- conditions.append("steps IN %(step_num)s")
- else:
- self.params.update({"step_num": abs(step_num) - 1})
- conditions.append("steps = %(step_num)s")
- else:
- raise ValueError("Missing both funnel_step and funnel_custom_steps")
-
- if self._filter.funnel_step_breakdown is not None:
- breakdown_prop_value = self._filter.funnel_step_breakdown
- if isinstance(breakdown_prop_value, int) and self._filter.breakdown_type != "cohort":
- breakdown_prop_value = str(breakdown_prop_value)
-
- self.params.update({"breakdown_prop_value": breakdown_prop_value})
- conditions.append("arrayFlatten(array(prop)) = arrayFlatten(array(%(breakdown_prop_value)s))")
-
- return " AND ".join(conditions)
-
- def _get_funnel_person_step_events(self):
- if self._filter.include_recordings:
- step_num = self._filter.funnel_step
- if self._filter.include_final_matching_events:
- # Always returns the user's final step of the funnel
- return ", final_matching_events as matching_events"
- elif step_num is None:
- raise ValueError("Missing funnel_step filter property")
- if step_num >= 0:
- # None drop off case
- self.params.update({"matching_events_step_num": step_num - 1})
- else:
- # Drop off case if negative number
- self.params.update({"matching_events_step_num": abs(step_num) - 2})
- return ", step_%(matching_events_step_num)s_matching_events as matching_events"
- return ""
-
- def _get_count_columns(self, max_steps: int):
- cols: list[str] = []
-
- for i in range(max_steps):
- cols.append(f"countIf(steps = {i + 1}) step_{i + 1}")
-
- return ", ".join(cols)
-
- def _get_step_time_names(self, max_steps: int):
- names = []
- for i in range(1, max_steps):
- names.append(f"step_{i}_conversion_time")
-
- formatted = ",".join(names)
- return f", {formatted}" if formatted else ""
-
- def _get_final_matching_event(self, max_steps: int):
- statement = None
- for i in range(max_steps - 1, -1, -1):
- if i == max_steps - 1:
- statement = f"if(isNull(latest_{i}),step_{i - 1}_matching_event,step_{i}_matching_event)"
- elif i == 0:
- statement = f"if(isNull(latest_0),(null,null,null,null),{statement})"
- else:
- statement = f"if(isNull(latest_{i}),step_{i - 1}_matching_event,{statement})"
- return f",{statement} as final_matching_event" if statement else ""
-
- def _get_matching_events(self, max_steps: int):
- if self._filter.include_recordings:
- events = []
- for i in range(0, max_steps):
- event_fields = ["latest", *self.extra_event_fields_and_properties]
- event_fields_with_step = ", ".join([f'"{field}_{i}"' for field in event_fields])
- event_clause = f"({event_fields_with_step}) as step_{i}_matching_event"
- events.append(event_clause)
- matching_event_select_statements = "," + ", ".join(events)
-
- final_matching_event_statement = self._get_final_matching_event(max_steps)
-
- return matching_event_select_statements + final_matching_event_statement
-
- return ""
-
- def _get_step_time_avgs(self, max_steps: int, inner_query: bool = False):
- conditions: list[str] = []
- for i in range(1, max_steps):
- conditions.append(
- f"avg(step_{i}_conversion_time) step_{i}_average_conversion_time_inner"
- if inner_query
- else f"avg(step_{i}_average_conversion_time_inner) step_{i}_average_conversion_time"
- )
-
- formatted = ", ".join(conditions)
- return f", {formatted}" if formatted else ""
-
- def _get_step_time_median(self, max_steps: int, inner_query: bool = False):
- conditions: list[str] = []
- for i in range(1, max_steps):
- conditions.append(
- f"median(step_{i}_conversion_time) step_{i}_median_conversion_time_inner"
- if inner_query
- else f"median(step_{i}_median_conversion_time_inner) step_{i}_median_conversion_time"
- )
-
- formatted = ", ".join(conditions)
- return f", {formatted}" if formatted else ""
-
- def _get_matching_event_arrays(self, max_steps: int):
- select_clause = ""
- if self._filter.include_recordings:
- for i in range(0, max_steps):
- select_clause += f", groupArray(10)(step_{i}_matching_event) as step_{i}_matching_events"
- select_clause += f", groupArray(10)(final_matching_event) as final_matching_events"
- return select_clause
-
- @staticmethod
- def _order_by(max_steps: int):
- return "ORDER BY " + ",".join([f"step_{i + 1} DESC" for i in reversed(range(max_steps))])
-
- def _get_limit(self):
- if self._filter.limit:
- return f"LIMIT {self._filter.limit}"
- # TODO figure out some good default limit
- return "LIMIT 1000"
-
- def get_query(self) -> str:
- raise NotImplementedError()
-
- def get_step_counts_query(self) -> str:
- raise NotImplementedError()
-
- def get_step_counts_without_aggregation_query(self) -> str:
- raise NotImplementedError()
-
- def _get_breakdown_select_prop(self) -> tuple[str, dict[str, Any]]:
- basic_prop_selector = ""
- basic_prop_params: dict[str, Any] = {}
- if not self._filter.breakdown:
- return basic_prop_selector, basic_prop_params
-
- self.params.update({"breakdown": self._filter.breakdown})
- if self._filter.breakdown_type == "person":
- if alias_poe_mode_for_legacy(self._team.person_on_events_mode) != PersonsOnEventsMode.DISABLED:
- basic_prop_selector, basic_prop_params = get_single_or_multi_property_string_expr(
- self._filter.breakdown,
- table="events",
- query_alias="prop_basic",
- column="person_properties",
- allow_denormalized_props=True,
- materialised_table_column="person_properties",
- )
- else:
- basic_prop_selector, basic_prop_params = get_single_or_multi_property_string_expr(
- self._filter.breakdown,
- table="person",
- query_alias="prop_basic",
- column="person_props",
- )
- elif self._filter.breakdown_type == "event":
- basic_prop_selector, basic_prop_params = get_single_or_multi_property_string_expr(
- self._filter.breakdown,
- table="events",
- query_alias="prop_basic",
- column="properties",
- normalize_url=self._filter.breakdown_normalize_url,
- )
- elif self._filter.breakdown_type == "cohort":
- basic_prop_selector = "value AS prop_basic"
- elif self._filter.breakdown_type == "group":
- # :TRICKY: We only support string breakdown for group properties
- assert isinstance(self._filter.breakdown, str)
-
- properties_field = f"group_properties_{self._filter.breakdown_group_type_index}"
- expression, _ = get_property_string_expr(
- table="groups",
- property_name=self._filter.breakdown,
- var="%(breakdown)s",
- column=properties_field,
- )
- basic_prop_selector = f"{expression} AS prop_basic"
- elif self._filter.breakdown_type == "hogql":
- from posthog.hogql.hogql import translate_hogql
-
- breakdown = self._filter.breakdown
- if isinstance(breakdown, list):
- expressions = [translate_hogql(str(exp), self._filter.hogql_context) for exp in breakdown]
- expression = f"array({','.join(expressions)})"
- else:
- expression = translate_hogql(cast(str, breakdown), self._filter.hogql_context)
- basic_prop_selector = f"{expression} AS prop_basic"
-
- # TODO: simplify once array and string breakdowns are sorted
- if self._filter.breakdown_attribution_type == BreakdownAttributionType.STEP:
- select_columns = []
- prop_aliases = []
- default_breakdown_selector = "[]" if self._query_has_array_breakdown() else "NULL"
- # get prop value from each step
- for index, _ in enumerate(self._filter.entities):
- prop_alias = f"prop_{index}"
- select_columns.append(f"if(step_{index} = 1, prop_basic, {default_breakdown_selector}) as {prop_alias}")
- prop_aliases.append(prop_alias)
- final_select = f"prop_{self._filter.breakdown_attribution_value} as prop_final"
-
- prop_window = "groupUniqArray(prop_final) over (PARTITION by aggregation_target) as prop_vals"
-
- return ",".join([basic_prop_selector, *select_columns, final_select, prop_window]), basic_prop_params
- elif self._filter.breakdown_attribution_type in [
- BreakdownAttributionType.FIRST_TOUCH,
- BreakdownAttributionType.LAST_TOUCH,
- ]:
- attribution_prop_alias = "prop_attribution"
- prop_conditional = (
- f"notEmpty(arrayFilter(x -> notEmpty(x), {attribution_prop_alias}))"
- if self._query_has_array_breakdown()
- else f"isNotNull({attribution_prop_alias})"
- )
-
- aggregate_operation = (
- "argMinIf"
- if self._filter.breakdown_attribution_type == BreakdownAttributionType.FIRST_TOUCH
- else "argMaxIf"
- )
-
- breakdown_window_selector = (
- f"{aggregate_operation}({attribution_prop_alias}, timestamp, {prop_conditional})"
- )
- prop_window = f"{breakdown_window_selector} over (PARTITION by aggregation_target) as prop_vals"
- return ",".join(
- [basic_prop_selector, f"prop_basic as {attribution_prop_alias}", prop_window]
- ), basic_prop_params
- else:
- # ALL_EVENTS
- return ",".join([basic_prop_selector, "prop_basic as prop"]), basic_prop_params
-
- def _get_cohort_breakdown_join(self) -> str:
- cohort_queries, ids, cohort_params = format_breakdown_cohort_join_query(self._team, self._filter)
- self.params.update({"breakdown_values": ids})
- self.params.update(cohort_params)
- return f"""
- INNER JOIN (
- {cohort_queries}
- ) cohort_join
- ON events.distinct_id = cohort_join.distinct_id
- """
-
- def _get_breakdown_conditions(self) -> Optional[list[str]]:
- """
- For people, pagination sets the offset param, which is common across filters
- and gives us the wrong breakdown values here, so we override it.
- For events, depending on the attribution type, we either look at only one entity,
- or all of them in the funnel.
- if this is a multi property breakdown then the breakdown values are misleading
- e.g. [Chrome, Safari], [95, 15] doesn't make clear that Chrome 15 isn't valid but Safari 15 is
- so the generated list here must be [[Chrome, 95], [Safari, 15]]
- """
- if self._filter.breakdown:
- use_all_funnel_entities = (
- self._filter.breakdown_attribution_type
- in [
- BreakdownAttributionType.FIRST_TOUCH,
- BreakdownAttributionType.LAST_TOUCH,
- ]
- or self._filter.funnel_order_type == FunnelOrderType.UNORDERED
- )
- first_entity = self._filter.entities[0]
-
- target_entity = first_entity
- if (
- self._filter.breakdown_attribution_value is not None
- and self._filter.breakdown_attribution_type == BreakdownAttributionType.STEP
- ):
- target_entity = self._filter.entities[self._filter.breakdown_attribution_value]
-
- values, has_more_values = get_breakdown_prop_values(
- self._filter,
- target_entity,
- "count(*)",
- self._team,
- extra_params={"offset": 0},
- use_all_funnel_entities=use_all_funnel_entities,
- person_properties_mode=get_person_properties_mode(self._team),
- )
- return values
-
- return None
-
- def _get_breakdown_prop(self, group_remaining=False) -> str:
- if self._filter.breakdown:
- other_aggregation = "['Other']" if self._query_has_array_breakdown() else "'Other'"
- if group_remaining and self._filter.breakdown_type in [
- "person",
- "event",
- "group",
- ]:
- return f", if(has(%(breakdown_values)s, prop), prop, {other_aggregation}) as prop"
- else:
- # Cohorts don't have "Other" aggregation
- return ", prop"
- else:
- return ""
-
- def _get_person_and_group_properties(self, aggregate: bool = False) -> str:
- fields = []
-
- for prop in self._include_properties:
- fields.append(f"any({prop}) as {prop}" if aggregate else prop)
-
- parsed_fields = f", {', '.join(fields)}" if fields else ""
- return parsed_fields
-
- def _query_has_array_breakdown(self) -> bool:
- return not isinstance(self._filter.breakdown, str) and self._filter.breakdown_type != "cohort"
diff --git a/posthog/queries/funnels/funnel.py b/posthog/queries/funnels/funnel.py
deleted file mode 100644
index 0f42a527fbb1..000000000000
--- a/posthog/queries/funnels/funnel.py
+++ /dev/null
@@ -1,142 +0,0 @@
-from typing import cast
-
-from posthog.queries.funnels.base import ClickhouseFunnelBase
-
-
-class ClickhouseFunnel(ClickhouseFunnelBase):
- """
- A basic ordered funnel.
-
- ## Query Intuition
- We start with all events of interest (coming from the `FunnelEventQuery`). The query runs in different levels: at each
- level, we first get the minimum timestamp of every event following the previous event. Then, we trickle up the levels, till we get to the top level,
- which implies all events are sorted in increasing order.
- Each level is a subquery.
-
- ## Exclusion Intuition
- Event exclusion between steps means that if this specific event happened between two funnel steps, we disqualify the user, not showing them in the results.
- To include event exclusions inside the funnel, the critical insight is that the exclusion is just like a parallel step to the funnel step that happens after
- the exclusion start step.
- For example, if we have a funnel with steps [1, 2, 3, 4] and we want to exclude events between step 2 and step 4, then the exclusion step semantics are just
- like step 3 semantics. We want to find this event after step 2.
- Since it's a parallel step, we don't need to add an extra level, we can reuse the existing levels.
- See `get_comparison_cols` and `_get_partition_cols` for how this works.
-
- Exclusion doesn't support duplicates like: steps [event 1, event 2], and excluding event 1 between steps 1 and 2.
-
- """
-
- QUERY_TYPE = "funnel"
-
- def get_query(self):
- max_steps = len(self._filter.entities)
-
- breakdown_clause = self._get_breakdown_prop()
- return f"""
- SELECT {self._get_count_columns(max_steps)} {self._get_step_time_avgs(max_steps)} {self._get_step_time_median(max_steps)} {breakdown_clause} FROM (
- {self.get_step_counts_query()}
- ) {"GROUP BY prop" if breakdown_clause != "" else ""}
- {self._order_by(max_steps) if breakdown_clause != "" else ""}
- {self._get_limit() if breakdown_clause != "" else ""}
- """
-
- def get_step_counts_query(self):
- steps_per_person_query = self.get_step_counts_without_aggregation_query()
- max_steps = len(self._filter.entities)
- breakdown_clause = self._get_breakdown_prop()
- inner_timestamps, outer_timestamps = self._get_timestamp_selects()
-
- return f"""
- SELECT aggregation_target, steps {self._get_step_time_avgs(max_steps, inner_query=True)} {self._get_step_time_median(max_steps, inner_query=True)} {self._get_matching_event_arrays(max_steps)} {breakdown_clause} {outer_timestamps} {self._get_person_and_group_properties(aggregate=True)} FROM (
- SELECT aggregation_target, steps, max(steps) over (PARTITION BY aggregation_target {breakdown_clause}) as max_steps {self._get_step_time_names(max_steps)} {self._get_matching_events(max_steps)} {breakdown_clause} {inner_timestamps} {self._get_person_and_group_properties()} FROM (
- {steps_per_person_query}
- )
- ) GROUP BY aggregation_target, steps {breakdown_clause}
- HAVING steps = max(max_steps)
- """
-
- def get_step_counts_without_aggregation_query(self):
- formatted_query = ""
- max_steps = len(self._filter.entities)
- if max_steps >= 2:
- formatted_query = self.build_step_subquery(2, max_steps)
- breakdown_query = self._get_breakdown_prop()
- else:
- formatted_query = self._get_inner_event_query()
- breakdown_query = self._get_breakdown_prop(group_remaining=True)
-
- exclusion_clause = self._get_exclusion_condition()
-
- return f"""
- SELECT *, {self._get_sorting_condition(max_steps, max_steps)} AS steps {exclusion_clause} {self._get_step_times(max_steps)}{self._get_matching_events(max_steps)} {breakdown_query} {self._get_person_and_group_properties()} FROM (
- {formatted_query}
- ) WHERE step_0 = 1
- {"AND exclusion = 0" if exclusion_clause else ""}
- """
-
- def _get_comparison_at_step(self, index: int, level_index: int):
- or_statements: list[str] = []
-
- for i in range(level_index, index + 1):
- or_statements.append(f"latest_{i} < latest_{level_index - 1}")
-
- return " OR ".join(or_statements)
-
- def get_comparison_cols(self, level_index: int, max_steps: int):
- """
- level_index: The current smallest comparison step. Everything before
- level index is already at the minimum ordered timestamps.
- """
- cols: list[str] = []
- for i in range(0, max_steps):
- cols.append(f"step_{i}")
- if i < level_index:
- cols.append(f"latest_{i}")
- for field in self.extra_event_fields_and_properties:
- cols.append(f'"{field}_{i}"')
- for exclusion_id, exclusion in enumerate(self._filter.exclusions):
- if cast(int, exclusion.funnel_from_step) + 1 == i:
- cols.append(f"exclusion_{exclusion_id}_latest_{exclusion.funnel_from_step}")
- else:
- comparison = self._get_comparison_at_step(i, level_index)
- cols.append(f"if({comparison}, NULL, latest_{i}) as latest_{i}")
- for field in self.extra_event_fields_and_properties:
- cols.append(f'if({comparison}, NULL, "{field}_{i}") as "{field}_{i}"')
- for exclusion_id, exclusion in enumerate(self._filter.exclusions):
- if cast(int, exclusion.funnel_from_step) + 1 == i:
- exclusion_identifier = f"exclusion_{exclusion_id}_latest_{exclusion.funnel_from_step}"
- cols.append(
- f"if({exclusion_identifier} < latest_{exclusion.funnel_from_step}, NULL, {exclusion_identifier}) as {exclusion_identifier}"
- )
-
- return ", ".join(cols)
-
- def build_step_subquery(self, level_index: int, max_steps: int, event_names_alias: str = "events"):
- if level_index >= max_steps:
- return f"""
- SELECT
- aggregation_target,
- timestamp,
- {self._get_partition_cols(1, max_steps)}
- {self._get_breakdown_prop(group_remaining=True)}
- {self._get_person_and_group_properties()}
- FROM ({self._get_inner_event_query(entity_name=event_names_alias)})
- """
- else:
- return f"""
- SELECT
- aggregation_target,
- timestamp,
- {self._get_partition_cols(level_index, max_steps)}
- {self._get_breakdown_prop()}
- {self._get_person_and_group_properties()}
- FROM (
- SELECT
- aggregation_target,
- timestamp,
- {self.get_comparison_cols(level_index, max_steps)}
- {self._get_breakdown_prop()}
- {self._get_person_and_group_properties()}
- FROM ({self.build_step_subquery(level_index + 1, max_steps)})
- )
- """
diff --git a/posthog/queries/funnels/funnel_persons.py b/posthog/queries/funnels/funnel_persons.py
deleted file mode 100644
index c221727866e3..000000000000
--- a/posthog/queries/funnels/funnel_persons.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import Optional
-
-from posthog.models.filters.filter import Filter
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.queries.actor_base_query import ActorBaseQuery
-from posthog.queries.funnels.funnel import ClickhouseFunnel
-from posthog.queries.funnels.sql import FUNNEL_PERSONS_BY_STEP_SQL
-
-
-class ClickhouseFunnelActors(ClickhouseFunnel, ActorBaseQuery):
- _filter: Filter
- QUERY_TYPE = "funnel_actors"
-
- @cached_property
- def aggregation_group_type_index(self):
- return self._filter.aggregation_group_type_index
-
- def actor_query(
- self,
- limit_actors: Optional[bool] = True,
- extra_fields: Optional[list[str]] = None,
- ):
- extra_fields_string = ", ".join([self._get_timestamp_outer_select()] + (extra_fields or []))
- return (
- FUNNEL_PERSONS_BY_STEP_SQL.format(
- steps_per_person_query=self.get_step_counts_query(),
- persons_steps=self._get_funnel_person_step_condition(),
- matching_events_select_statement=self._get_funnel_person_step_events(),
- extra_fields=extra_fields_string,
- limit="LIMIT %(limit)s" if limit_actors else "",
- offset="OFFSET %(offset)s" if limit_actors else "",
- ),
- self.params,
- )
diff --git a/posthog/queries/funnels/funnel_strict.py b/posthog/queries/funnels/funnel_strict.py
deleted file mode 100644
index 467a771bece5..000000000000
--- a/posthog/queries/funnels/funnel_strict.py
+++ /dev/null
@@ -1,75 +0,0 @@
-from posthog.queries.funnels.base import ClickhouseFunnelBase
-
-
-class ClickhouseFunnelStrict(ClickhouseFunnelBase):
- QUERY_TYPE = "funnel_strict"
-
- def get_query(self):
- max_steps = len(self._filter.entities)
-
- breakdown_clause = self._get_breakdown_prop()
-
- return f"""
- SELECT {self._get_count_columns(max_steps)} {self._get_step_time_avgs(max_steps)} {self._get_step_time_median(max_steps)} {breakdown_clause} FROM (
- {self.get_step_counts_query()}
- ) {"GROUP BY prop" if breakdown_clause != "" else ""}
- {self._order_by(max_steps) if breakdown_clause != "" else ""}
- {self._get_limit() if breakdown_clause != "" else ""}
- """
-
- def get_step_counts_query(self):
- steps_per_person_query = self.get_step_counts_without_aggregation_query()
- max_steps = len(self._filter.entities)
- breakdown_clause = self._get_breakdown_prop()
- inner_timestamps, outer_timestamps = self._get_timestamp_selects()
-
- return f"""
- SELECT aggregation_target, steps {self._get_step_time_avgs(max_steps, inner_query=True)} {self._get_step_time_median(max_steps, inner_query=True)} {breakdown_clause} {outer_timestamps} {self._get_matching_event_arrays(max_steps)} {self._get_person_and_group_properties(aggregate=True)} FROM (
- SELECT aggregation_target, steps, max(steps) over (PARTITION BY aggregation_target {breakdown_clause}) as max_steps {self._get_step_time_names(max_steps)} {breakdown_clause} {inner_timestamps} {self._get_matching_events(max_steps)} {self._get_person_and_group_properties()} FROM (
- {steps_per_person_query}
- )
- ) GROUP BY aggregation_target, steps {breakdown_clause}
- HAVING steps = max(max_steps)
- """
-
- def get_step_counts_without_aggregation_query(self):
- max_steps = len(self._filter.entities)
-
- partition_select = self._get_partition_cols(1, max_steps)
- sorting_condition = self._get_sorting_condition(max_steps, max_steps)
- breakdown_clause = self._get_breakdown_prop(group_remaining=True)
-
- inner_query = f"""
- SELECT
- aggregation_target,
- timestamp,
- {partition_select}
- {breakdown_clause}
- {self._get_person_and_group_properties()}
- FROM ({self._get_inner_event_query(skip_entity_filter=True, skip_step_filter=True)})
- """
-
- formatted_query = f"""
- SELECT *, {sorting_condition} AS steps {self._get_step_times(max_steps)}{self._get_matching_events(max_steps)} {self._get_person_and_group_properties()} FROM (
- {inner_query}
- ) WHERE step_0 = 1"""
-
- return formatted_query
-
- def _get_partition_cols(self, level_index: int, max_steps: int):
- cols: list[str] = []
- for i in range(0, max_steps):
- cols.append(f"step_{i}")
- if i < level_index:
- cols.append(f"latest_{i}")
- for field in self.extra_event_fields_and_properties:
- cols.append(f'"{field}_{i}"')
- else:
- cols.append(
- f"min(latest_{i}) over (PARTITION by aggregation_target {self._get_breakdown_prop()} ORDER BY timestamp DESC ROWS BETWEEN {i} PRECEDING AND {i} PRECEDING) latest_{i}"
- )
- for field in self.extra_event_fields_and_properties:
- cols.append(
- f'min("{field}_{i}") over (PARTITION by aggregation_target {self._get_breakdown_prop()} ORDER BY timestamp DESC ROWS BETWEEN {i} PRECEDING AND {i} PRECEDING) "{field}_{i}"'
- )
- return ", ".join(cols)
diff --git a/posthog/queries/funnels/funnel_strict_persons.py b/posthog/queries/funnels/funnel_strict_persons.py
deleted file mode 100644
index 2ad13822f546..000000000000
--- a/posthog/queries/funnels/funnel_strict_persons.py
+++ /dev/null
@@ -1,34 +0,0 @@
-from typing import Optional
-
-from posthog.models.filters.filter import Filter
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.queries.actor_base_query import ActorBaseQuery
-from posthog.queries.funnels.funnel_strict import ClickhouseFunnelStrict
-from posthog.queries.funnels.sql import FUNNEL_PERSONS_BY_STEP_SQL
-
-
-class ClickhouseFunnelStrictActors(ClickhouseFunnelStrict, ActorBaseQuery):
- _filter: Filter
- QUERY_TYPE = "funnel_strict_actors"
-
- @cached_property
- def aggregation_group_type_index(self):
- return self._filter.aggregation_group_type_index
-
- def actor_query(
- self,
- limit_actors: Optional[bool] = True,
- extra_fields: Optional[list[str]] = None,
- ):
- extra_fields_string = ", ".join([self._get_timestamp_outer_select()] + (extra_fields or []))
- return (
- FUNNEL_PERSONS_BY_STEP_SQL.format(
- steps_per_person_query=self.get_step_counts_query(),
- persons_steps=self._get_funnel_person_step_condition(),
- matching_events_select_statement=self._get_funnel_person_step_events(),
- extra_fields=extra_fields_string,
- limit="LIMIT %(limit)s" if limit_actors else "",
- offset="OFFSET %(offset)s" if limit_actors else "",
- ),
- self.params,
- )
diff --git a/posthog/queries/funnels/funnel_time_to_convert.py b/posthog/queries/funnels/funnel_time_to_convert.py
deleted file mode 100644
index 94798411c15d..000000000000
--- a/posthog/queries/funnels/funnel_time_to_convert.py
+++ /dev/null
@@ -1,118 +0,0 @@
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import FUNNEL_TO_STEP
-from posthog.models.filters.filter import Filter
-from posthog.models.team import Team
-from posthog.queries.funnels.base import ClickhouseFunnelBase
-from posthog.queries.funnels.utils import get_funnel_order_class
-
-
-class ClickhouseFunnelTimeToConvert(ClickhouseFunnelBase):
- QUERY_TYPE = "funnel_time_to_convert"
-
- def __init__(self, filter: Filter, team: Team) -> None:
- super().__init__(filter, team)
- self.funnel_order = get_funnel_order_class(filter)(filter, team)
-
- def _format_results(self, results: list) -> dict:
- return {
- "bins": [(bin_from_seconds, person_count) for bin_from_seconds, person_count, _ in results],
- "average_conversion_time": results[0][2],
- }
-
- def get_query(self) -> str:
- steps_per_person_query = self.funnel_order.get_step_counts_query()
- self.params.update(self.funnel_order.params)
- # expects 1 person per row, whatever their max step is, and the step conversion times for this person
-
- # Conversion from which step should be calculated
- from_step = self._filter.funnel_from_step or 0
- # Conversion to which step should be calculated
- to_step = self._filter.funnel_to_step or len(self._filter.entities) - 1
-
- # Use custom bin_count if provided by user, otherwise infer an automatic one based on the number of samples
- bin_count = self._filter.bin_count
- if bin_count is not None:
- # Custom count is clamped between 1 and 90
- if bin_count < 1:
- bin_count = 1
- elif bin_count > 90:
- bin_count = 90
- bin_count_identifier = str(bin_count)
- bin_count_expression = None
- else:
- # Auto count is clamped between 1 and 60
- bin_count_identifier = "bin_count"
- bin_count_expression = f"""
- count() AS sample_count,
- least(60, greatest(1, ceil(cbrt(ifNull(sample_count, 0))))) AS {bin_count_identifier},
- """
-
- if not (0 < to_step < len(self._filter.entities)):
- raise ValidationError(
- f"Filter parameter {FUNNEL_TO_STEP} can only be one of {', '.join(map(str, range(1, len(self._filter.entities))))} for time to convert!"
- )
-
- steps_average_conversion_time_identifiers = [
- f"step_{step + 1}_average_conversion_time_inner" for step in range(from_step, to_step)
- ]
- steps_average_conversion_time_expression_sum = " + ".join(steps_average_conversion_time_identifiers)
-
- query = f"""
- WITH
- step_runs AS (
- {steps_per_person_query}
- ),
- histogram_params AS (
- /* Binning ensures that each sample belongs to a bin in results */
- /* If bin_count is not a custom number, it's calculated in bin_count_expression */
- SELECT
- ifNull(floor(min({steps_average_conversion_time_expression_sum})), 0) AS from_seconds,
- ifNull(ceil(max({steps_average_conversion_time_expression_sum})), 1) AS to_seconds,
- round(avg({steps_average_conversion_time_expression_sum}), 2) AS average_conversion_time,
- {bin_count_expression or ""}
- ceil((to_seconds - from_seconds) / {bin_count_identifier}) AS bin_width_seconds_raw,
- /* Use 60 seconds as fallback bin width in case of only one sample */
- if(bin_width_seconds_raw > 0, bin_width_seconds_raw, 60) AS bin_width_seconds
- FROM step_runs
- -- We only need to check step to_step here, because it depends on all the other ones being NOT NULL too
- WHERE step_{to_step}_average_conversion_time_inner IS NOT NULL
- ),
- /* Below CTEs make histogram_params columns available to the query below as straightforward identifiers */
- ( SELECT bin_width_seconds FROM histogram_params ) AS bin_width_seconds,
- /* bin_count is only made available as an identifier if it had to be calculated */
- {
- f"( SELECT {bin_count_identifier} FROM histogram_params ) AS {bin_count_identifier},"
- if bin_count_expression
- else ""
- }
- ( SELECT from_seconds FROM histogram_params ) AS histogram_from_seconds,
- ( SELECT to_seconds FROM histogram_params ) AS histogram_to_seconds,
- ( SELECT average_conversion_time FROM histogram_params ) AS histogram_average_conversion_time
- SELECT
- bin_from_seconds,
- person_count,
- histogram_average_conversion_time AS average_conversion_time
- FROM (
- /* Calculating bins from step runs */
- SELECT
- histogram_from_seconds + floor(({
- steps_average_conversion_time_expression_sum
- } - histogram_from_seconds) / bin_width_seconds) * bin_width_seconds AS bin_from_seconds,
- count() AS person_count
- FROM step_runs
- GROUP BY bin_from_seconds
- ) results
- RIGHT OUTER JOIN (
- /* Making sure bin_count bins are returned */
- /* Those not present in the results query due to lack of data simply get person_count 0 */
- SELECT histogram_from_seconds + number * bin_width_seconds AS bin_from_seconds FROM system.numbers LIMIT ifNull({
- bin_count_identifier
- }, 0) + 1
- ) fill
- USING (bin_from_seconds)
- ORDER BY bin_from_seconds
- SETTINGS max_ast_elements=1000000, max_expanded_ast_elements=1000000
- """
-
- return query
diff --git a/posthog/queries/funnels/funnel_trends.py b/posthog/queries/funnels/funnel_trends.py
deleted file mode 100644
index 3e1430d26cfc..000000000000
--- a/posthog/queries/funnels/funnel_trends.py
+++ /dev/null
@@ -1,221 +0,0 @@
-from datetime import datetime
-from itertools import groupby
-from typing import Optional
-
-from posthog.models.filters.filter import Filter
-from posthog.models.team import Team
-from posthog.queries.funnels.base import ClickhouseFunnelBase
-from posthog.queries.funnels.utils import get_funnel_order_class
-from posthog.queries.util import (
- correct_result_for_sampling,
- get_earliest_timestamp,
- get_interval_func_ch,
- get_start_of_interval_sql,
-)
-
-from products.cohorts.backend.models.cohort import Cohort
-
-TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"
-HUMAN_READABLE_TIMESTAMP_FORMAT = "%-d-%b-%Y"
-
-
-class ClickhouseFunnelTrends(ClickhouseFunnelBase):
- """
- ## Funnel trends assumptions
-
- Funnel trends are a graph of conversion over time – meaning a Y ({conversion_rate}) for each X ({entrance_period}).
-
- ### What is {entrance_period}?
-
- A funnel is considered entered by a user when they have performed its first step.
- When that happens, we consider that an entrance of funnel.
-
- Now, our time series is based on a sequence of {entrance_period}s, each starting at {entrance_period_start}
- and ending _right before the next_ {entrance_period_start}. A person is then counted at most once in each
- {entrance_period}.
-
- ### What is {conversion_rate}?
-
- Each time a funnel is entered by a person, they have exactly {funnel_window_interval} {funnel_window_interval_unit} to go
- through the funnel's steps. Later events are just not taken into account.
-
- For {conversion_rate}, we need to know reference steps: {from_step} and {to_step}.
- By default they are respectively the first and the last steps of the funnel.
-
- Then for each {entrance_period} we calculate {reached_from_step_count} – the number of persons
- who entered the funnel and reached step {from_step} (along with all the steps leading up to it, if there any).
- Similarly we calculate {reached_to_step_count}, which is the number of persons from {reached_from_step_count}
- who also reached step {to_step} (along with all the steps leading up to it, including of course step {from_step}).
-
- {conversion_rate} is simply {reached_to_step_count} divided by {reached_from_step_count},
- multiplied by 100 to be a percentage.
-
- If no people have reached step {from_step} in the period, {conversion_rate} is zero.
- """
-
- QUERY_TYPE = "funnel_trends"
-
- def __init__(self, filter: Filter, team: Team) -> None:
- super().__init__(filter, team)
-
- self.funnel_order = get_funnel_order_class(filter)(filter, team)
-
- def _exec_query(self):
- return self._summarize_data(super()._exec_query())
-
- def get_step_counts_without_aggregation_query(
- self, *, specific_entrance_period_start: Optional[datetime] = None
- ) -> str:
- steps_per_person_query = self.funnel_order.get_step_counts_without_aggregation_query()
-
- # This is used by funnel trends when we only need data for one period, e.g. person per data point
- if specific_entrance_period_start:
- self.params["entrance_period_start"] = specific_entrance_period_start.strftime(TIMESTAMP_FORMAT)
-
- event_select_clause = ""
- if self._filter.include_recordings:
- max_steps = len(self._filter.entities)
- event_select_clause = self._get_matching_event_arrays(max_steps)
-
- breakdown_clause = self._get_breakdown_prop()
- return f"""
- SELECT
- aggregation_target,
- {get_start_of_interval_sql(self._filter.interval, team=self._team)} AS entrance_period_start,
- max(steps) AS steps_completed
- {event_select_clause}
- {breakdown_clause}
- FROM (
- {steps_per_person_query}
- )
- {"WHERE toDateTime(entrance_period_start) = %(entrance_period_start)s" if specific_entrance_period_start else ""}
- GROUP BY aggregation_target, entrance_period_start {breakdown_clause}"""
-
- def get_query(self) -> str:
- step_counts = self.get_step_counts_without_aggregation_query()
- # Expects multiple rows for same person, first event time, steps taken.
- self.params.update(self.funnel_order.params)
-
- (
- reached_from_step_count_condition,
- reached_to_step_count_condition,
- _,
- ) = self.get_steps_reached_conditions()
- interval_func = get_interval_func_ch(self._filter.interval)
-
- if self._filter.date_from is None:
- _date_from = get_earliest_timestamp(self._team.pk)
- else:
- _date_from = self._filter.date_from
-
- breakdown_clause = self._get_breakdown_prop()
-
- self.params.update(
- {
- "formatted_date_from": _date_from.strftime("%Y-%m-%d %H:%M:%S"),
- "formatted_date_to": self._filter.date_to.strftime("%Y-%m-%d %H:%M:%S"),
- "interval": self._filter.interval,
- }
- )
-
- query = f"""
- SELECT
- entrance_period_start,
- reached_from_step_count,
- reached_to_step_count,
- if(reached_from_step_count > 0, round(reached_to_step_count / reached_from_step_count * 100, 2), 0) AS conversion_rate
- {breakdown_clause}
- FROM (
- SELECT
- entrance_period_start,
- countIf({reached_from_step_count_condition}) AS reached_from_step_count,
- countIf({reached_to_step_count_condition}) AS reached_to_step_count
- {breakdown_clause}
- FROM (
- {step_counts}
- ) GROUP BY entrance_period_start {breakdown_clause}
- ) data
- RIGHT OUTER JOIN (
- SELECT
- {get_start_of_interval_sql(self._filter.interval, team=self._team, source="%(formatted_date_from)s")} + {interval_func}(number) AS entrance_period_start
- {", breakdown_value as prop" if breakdown_clause else ""}
- FROM numbers(dateDiff(%(interval)s, {get_start_of_interval_sql(self._filter.interval, team=self._team, source="%(formatted_date_from)s")}, {get_start_of_interval_sql(self._filter.interval, team=self._team, source="%(formatted_date_to)s")}) + 1) AS period_offsets
- {"ARRAY JOIN (%(breakdown_values)s) AS breakdown_value" if breakdown_clause else ""}
- ) fill
- USING (entrance_period_start {breakdown_clause})
- ORDER BY entrance_period_start ASC
- """
-
- return query
-
- def get_steps_reached_conditions(self) -> tuple[str, str, str]:
- # How many steps must have been done to count for the denominator of a funnel trends data point
- from_step = self._filter.funnel_from_step or 0
- # How many steps must have been done to count for the numerator of a funnel trends data point
- to_step = self._filter.funnel_to_step or len(self._filter.entities) - 1
-
- # Those who converted OR dropped off
- reached_from_step_count_condition = f"steps_completed >= {from_step + 1}"
- # Those who converted
- reached_to_step_count_condition = f"steps_completed >= {to_step + 1}"
- # Those who dropped off
- did_not_reach_to_step_count_condition = (
- f"{reached_from_step_count_condition} AND steps_completed < {to_step + 1}"
- )
- return (
- reached_from_step_count_condition,
- reached_to_step_count_condition,
- did_not_reach_to_step_count_condition,
- )
-
- def _summarize_data(self, results):
- breakdown_clause = self._get_breakdown_prop()
-
- summary = []
-
- for period_row in results:
- serialized_result = {
- "timestamp": period_row[0],
- "reached_from_step_count": correct_result_for_sampling(period_row[1], self._filter.sampling_factor),
- "reached_to_step_count": correct_result_for_sampling(period_row[2], self._filter.sampling_factor),
- "conversion_rate": period_row[3],
- }
-
- if breakdown_clause:
- if isinstance(period_row[-1], str) or (
- isinstance(period_row[-1], list) and all(isinstance(item, str) for item in period_row[-1])
- ):
- serialized_result.update({"breakdown_value": (period_row[-1])})
- else:
- # nosemgrep: idor-lookup-without-team (ID from team-scoped ClickHouse result)
- serialized_result.update({"breakdown_value": Cohort.objects.get(pk=period_row[-1]).name})
-
- summary.append(serialized_result)
- return summary
-
- def _format_results(self, summary):
- if self._filter.breakdown:
- grouper = lambda row: row["breakdown_value"]
- sorted_data = sorted(summary, key=grouper)
- final_res = []
- for key, value in groupby(sorted_data, grouper):
- breakdown_res = self._format_single_summary(list(value))
- final_res.append({**breakdown_res, "breakdown_value": key})
- return final_res
- else:
- res = self._format_single_summary(summary)
-
- return [res]
-
- def _format_single_summary(self, summary):
- count = len(summary)
- data = []
- days = []
- labels = []
- for row in summary:
- timestamp: datetime = row["timestamp"]
- data.append(row["conversion_rate"])
- hour_min_sec = " %H:%M:%S" if self._filter.interval == "hour" else ""
- days.append(timestamp.strftime(f"%Y-%m-%d{hour_min_sec}"))
- labels.append(timestamp.strftime(HUMAN_READABLE_TIMESTAMP_FORMAT))
- return {"count": count, "data": data, "days": days, "labels": labels}
diff --git a/posthog/queries/funnels/funnel_trends_persons.py b/posthog/queries/funnels/funnel_trends_persons.py
deleted file mode 100644
index 0f4391eb041e..000000000000
--- a/posthog/queries/funnels/funnel_trends_persons.py
+++ /dev/null
@@ -1,69 +0,0 @@
-from typing import Optional
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import DROP_OFF, ENTRANCE_PERIOD_START
-from posthog.models.filters.filter import Filter
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.queries.actor_base_query import ActorBaseQuery
-from posthog.queries.funnels.funnel_trends import ClickhouseFunnelTrends
-from posthog.queries.funnels.sql import FUNNEL_PERSONS_BY_STEP_SQL
-
-
-class ClickhouseFunnelTrendsActors(ClickhouseFunnelTrends, ActorBaseQuery):
- _filter: Filter
- QUERY_TYPE = "funnel_trends_actors"
-
- @cached_property
- def aggregation_group_type_index(self):
- return self._filter.aggregation_group_type_index
-
- def _get_funnel_person_step_events(self):
- if self._filter.include_recordings:
- # Get the event that should be used to match the recording
- funnel_to_step = self._filter.funnel_to_step
- is_drop_off = self._filter.drop_off
-
- if funnel_to_step is None or is_drop_off:
- # If there is no funnel_to_step or if we are looking for drop off, we need to get the users final event
- return ", final_matching_events as matching_events"
- else:
- # Otherwise, we return the event of the funnel_to_step
- self.params.update({"matching_events_step_num": funnel_to_step})
- return ", step_%(matching_events_step_num)s_matching_events as matching_events"
- return ""
-
- def actor_query(self, limit_actors: Optional[bool] = True):
- drop_off = self._filter.drop_off
- if drop_off is None:
- raise ValidationError(f"Filter parameter {DROP_OFF} must be provided and a bool for funnel trends persons!")
-
- entrance_period_start = self._filter.entrance_period_start
- if not entrance_period_start:
- raise ValidationError(
- f"Filter parameter {ENTRANCE_PERIOD_START} must be provided and a datetime for funnel trends persons!"
- )
-
- step_counts_query = self.get_step_counts_without_aggregation_query(
- specific_entrance_period_start=entrance_period_start
- )
- # Expects multiple rows for same person, first event time, steps taken.
- self.params.update(self.funnel_order.params)
-
- (
- _,
- reached_to_step_count_condition,
- did_not_reach_to_step_count_condition,
- ) = self.get_steps_reached_conditions()
-
- return (
- FUNNEL_PERSONS_BY_STEP_SQL.format(
- steps_per_person_query=step_counts_query,
- persons_steps=did_not_reach_to_step_count_condition if drop_off else reached_to_step_count_condition,
- matching_events_select_statement=self._get_funnel_person_step_events(),
- extra_fields="",
- limit="LIMIT %(limit)s" if limit_actors else "",
- offset="OFFSET %(offset)s" if limit_actors else "",
- ),
- self.params,
- )
diff --git a/posthog/queries/funnels/funnel_unordered.py b/posthog/queries/funnels/funnel_unordered.py
deleted file mode 100644
index ab2ae527ad2c..000000000000
--- a/posthog/queries/funnels/funnel_unordered.py
+++ /dev/null
@@ -1,182 +0,0 @@
-import uuid
-from typing import Any, Optional, cast
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.models.entity.entity import Entity
-from posthog.queries.funnels.base import ClickhouseFunnelBase
-from posthog.queries.util import correct_result_for_sampling
-
-
-class ClickhouseFunnelUnordered(ClickhouseFunnelBase):
- """
- Unordered Funnel is a funnel where the order of steps doesn't matter.
-
- ## Query Intuition
-
- Imagine a funnel with three events: A, B, and C.
- This query splits the problem into two parts:
- 1. Given the first event is A, find the furthest everyone went starting from A.
- This finds any B's and C's that happen after A (without ordering them)
- 2. Repeat the above, assuming first event to be B, and then C.
-
- Then, the outer query unions the result of (2) and takes the maximum of these.
-
- ## Results
-
- The result format is the same as the basic funnel, i.e. [step, count].
- Here, `step_i` (0 indexed) signifies the number of people that did at least `i+1` steps.
-
- ## Exclusion Semantics
- For unordered funnels, exclusion is a bit weird. It means, given all ordering of the steps,
- how far can you go without seeing an exclusion event.
- If you see an exclusion event => you're discarded.
- See test_advanced_funnel_multiple_exclusions_between_steps for details.
- """
-
- QUERY_TYPE = "funnel_unordered"
-
- def _serialize_step(
- self,
- step: Entity,
- count: int,
- people: Optional[list[uuid.UUID]] = None,
- sampling_factor: Optional[float] = None,
- ) -> dict[str, Any]:
- return {
- "action_id": None,
- "name": f"Completed {step.index + 1} step{'s' if step.index != 0 else ''}",
- "custom_name": None,
- "order": step.index,
- "people": people if people else [],
- "count": correct_result_for_sampling(count, sampling_factor),
- "type": step.type,
- }
-
- def get_query(self):
- max_steps = len(self._filter.entities)
-
- for exclusion in self._filter.exclusions:
- if exclusion.funnel_from_step != 0 or exclusion.funnel_to_step != max_steps - 1:
- raise ValidationError("Partial Exclusions not allowed in unordered funnels")
-
- breakdown_clause = self._get_breakdown_prop()
-
- return f"""
- SELECT {self._get_count_columns(max_steps)} {self._get_step_time_avgs(max_steps)} {self._get_step_time_median(max_steps)} {breakdown_clause} FROM (
- {self.get_step_counts_query()}
- ) {"GROUP BY prop" if breakdown_clause != "" else ""}
- {self._order_by(max_steps) if breakdown_clause != "" else ""}
- {self._get_limit() if breakdown_clause != "" else ""}
- """
-
- def get_step_counts_query(self):
- max_steps = len(self._filter.entities)
-
- union_query = self.get_step_counts_without_aggregation_query()
- breakdown_clause = self._get_breakdown_prop()
- inner_timestamps, outer_timestamps = self._get_timestamp_selects()
-
- return f"""
- SELECT aggregation_target, steps {self._get_step_time_avgs(max_steps, inner_query=True)} {self._get_step_time_median(max_steps, inner_query=True)} {breakdown_clause} {outer_timestamps} {self._get_person_and_group_properties(aggregate=True)} FROM (
- SELECT aggregation_target, steps, max(steps) over (PARTITION BY aggregation_target {breakdown_clause}) as max_steps {self._get_step_time_names(max_steps)} {breakdown_clause} {inner_timestamps} {self._get_person_and_group_properties()} FROM (
- {union_query}
- )
- ) GROUP BY aggregation_target, steps {breakdown_clause}
- HAVING steps = max(max_steps)
- """
-
- def get_step_counts_without_aggregation_query(self):
- max_steps = len(self._filter.entities)
- union_queries = []
- entities_to_use = list(self._filter.entities)
-
- partition_select = self._get_partition_cols(1, max_steps)
- sorting_condition = self.get_sorting_condition(max_steps)
- breakdown_clause = self._get_breakdown_prop(group_remaining=True)
- exclusion_clause = self._get_exclusion_condition()
-
- for i in range(max_steps):
- inner_query = f"""
- SELECT
- aggregation_target,
- timestamp,
- {partition_select}
- {breakdown_clause}
- {self._get_person_and_group_properties()}
- FROM ({self._get_inner_event_query(entities_to_use, f"events_{i}")})
- """
-
- formatted_query = f"""
- SELECT *, {sorting_condition} AS steps {exclusion_clause} {self._get_step_times(max_steps)} {self._get_person_and_group_properties()} FROM (
- {inner_query}
- ) WHERE step_0 = 1
- {"AND exclusion = 0" if exclusion_clause else ""}
- """
-
- #  rotate entities by 1 to get new first event
- entities_to_use.append(entities_to_use.pop(0))
- union_queries.append(formatted_query)
-
- return " UNION ALL ".join(union_queries)
-
- def _get_step_times(self, max_steps: int):
- conditions: list[str] = []
-
- conversion_times_elements = []
- for i in range(max_steps):
- conversion_times_elements.append(f"latest_{i}")
-
- conditions.append(f"arraySort([{','.join(conversion_times_elements)}]) as conversion_times")
-
- for i in range(1, max_steps):
- conditions.append(
- f"if(isNotNull(conversion_times[{i + 1}]) AND conversion_times[{i + 1}] <= conversion_times[{i}] + INTERVAL {self._filter.funnel_window_interval} {self._filter.funnel_window_interval_unit_ch()}, "
- f"dateDiff('second', conversion_times[{i}], conversion_times[{i + 1}]), NULL) step_{i}_conversion_time"
- )
- # array indices in ClickHouse are 1-based :shrug:
-
- formatted = ", ".join(conditions)
- return f", {formatted}" if formatted else ""
-
- def get_sorting_condition(self, max_steps: int):
- conditions = []
-
- event_times_elements = []
- for i in range(max_steps):
- event_times_elements.append(f"latest_{i}")
-
- conditions.append(f"arraySort([{','.join(event_times_elements)}]) as event_times")
- # replacement of latest_i for whatever query part requires it, just like conversion_times
- basic_conditions: list[str] = []
- for i in range(1, max_steps):
- basic_conditions.append(
- f"if(latest_0 < latest_{i} AND latest_{i} <= latest_0 + INTERVAL {self._filter.funnel_window_interval} {self._filter.funnel_window_interval_unit_ch()}, 1, 0)"
- )
-
- conditions.append(f"arraySum([{','.join(basic_conditions)}, 1])")
-
- if basic_conditions:
- return ",".join(conditions)
- else:
- return "1"
-
- def _get_exclusion_condition(self):
- if not self._filter.exclusions:
- return ""
-
- conditions = []
- for exclusion_id, exclusion in enumerate(self._filter.exclusions):
- from_time = f"latest_{exclusion.funnel_from_step}"
- to_time = f"event_times[{cast(int, exclusion.funnel_to_step) + 1}]"
- exclusion_time = f"exclusion_{exclusion_id}_latest_{exclusion.funnel_from_step}"
- condition = (
- f"if( {exclusion_time} > {from_time} AND {exclusion_time} < "
- f"if(isNull({to_time}), {from_time} + INTERVAL {self._filter.funnel_window_interval} {self._filter.funnel_window_interval_unit_ch()}, {to_time}), 1, 0)"
- )
- conditions.append(condition)
-
- if conditions:
- return f", arraySum([{','.join(conditions)}]) as exclusion"
- else:
- return ""
diff --git a/posthog/queries/funnels/funnel_unordered_persons.py b/posthog/queries/funnels/funnel_unordered_persons.py
deleted file mode 100644
index fc1e953bfb58..000000000000
--- a/posthog/queries/funnels/funnel_unordered_persons.py
+++ /dev/null
@@ -1,41 +0,0 @@
-from typing import Optional
-
-from posthog.models.filters.filter import Filter
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.queries.actor_base_query import ActorBaseQuery
-from posthog.queries.funnels.funnel_unordered import ClickhouseFunnelUnordered
-from posthog.queries.funnels.sql import FUNNEL_PERSONS_BY_STEP_SQL
-
-
-class ClickhouseFunnelUnorderedActors(ClickhouseFunnelUnordered, ActorBaseQuery):
- _filter: Filter
- QUERY_TYPE = "funnel_unordered_actors"
-
- @cached_property
- def aggregation_group_type_index(self):
- return self._filter.aggregation_group_type_index
-
- def _get_funnel_person_step_events(self):
- # Unordered funnels does not support matching events (and thereby recordings),
- # but it simplifies the logic if we return an empty array for matching events
- if self._filter.include_recordings:
- return ", array() as matching_events"
- return ""
-
- def actor_query(
- self,
- limit_actors: Optional[bool] = True,
- extra_fields: Optional[list[str]] = None,
- ):
- extra_fields_string = ", ".join([self._get_timestamp_outer_select()] + (extra_fields or []))
- return (
- FUNNEL_PERSONS_BY_STEP_SQL.format(
- steps_per_person_query=self.get_step_counts_query(),
- persons_steps=self._get_funnel_person_step_condition(),
- matching_events_select_statement=self._get_funnel_person_step_events(),
- extra_fields=extra_fields_string,
- limit="LIMIT %(limit)s" if limit_actors else "",
- offset="OFFSET %(offset)s" if limit_actors else "",
- ),
- self.params,
- )
diff --git a/posthog/queries/funnels/sql.py b/posthog/queries/funnels/sql.py
deleted file mode 100644
index 8d488f936631..000000000000
--- a/posthog/queries/funnels/sql.py
+++ /dev/null
@@ -1,11 +0,0 @@
-FUNNEL_PERSONS_BY_STEP_SQL = """
-SELECT aggregation_target AS actor_id{matching_events_select_statement} {extra_fields}
-FROM (
- {steps_per_person_query}
-)
-WHERE {persons_steps}
-ORDER BY aggregation_target
-{limit}
-{offset}
-SETTINGS max_ast_elements=1000000, max_expanded_ast_elements=1000000
-"""
diff --git a/posthog/queries/funnels/test/__init__.py b/posthog/queries/funnels/test/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/queries/funnels/test/__snapshots__/test_breakdowns_by_current_url.ambr b/posthog/queries/funnels/test/__snapshots__/test_breakdowns_by_current_url.ambr
deleted file mode 100644
index 6ed53b789556..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_breakdowns_by_current_url.ambr
+++ /dev/null
@@ -1,201 +0,0 @@
-# serializer version: 1
-# name: TestBreakdownsByCurrentURL.test_breakdown_by_current_url
- '''
-
- SELECT array(if(empty(trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '')))) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['terminate funnel', 'watched movie']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 101
- OFFSET 0
- '''
-# ---
-# name: TestBreakdownsByCurrentURL.test_breakdown_by_current_url.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([['https://example.com/home'], ['https://example.com'], ['/']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'watched movie', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'terminate funnel', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(if(empty(trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '')))) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['terminate funnel', 'watched movie']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['terminate funnel', 'watched movie']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestBreakdownsByCurrentURL.test_breakdown_by_pathname
- '''
-
- SELECT array(if(empty(trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$pathname'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$pathname'), '^"|"$', '')))) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['terminate funnel', 'watched movie']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 101
- OFFSET 0
- '''
-# ---
-# name: TestBreakdownsByCurrentURL.test_breakdown_by_pathname.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([['/'], ['/home']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'watched movie', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'terminate funnel', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(if(empty(trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$pathname'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$pathname'), '^"|"$', '')))) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['terminate funnel', 'watched movie']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['terminate funnel', 'watched movie']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr
deleted file mode 100644
index 6e1eeb0dd691..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr
+++ /dev/null
@@ -1,1456 +0,0 @@
-# serializer version: 1
-# name: TestFOSSFunnel.test_funnel_conversion_window_seconds
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 15 SECOND
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 15 SECOND, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 15 SECOND, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 15 SECOND, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 15 SECOND, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_conversion_window_seconds.1
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 15 SECOND
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 15 SECOND, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 15 SECOND, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 15 SECOND, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 15 SECOND, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_events_with_person_on_events_v2
- '''
-
- SELECT DISTINCT person_id
- FROM events
- WHERE team_id = 99999
- AND distinct_id = 'stopped_after_pay'
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_events_with_person_on_events_v2.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as aggregation_target,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if((((match(elements_chain, '(^|;)button(\\.|$|;|:)'))
- AND (match(elements_chain, '(text="Pay\\ \\$10")'))
- AND event = '$autocapture')) , 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if((((match(elements_chain, '(^|;)a(\\.|$|;|:)'))
- AND (match(elements_chain, '(href="/movie")'))
- AND event = '$autocapture')) , 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event IN ['$autocapture', 'user signed up', '$autocapture', '$autocapture']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2011-12-25 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2012-01-01 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_cohorts_step_filter
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up'
- AND (person_id IN (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___email, person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(ilike(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'email'), ''), 'null'), '^"|"$', '')), '%.com%'), 0)))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(ilike(toString(persons.properties___email), '%.com%'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1, join_algorithm='auto'))), 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_precalculated_cohort_step_filter
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_precalculated_cohort_step_filter.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up'
- AND (person_id IN
- (SELECT DISTINCT person_id
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0)), 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_precalculated_cohort_step_filter.2
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_precalculated_cohort_step_filter.3
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up'
- AND (person_id IN
- (SELECT DISTINCT person_id
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0 )), 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC') )
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1) ))
- WHERE step_0 = 1 ))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_property_groups
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- countIf(steps = 3) step_3,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- avg(step_2_average_conversion_time_inner) step_2_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- median(step_2_median_conversion_time_inner) step_2_median_conversion_time
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = '$pageview'
- AND (has(['aloha.com'], replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = '$pageview'
- AND (has(['aloha2.com'], replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['$pageview', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.com%'
- AND has(['20'], replaceRegexpAll(JSONExtractRaw(properties, 'age'), '^"|"$', '')))
- OR (replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.org%'
- OR has(['28'], replaceRegexpAll(JSONExtractRaw(properties, 'age'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.com%'
- AND has(['20'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'age'), '^"|"$', '')))
- OR (replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.org%'
- OR has(['28'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'age'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['$pageview', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_property_groups.1
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = '$pageview'
- AND (has(['aloha.com'], replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = '$pageview'
- AND (has(['aloha2.com'], replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['$pageview', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.com%'
- AND has(['20'], replaceRegexpAll(JSONExtractRaw(properties, 'age'), '^"|"$', '')))
- OR (replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.org%'
- OR has(['28'], replaceRegexpAll(JSONExtractRaw(properties, 'age'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.com%'
- AND has(['20'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'age'), '^"|"$', '')))
- OR (replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.org%'
- OR has(['28'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'age'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['$pageview', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_property_groups.2
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = '$pageview'
- AND (has(['aloha.com'], replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = '$pageview'
- AND (has(['aloha2.com'], replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['$pageview', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.com%'
- AND has(['20'], replaceRegexpAll(JSONExtractRaw(properties, 'age'), '^"|"$', '')))
- OR (replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.org%'
- OR has(['28'], replaceRegexpAll(JSONExtractRaw(properties, 'age'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.com%'
- AND has(['20'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'age'), '^"|"$', '')))
- OR (replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.org%'
- OR has(['28'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'age'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['$pageview', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_property_groups.3
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = '$pageview'
- AND (has(['aloha.com'], replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = '$pageview'
- AND (has(['aloha2.com'], replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['$pageview', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.com%'
- AND has(['20'], replaceRegexpAll(JSONExtractRaw(properties, 'age'), '^"|"$', '')))
- OR (replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%.org%'
- OR has(['28'], replaceRegexpAll(JSONExtractRaw(properties, 'age'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.com%'
- AND has(['20'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'age'), '^"|"$', '')))
- OR (replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%.org%'
- OR has(['28'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'age'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['$pageview', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_static_cohort_step_filter
- '''
- SELECT person_id
- FROM person_static_cohort
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND person_id IN ['00000000-0000-4000-8000-000000000001']
- GROUP BY person_id
- '''
-# ---
-# name: TestFOSSFunnel.test_funnel_with_static_cohort_step_filter.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up'
- AND (person_id IN
- (SELECT person_id as id
- FROM person_static_cohort
- WHERE cohort_id = 99999
- AND team_id = 99999)), 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-14 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- '''
-# ---
-# name: TestFOSSFunnel.test_timezones
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'user signed up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'paid', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'US/Pacific') >= toDateTime('2020-01-01 00:00:00', 'US/Pacific')
- AND toTimeZone(timestamp, 'US/Pacific') <= toDateTime('2020-01-14 23:59:59', 'US/Pacific'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['paid', 'user signed up']
- AND toTimeZone(timestamp, 'US/Pacific') >= toDateTime('2020-01-01 00:00:00', 'US/Pacific')
- AND toTimeZone(timestamp, 'US/Pacific') <= toDateTime('2020-01-14 23:59:59', 'US/Pacific')
- AND (step_0 = 1
- OR step_1 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- '''
-# ---
-# name: TestFunnelBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([[''], ['Mac'], ['Chrome'], ['Safari']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy'
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'buy'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(e.properties, '$version'), '^"|"$', '')))
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([['Safari'], ['Mac']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy'
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS prop_basic,
- if(step_0 = 1, prop_basic, []) as prop_0,
- if(step_1 = 1, prop_basic, []) as prop_1,
- prop_1 as prop_final,
- groupUniqArray(prop_final) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)) ARRAY
- JOIN prop_vals as prop
- WHERE prop != []))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelBreakdown.test_funnel_step_multiple_breakdown_snapshot
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelBreakdown.test_funnel_step_multiple_breakdown_snapshot.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner ,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time ,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- prop
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([['', ''], ['alakazam', ''], ['Safari', 'xyz'], ['Mac', ''], ['Chrome', 'xyz'], ['0', '0'], ['', 'no-mac']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['','']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', '')) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel_persons.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel_persons.ambr
deleted file mode 100644
index 10c0894f4bbf..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel_persons.ambr
+++ /dev/null
@@ -1,556 +0,0 @@
-# serializer version: 1
-# name: TestFunnelPersons.test_funnel_person_recordings
- '''
-
- SELECT aggregation_target AS actor_id,
- step_0_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2,
- if(latest_2 < latest_1, NULL, "uuid_2") as "uuid_2",
- if(latest_2 < latest_1, NULL, "$session_id_2") as "$session_id_2",
- if(latest_2 < latest_1, NULL, "$window_id_2") as "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelPersons.test_funnel_person_recordings.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s1']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestFunnelPersons.test_funnel_person_recordings.2
- '''
-
- SELECT aggregation_target AS actor_id,
- step_1_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2,
- if(latest_2 < latest_1, NULL, "uuid_2") as "uuid_2",
- if(latest_2 < latest_1, NULL, "$session_id_2") as "$session_id_2",
- if(latest_2 < latest_1, NULL, "$window_id_2") as "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelPersons.test_funnel_person_recordings.3
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s2']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestFunnelPersons.test_funnel_person_recordings.4
- '''
-
- SELECT aggregation_target AS actor_id,
- step_1_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2,
- if(latest_2 < latest_1, NULL, "uuid_2") as "uuid_2",
- if(latest_2 < latest_1, NULL, "$session_id_2") as "$session_id_2",
- if(latest_2 < latest_1, NULL, "$window_id_2") as "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps = 2
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelPersons.test_funnel_person_recordings.5
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s2']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel_strict.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel_strict.ambr
deleted file mode 100644
index 02507f47fa8c..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel_strict.ambr
+++ /dev/null
@@ -1,284 +0,0 @@
-# serializer version: 1
-# name: TestFunnelStrictStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelStrictStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1 ,
- if(has([[''], ['Mac'], ['Chrome'], ['Safari']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy'
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (1=1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelStrictStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'buy'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(e.properties, '$version'), '^"|"$', '')))
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelStrictStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1 ,
- if(has([['Safari'], ['Mac']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy'
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS prop_basic,
- if(step_0 = 1, prop_basic, []) as prop_0,
- if(step_1 = 1, prop_basic, []) as prop_1,
- prop_1 as prop_final,
- groupUniqArray(prop_final) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (1=1)) ARRAY
- JOIN prop_vals as prop
- WHERE prop != []))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelStrictStepsBreakdown.test_funnel_step_multiple_breakdown_snapshot
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelStrictStepsBreakdown.test_funnel_step_multiple_breakdown_snapshot.1
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- prop
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1 ,
- if(has([['', ''], ['alakazam', ''], ['Safari', 'xyz'], ['Mac', ''], ['Chrome', 'xyz'], ['0', '0'], ['', 'no-mac']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['','']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', '')) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (1=1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel_strict_persons.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel_strict_persons.ambr
deleted file mode 100644
index a41ab9e8fa05..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel_strict_persons.ambr
+++ /dev/null
@@ -1,436 +0,0 @@
-# serializer version: 1
-# name: TestFunnelStrictStepsPersons.test_strict_funnel_person_recordings
- '''
-
- SELECT aggregation_target AS actor_id,
- step_0_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- min("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "uuid_1",
- min("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$session_id_1",
- min("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) latest_2,
- min("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "uuid_2",
- min("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "$session_id_2",
- min("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (1=1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelStrictStepsPersons.test_strict_funnel_person_recordings.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s1']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestFunnelStrictStepsPersons.test_strict_funnel_person_recordings.2
- '''
-
- SELECT aggregation_target AS actor_id,
- step_1_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- min("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "uuid_1",
- min("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$session_id_1",
- min("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) latest_2,
- min("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "uuid_2",
- min("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "$session_id_2",
- min("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (1=1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelStrictStepsPersons.test_strict_funnel_person_recordings.3
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s2']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestFunnelStrictStepsPersons.test_strict_funnel_person_recordings.4
- '''
-
- SELECT aggregation_target AS actor_id,
- step_1_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner ,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time ,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- min("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "uuid_1",
- min("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$session_id_1",
- min("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) latest_2,
- min("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "uuid_2",
- min("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "$session_id_2",
- min("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (1=1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps = 2
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelStrictStepsPersons.test_strict_funnel_person_recordings.5
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s2']
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel_time_to_convert.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel_time_to_convert.ambr
deleted file mode 100644
index 7b7efaa9c95a..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel_time_to_convert.ambr
+++ /dev/null
@@ -1,446 +0,0 @@
-# serializer version: 1
-# name: TestFunnelTimeToConvert.test_auto_bin_count_single_step
- '''
- WITH step_runs AS
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps)),
- histogram_params AS
- (SELECT ifNull(floor(min(step_1_average_conversion_time_inner)), 0) AS from_seconds,
- ifNull(ceil(max(step_1_average_conversion_time_inner)), 1) AS to_seconds,
- round(avg(step_1_average_conversion_time_inner), 2) AS average_conversion_time,
- count() AS sample_count,
- least(60, greatest(1, ceil(cbrt(ifNull(sample_count, 0))))) AS bin_count,
- ceil((to_seconds - from_seconds) / bin_count) AS bin_width_seconds_raw,
- if(bin_width_seconds_raw > 0, bin_width_seconds_raw, 60) AS bin_width_seconds
- FROM step_runs
- WHERE step_1_average_conversion_time_inner IS NOT NULL),
-
- (SELECT bin_width_seconds
- FROM histogram_params) AS bin_width_seconds,
-
- (SELECT bin_count
- FROM histogram_params) AS bin_count,
-
- (SELECT from_seconds
- FROM histogram_params) AS histogram_from_seconds,
-
- (SELECT to_seconds
- FROM histogram_params) AS histogram_to_seconds,
-
- (SELECT average_conversion_time
- FROM histogram_params) AS histogram_average_conversion_time
- SELECT bin_from_seconds,
- person_count,
- histogram_average_conversion_time AS average_conversion_time
- FROM
- (SELECT histogram_from_seconds + floor((step_1_average_conversion_time_inner - histogram_from_seconds) / bin_width_seconds) * bin_width_seconds AS bin_from_seconds,
- count() AS person_count
- FROM step_runs
- GROUP BY bin_from_seconds) results
- RIGHT OUTER JOIN
- (SELECT histogram_from_seconds + number * bin_width_seconds AS bin_from_seconds
- FROM system.numbers
- LIMIT ifNull(bin_count, 0) + 1) fill USING (bin_from_seconds)
- ORDER BY bin_from_seconds SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelTimeToConvert.test_basic_strict
- '''
- WITH step_runs AS
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN 2 PRECEDING AND 2 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC')
- AND (1=1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps)),
- histogram_params AS
- (SELECT ifNull(floor(min(step_1_average_conversion_time_inner)), 0) AS from_seconds,
- ifNull(ceil(max(step_1_average_conversion_time_inner)), 1) AS to_seconds,
- round(avg(step_1_average_conversion_time_inner), 2) AS average_conversion_time,
- count() AS sample_count,
- least(60, greatest(1, ceil(cbrt(ifNull(sample_count, 0))))) AS bin_count,
- ceil((to_seconds - from_seconds) / bin_count) AS bin_width_seconds_raw,
- if(bin_width_seconds_raw > 0, bin_width_seconds_raw, 60) AS bin_width_seconds
- FROM step_runs
- WHERE step_1_average_conversion_time_inner IS NOT NULL),
-
- (SELECT bin_width_seconds
- FROM histogram_params) AS bin_width_seconds,
-
- (SELECT bin_count
- FROM histogram_params) AS bin_count,
-
- (SELECT from_seconds
- FROM histogram_params) AS histogram_from_seconds,
-
- (SELECT to_seconds
- FROM histogram_params) AS histogram_to_seconds,
-
- (SELECT average_conversion_time
- FROM histogram_params) AS histogram_average_conversion_time
- SELECT bin_from_seconds,
- person_count,
- histogram_average_conversion_time AS average_conversion_time
- FROM
- (SELECT histogram_from_seconds + floor((step_1_average_conversion_time_inner - histogram_from_seconds) / bin_width_seconds) * bin_width_seconds AS bin_from_seconds,
- count() AS person_count
- FROM step_runs
- GROUP BY bin_from_seconds) results
- RIGHT OUTER JOIN
- (SELECT histogram_from_seconds + number * bin_width_seconds AS bin_from_seconds
- FROM system.numbers
- LIMIT ifNull(bin_count, 0) + 1) fill USING (bin_from_seconds)
- ORDER BY bin_from_seconds SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelTimeToConvert.test_basic_unordered
- '''
- WITH step_runs AS
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step two', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step three', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step one', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step three', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step one', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step two', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-06-07 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-06-13 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps)),
- histogram_params AS
- (SELECT ifNull(floor(min(step_1_average_conversion_time_inner)), 0) AS from_seconds,
- ifNull(ceil(max(step_1_average_conversion_time_inner)), 1) AS to_seconds,
- round(avg(step_1_average_conversion_time_inner), 2) AS average_conversion_time,
- count() AS sample_count,
- least(60, greatest(1, ceil(cbrt(ifNull(sample_count, 0))))) AS bin_count,
- ceil((to_seconds - from_seconds) / bin_count) AS bin_width_seconds_raw,
- if(bin_width_seconds_raw > 0, bin_width_seconds_raw, 60) AS bin_width_seconds
- FROM step_runs
- WHERE step_1_average_conversion_time_inner IS NOT NULL),
-
- (SELECT bin_width_seconds
- FROM histogram_params) AS bin_width_seconds,
-
- (SELECT bin_count
- FROM histogram_params) AS bin_count,
-
- (SELECT from_seconds
- FROM histogram_params) AS histogram_from_seconds,
-
- (SELECT to_seconds
- FROM histogram_params) AS histogram_to_seconds,
-
- (SELECT average_conversion_time
- FROM histogram_params) AS histogram_average_conversion_time
- SELECT bin_from_seconds,
- person_count,
- histogram_average_conversion_time AS average_conversion_time
- FROM
- (SELECT histogram_from_seconds + floor((step_1_average_conversion_time_inner - histogram_from_seconds) / bin_width_seconds) * bin_width_seconds AS bin_from_seconds,
- count() AS person_count
- FROM step_runs
- GROUP BY bin_from_seconds) results
- RIGHT OUTER JOIN
- (SELECT histogram_from_seconds + number * bin_width_seconds AS bin_from_seconds
- FROM system.numbers
- LIMIT ifNull(bin_count, 0) + 1) fill USING (bin_from_seconds)
- ORDER BY bin_from_seconds SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel_trends.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel_trends.ambr
deleted file mode 100644
index 985164cc6965..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel_trends.ambr
+++ /dev/null
@@ -1,363 +0,0 @@
-# serializer version: 1
-# name: TestFunnelTrends.test_timezones_trends
- '''
-
- SELECT entrance_period_start,
- reached_from_step_count,
- reached_to_step_count,
- if(reached_from_step_count > 0, round(reached_to_step_count / reached_from_step_count * 100, 2), 0) AS conversion_rate
- FROM
- (SELECT entrance_period_start,
- countIf(steps_completed >= 1) AS reached_from_step_count,
- countIf(steps_completed >= 3) AS reached_to_step_count
- FROM
- (SELECT aggregation_target,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS entrance_period_start,
- max(steps) AS steps_completed
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-04-30 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-04-30 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1)
- GROUP BY aggregation_target,
- entrance_period_start)
- GROUP BY entrance_period_start) data
- RIGHT OUTER JOIN
- (SELECT toStartOfDay(toDateTime('2021-04-30 00:00:00', 'UTC')) + toIntervalDay(number) AS entrance_period_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2021-04-30 00:00:00', 'UTC')), toStartOfDay(toDateTime('2021-05-07 00:00:00', 'UTC'))) + 1) AS period_offsets) fill USING (entrance_period_start)
- ORDER BY entrance_period_start ASC
- '''
-# ---
-# name: TestFunnelTrends.test_timezones_trends.1
- '''
-
- SELECT entrance_period_start,
- reached_from_step_count,
- reached_to_step_count,
- if(reached_from_step_count > 0, round(reached_to_step_count / reached_from_step_count * 100, 2), 0) AS conversion_rate
- FROM
- (SELECT entrance_period_start,
- countIf(steps_completed >= 1) AS reached_from_step_count,
- countIf(steps_completed >= 3) AS reached_to_step_count
- FROM
- (SELECT aggregation_target,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'US/Pacific')) AS entrance_period_start,
- max(steps) AS steps_completed
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'US/Pacific') >= toDateTime('2021-04-30 00:00:00', 'US/Pacific')
- AND toTimeZone(timestamp, 'US/Pacific') <= toDateTime('2021-05-07 23:59:59', 'US/Pacific'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'US/Pacific') >= toDateTime('2021-04-30 00:00:00', 'US/Pacific')
- AND toTimeZone(timestamp, 'US/Pacific') <= toDateTime('2021-05-07 23:59:59', 'US/Pacific')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1)
- GROUP BY aggregation_target,
- entrance_period_start)
- GROUP BY entrance_period_start) data
- RIGHT OUTER JOIN
- (SELECT toStartOfDay(toDateTime('2021-04-30 00:00:00', 'US/Pacific')) + toIntervalDay(number) AS entrance_period_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2021-04-30 00:00:00', 'US/Pacific')), toStartOfDay(toDateTime('2021-05-07 00:00:00', 'US/Pacific'))) + 1) AS period_offsets) fill USING (entrance_period_start)
- ORDER BY entrance_period_start ASC
- '''
-# ---
-# name: TestFunnelTrends.test_week_interval
- '''
-
- SELECT entrance_period_start,
- reached_from_step_count,
- reached_to_step_count,
- if(reached_from_step_count > 0, round(reached_to_step_count / reached_from_step_count * 100, 2), 0) AS conversion_rate
- FROM
- (SELECT entrance_period_start,
- countIf(steps_completed >= 1) AS reached_from_step_count,
- countIf(steps_completed >= 3) AS reached_to_step_count
- FROM
- (SELECT aggregation_target,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC'), 0) AS entrance_period_start,
- max(steps) AS steps_completed
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1)
- GROUP BY aggregation_target,
- entrance_period_start)
- GROUP BY entrance_period_start) data
- RIGHT OUTER JOIN
- (SELECT toStartOfWeek(toDateTime('2021-05-01 00:00:00', 'UTC'), 0) + toIntervalWeek(number) AS entrance_period_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2021-05-01 00:00:00', 'UTC'), 0), toStartOfWeek(toDateTime('2021-05-07 00:00:00', 'UTC'), 0)) + 1) AS period_offsets) fill USING (entrance_period_start)
- ORDER BY entrance_period_start ASC
- '''
-# ---
-# name: TestFunnelTrends.test_week_interval.1
- '''
-
- SELECT aggregation_target AS actor_id
- FROM
- (SELECT aggregation_target,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC'), 0) AS entrance_period_start,
- max(steps) AS steps_completed
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 7 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 7 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- latest_1,
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1)
- WHERE toDateTime(entrance_period_start) = '2021-04-25 00:00:00'
- GROUP BY aggregation_target,
- entrance_period_start)
- WHERE steps_completed >= 3
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel_trends_persons.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel_trends_persons.ambr
deleted file mode 100644
index 04ae108f93db..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel_trends_persons.ambr
+++ /dev/null
@@ -1,491 +0,0 @@
-# serializer version: 1
-# name: TestFunnelTrendsPersons.test_funnel_trend_persons_returns_recordings
- '''
-
- SELECT aggregation_target AS actor_id,
- step_1_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS entrance_period_start,
- max(steps) AS steps_completed ,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2,
- if(latest_2 < latest_1, NULL, "uuid_2") as "uuid_2",
- if(latest_2 < latest_1, NULL, "$session_id_2") as "$session_id_2",
- if(latest_2 < latest_1, NULL, "$window_id_2") as "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1)
- WHERE toDateTime(entrance_period_start) = '2021-05-01 00:00:00'
- GROUP BY aggregation_target,
- entrance_period_start)
- WHERE steps_completed >= 2
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelTrendsPersons.test_funnel_trend_persons_returns_recordings.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s1b']
- AND min_first_timestamp >= '2021-04-30 00:00:00'
- AND max_last_timestamp <= '2021-05-08 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestFunnelTrendsPersons.test_funnel_trend_persons_with_drop_off
- '''
-
- SELECT aggregation_target AS actor_id,
- final_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS entrance_period_start,
- max(steps) AS steps_completed ,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2,
- if(latest_2 < latest_1, NULL, "uuid_2") as "uuid_2",
- if(latest_2 < latest_1, NULL, "$session_id_2") as "$session_id_2",
- if(latest_2 < latest_1, NULL, "$window_id_2") as "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1)
- WHERE toDateTime(entrance_period_start) = '2021-05-01 00:00:00'
- GROUP BY aggregation_target,
- entrance_period_start)
- WHERE steps_completed >= 1
- AND steps_completed < 3
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelTrendsPersons.test_funnel_trend_persons_with_drop_off.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s1a']
- AND min_first_timestamp >= '2021-04-30 00:00:00'
- AND max_last_timestamp <= '2021-05-08 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestFunnelTrendsPersons.test_funnel_trend_persons_with_no_to_step
- '''
-
- SELECT aggregation_target AS actor_id,
- final_matching_events as matching_events
- FROM
- (SELECT aggregation_target,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS entrance_period_start,
- max(steps) AS steps_completed ,
- groupArray(10)(step_0_matching_event) as step_0_matching_events,
- groupArray(10)(step_1_matching_event) as step_1_matching_events,
- groupArray(10)(step_2_matching_event) as step_2_matching_events,
- groupArray(10)(final_matching_event) as final_matching_events
- FROM
- (SELECT *,
- if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY
- AND latest_1 <= latest_2
- AND latest_2 <= latest_0 + INTERVAL 14 DAY, 3, if(latest_0 <= latest_1
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, 2, 1)) AS steps ,
- if(isNotNull(latest_1)
- AND latest_1 <= latest_0 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_0), toDateTime(latest_1)), NULL) step_1_conversion_time,
- if(isNotNull(latest_2)
- AND latest_2 <= latest_1 + INTERVAL 14 DAY, dateDiff('second', toDateTime(latest_1), toDateTime(latest_2)), NULL) step_2_conversion_time,
- ("latest_0",
- "uuid_0",
- "$session_id_0",
- "$window_id_0") as step_0_matching_event,
- ("latest_1",
- "uuid_1",
- "$session_id_1",
- "$window_id_1") as step_1_matching_event,
- ("latest_2",
- "uuid_2",
- "$session_id_2",
- "$window_id_2") as step_2_matching_event,
- if(isNull(latest_0),(null, null, null, null),if(isNull(latest_1), step_0_matching_event, if(isNull(latest_2), step_1_matching_event, step_2_matching_event))) as final_matching_event
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- latest_1,
- "uuid_1",
- "$session_id_1",
- "$window_id_1",
- step_2,
- if(latest_2 < latest_1, NULL, latest_2) as latest_2,
- if(latest_2 < latest_1, NULL, "uuid_2") as "uuid_2",
- if(latest_2 < latest_1, NULL, "$session_id_2") as "$session_id_2",
- if(latest_2 < latest_1, NULL, "$window_id_2") as "$window_id_2"
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-05-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-05-07 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))))
- WHERE step_0 = 1)
- WHERE toDateTime(entrance_period_start) = '2021-05-01 00:00:00'
- GROUP BY aggregation_target,
- entrance_period_start)
- WHERE steps_completed >= 3
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelTrendsPersons.test_funnel_trend_persons_with_no_to_step.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s1c']
- AND min_first_timestamp >= '2021-04-30 00:00:00'
- AND max_last_timestamp <= '2021-05-08 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel_unordered.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel_unordered.ambr
deleted file mode 100644
index 7937435857eb..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel_unordered.ambr
+++ /dev/null
@@ -1,496 +0,0 @@
-# serializer version: 1
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen.1
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen.2
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- prop
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([[''], ['Mac'], ['Chrome'], ['Safari']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy'
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([[''], ['Mac'], ['Chrome'], ['Safari']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'buy'
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', ''))), 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'sign up', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step.1
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step.2
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- prop
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([[''], ['Mac'], ['Chrome'], ['Safari']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy'
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', ''))), 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS prop_basic,
- if(step_0 = 1, prop_basic, []) as prop_0,
- if(step_1 = 1, prop_basic, []) as prop_1,
- prop_1 as prop_final,
- groupUniqArray(prop_final) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)) ARRAY
- JOIN prop_vals as prop
- WHERE prop != []))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([[''], ['Mac'], ['Chrome'], ['Safari']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'buy'
- AND (has(['xyz'], replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', ''))), 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'sign up', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')) AS prop_basic,
- if(step_0 = 1, prop_basic, []) as prop_0,
- if(step_1 = 1, prop_basic, []) as prop_1,
- prop_1 as prop_final,
- groupUniqArray(prop_final) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1)) ARRAY
- JOIN prop_vals as prop
- WHERE prop != []))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_step_multiple_breakdown_snapshot
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_step_multiple_breakdown_snapshot.1
- '''
-
- SELECT array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestFunnelUnorderedStepsBreakdown.test_funnel_step_multiple_breakdown_snapshot.2
- '''
-
- SELECT countIf(steps = 1) step_1,
- countIf(steps = 2) step_2,
- avg(step_1_average_conversion_time_inner) step_1_average_conversion_time,
- median(step_1_median_conversion_time_inner) step_1_median_conversion_time,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- prop
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target, prop) as max_steps,
- step_1_conversion_time,
- prop
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([['', ''], ['alakazam', ''], ['Safari', 'xyz'], ['Mac', ''], ['Chrome', 'xyz'], ['0', '0'], ['', 'no-mac']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['','']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'sign up', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'buy', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', '')) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1))))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- step_1,
- min(latest_1) over (PARTITION by aggregation_target, prop
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1 ,
- if(has([['', ''], ['alakazam', ''], ['Safari', 'xyz'], ['Mac', ''], ['Chrome', 'xyz'], ['0', '0'], ['', 'no-mac']], prop), prop, ['Other']) as prop
- FROM
- (SELECT *,
- if(notEmpty(arrayFilter(x -> notEmpty(x), prop_vals)), prop_vals, ['','']) as prop
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'buy', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(event = 'sign up', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- array(replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''), replaceRegexpAll(JSONExtractRaw(properties, '$version'), '^"|"$', '')) AS prop_basic,
- prop_basic as prop_attribution,
- argMinIf(prop_attribution, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_attribution))) over (PARTITION by aggregation_target) as prop_vals
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['buy', 'sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1))))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps,
- prop
- HAVING steps = max(max_steps))
- GROUP BY prop
- ORDER BY step_2 DESC,
- step_1 DESC
- LIMIT 100
- '''
-# ---
diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel_unordered_persons.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel_unordered_persons.ambr
deleted file mode 100644
index b28c7cf90e4a..000000000000
--- a/posthog/queries/funnels/test/__snapshots__/test_funnel_unordered_persons.ambr
+++ /dev/null
@@ -1,268 +0,0 @@
-# serializer version: 1
-# name: TestFunnelUnorderedStepsPersons.test_unordered_funnel_does_not_return_recordings
- '''
-
- SELECT aggregation_target AS actor_id,
- array() as matching_events
- FROM
- (SELECT aggregation_target,
- steps,
- avg(step_1_conversion_time) step_1_average_conversion_time_inner,
- avg(step_2_conversion_time) step_2_average_conversion_time_inner,
- median(step_1_conversion_time) step_1_median_conversion_time_inner,
- median(step_2_conversion_time) step_2_median_conversion_time_inner
- FROM
- (SELECT aggregation_target,
- steps,
- max(steps) over (PARTITION BY aggregation_target) as max_steps,
- step_1_conversion_time,
- step_2_conversion_time
- FROM
- (SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step one', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step two', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step three', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step two', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step three', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step one', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))
- WHERE step_0 = 1
- UNION ALL SELECT *,
- arraySort([latest_0,latest_1,latest_2]) as event_times,
- arraySum([if(latest_0 < latest_1 AND latest_1 <= latest_0 + INTERVAL 7 DAY, 1, 0),if(latest_0 < latest_2 AND latest_2 <= latest_0 + INTERVAL 7 DAY, 1, 0), 1]) AS steps ,
- arraySort([latest_0,latest_1,latest_2]) as conversion_times,
- if(isNotNull(conversion_times[2])
- AND conversion_times[2] <= conversion_times[1] + INTERVAL 7 DAY, dateDiff('second', conversion_times[1], conversion_times[2]), NULL) step_1_conversion_time,
- if(isNotNull(conversion_times[3])
- AND conversion_times[3] <= conversion_times[2] + INTERVAL 7 DAY, dateDiff('second', conversion_times[2], conversion_times[3]), NULL) step_2_conversion_time
- FROM
- (SELECT aggregation_target, timestamp, step_0,
- latest_0,
- "uuid_0",
- "$session_id_0",
- "$window_id_0",
- step_1,
- min(latest_1) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_1,
- last_value("uuid_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_1",
- last_value("$session_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_1",
- last_value("$window_id_1") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_1",
- step_2,
- min(latest_2) over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) latest_2,
- last_value("uuid_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "uuid_2",
- last_value("$session_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$session_id_2",
- last_value("$window_id_2") over (PARTITION by aggregation_target
- ORDER BY timestamp DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 0 PRECEDING) "$window_id_2"
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as aggregation_target,
- e.uuid AS uuid,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- if(event = 'step three', 1, 0) as step_0,
- if(step_0 = 1, timestamp, null) as latest_0,
- if(step_0 = 1, "uuid", null) as "uuid_0",
- if(step_0 = 1, "$session_id", null) as "$session_id_0",
- if(step_0 = 1, "$window_id", null) as "$window_id_0",
- if(event = 'step one', 1, 0) as step_1,
- if(step_1 = 1, timestamp, null) as latest_1,
- if(step_1 = 1, "uuid", null) as "uuid_1",
- if(step_1 = 1, "$session_id", null) as "$session_id_1",
- if(step_1 = 1, "$window_id", null) as "$window_id_1",
- if(event = 'step two', 1, 0) as step_2,
- if(step_2 = 1, timestamp, null) as latest_2,
- if(step_2 = 1, "uuid", null) as "uuid_2",
- if(step_2 = 1, "$session_id", null) as "$session_id_2",
- if(step_2 = 1, "$window_id", null) as "$window_id_2"
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event IN ['step one', 'step three', 'step two']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-08 23:59:59', 'UTC')
- AND (step_0 = 1
- OR step_1 = 1
- OR step_2 = 1)))
- WHERE step_0 = 1))
- GROUP BY aggregation_target,
- steps
- HAVING steps = max(max_steps))
- WHERE steps IN [1, 2, 3]
- ORDER BY aggregation_target
- LIMIT 100
- OFFSET 0 SETTINGS max_ast_elements=1000000,
- max_expanded_ast_elements=1000000
- '''
-# ---
-# name: TestFunnelUnorderedStepsPersons.test_unordered_funnel_does_not_return_recordings.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in []
- AND min_first_timestamp >= '2020-12-31 00:00:00'
- AND max_last_timestamp <= '2021-01-09 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
diff --git a/posthog/queries/funnels/test/breakdown_cases.py b/posthog/queries/funnels/test/breakdown_cases.py
deleted file mode 100644
index d383ab43ae0f..000000000000
--- a/posthog/queries/funnels/test/breakdown_cases.py
+++ /dev/null
@@ -1,2725 +0,0 @@
-import uuid
-from dataclasses import dataclass
-from datetime import datetime
-from string import ascii_lowercase
-from typing import Any, Literal, Optional, Union
-
-from posthog.test.base import APIBaseTest, also_test_with_materialized_columns, snapshot_clickhouse_queries
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.filters import Filter
-from posthog.queries.breakdown_props import ALL_USERS_COHORT_ID
-from posthog.queries.funnels.funnel_unordered import ClickhouseFunnelUnordered
-from posthog.test.test_journeys import journeys_for
-
-from products.cohorts.backend.models.cohort import Cohort
-
-
-@dataclass(frozen=True)
-class FunnelStepResult:
- name: str
- count: int
- breakdown: Union[list[str], str]
- average_conversion_time: Optional[float] = None
- median_conversion_time: Optional[float] = None
- type: Literal["events", "actions"] = "events"
- action_id: Optional[str] = None
-
-
-def funnel_breakdown_test_factory(Funnel, FunnelPerson, _create_event, _create_action, _create_person):
- class TestFunnelBreakdown(APIBaseTest):
- def _get_actor_ids_at_step(self, filter, funnel_step, breakdown_value=None):
- person_filter = filter.shallow_clone({"funnel_step": funnel_step, "funnel_step_breakdown": breakdown_value})
- _, serialized_result, _ = FunnelPerson(person_filter, self.team).get_actors()
-
- return [val["id"] for val in serialized_result]
-
- def _assert_funnel_breakdown_result_is_correct(self, result, steps: list[FunnelStepResult]):
- def funnel_result(step: FunnelStepResult, order: int) -> dict[str, Any]:
- return {
- "action_id": step.name if step.type == "events" else step.action_id,
- "name": step.name,
- "custom_name": None,
- "order": order,
- "people": [],
- "count": step.count,
- "type": step.type,
- "average_conversion_time": step.average_conversion_time,
- "median_conversion_time": step.median_conversion_time,
- "breakdown": step.breakdown,
- "breakdown_value": step.breakdown,
- **(
- {
- "action_id": None,
- "name": f"Completed {order + 1} step{'s' if order > 0 else ''}",
- }
- if Funnel == ClickhouseFunnelUnordered
- else {}
- ),
- }
-
- step_results = []
- for index, step_result in enumerate(steps):
- step_results.append(funnel_result(step_result, index))
-
- assert_funnel_results_equal(result, step_results)
-
- @also_test_with_materialized_columns(["$browser", "$browser_version"])
- def test_funnel_step_multi_property_breakdown_event(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser", "$browser_version"],
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- journey = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {
- "key": "val",
- "$browser": "Chrome",
- "$browser_version": 95,
- },
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {
- "key": "val",
- "$browser": "Chrome",
- "$browser_version": 95,
- },
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {
- "key": "val",
- "$browser": "Chrome",
- "$browser_version": 95,
- },
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {
- "key": "val",
- "$browser": "Safari",
- "$browser_version": 15,
- },
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {
- "key": "val",
- "$browser": "Safari",
- "$browser_version": 15,
- },
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {
- "key": "val",
- "$browser": "Safari",
- "$browser_version": 14,
- },
- }
- ],
- }
-
- people = journeys_for(events_by_person=journey, team=self.team)
-
- result = funnel.run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="sign up", breakdown=["Safari", "14"], count=1),
- FunnelStepResult(name="play movie", breakdown=["Safari", "14"], count=0),
- FunnelStepResult(name="buy", breakdown=["Safari", "14"], count=0),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Safari", "14"]),
- [people["person3"].uuid],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, ["Safari", "14"]), [])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["Safari", "15"], count=1),
- FunnelStepResult(
- name="play movie",
- breakdown=["Safari", "15"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(name="buy", breakdown=["Safari", "15"], count=0),
- ],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Safari", "15"]),
- [people["person2"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, ["Safari", "15"]),
- [people["person2"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=["Chrome", "95"], count=1),
- FunnelStepResult(
- name="play movie",
- breakdown=["Chrome", "95"],
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome", "95"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Chrome", "95"]),
- [people["person1"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, ["Chrome", "95"]),
- [people["person1"].uuid],
- )
-
- @also_test_with_materialized_columns(["$browser"])
- def test_funnel_step_breakdown_event_with_string_only_breakdown(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": "$browser",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- journey = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"key": "val", "$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"key": "val", "$browser": "Chrome"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"key": "val", "$browser": "Chrome"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"key": "val", "$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"key": "val", "$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"key": "val", "$browser": "Safari"},
- }
- ],
- }
-
- people = journeys_for(events_by_person=journey, team=self.team)
-
- result = funnel.run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=["Chrome"], count=1),
- FunnelStepResult(
- name="play movie",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Chrome"),
- [people["person1"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Chrome"),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["Safari"], count=2),
- FunnelStepResult(
- name="play movie",
- breakdown=["Safari"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(name="buy", breakdown=["Safari"], count=0),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person2"].uuid, people["person3"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Safari"),
- [people["person2"].uuid],
- )
-
- @also_test_with_materialized_columns(["$browser"])
- def test_funnel_step_breakdown_event(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- journey = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"key": "val", "$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"key": "val", "$browser": "Chrome"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"key": "val", "$browser": "Chrome"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"key": "val", "$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"key": "val", "$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"key": "val", "$browser": "Safari"},
- }
- ],
- }
-
- people = journeys_for(events_by_person=journey, team=self.team)
-
- result = funnel.run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=["Chrome"], count=1),
- FunnelStepResult(
- name="play movie",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Chrome"),
- [people["person1"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Chrome"),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["Safari"], count=2),
- FunnelStepResult(
- name="play movie",
- breakdown=["Safari"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(name="buy", breakdown=["Safari"], count=0),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person2"].uuid, people["person3"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Safari"),
- [people["person2"].uuid],
- )
-
- @also_test_with_materialized_columns(["$browser"])
- def test_funnel_step_breakdown_event_with_other(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_limit": 1,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"$browser": "Chrome"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Safari"},
- }
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "random"},
- }
- ],
- "person5": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": "another one"},
- }
- ],
- }
-
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sort_breakdown_funnel_results(result)
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["Safari"], count=2),
- FunnelStepResult(
- name="play movie",
- breakdown=["Safari"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(name="buy", breakdown=["Safari"], count=0),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person2"].uuid, people["person3"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Safari"),
- [people["person2"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=["Other"], count=3),
- FunnelStepResult(
- name="play movie",
- breakdown=["Other"],
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown=["Other"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Other"),
- [
- people["person1"].uuid,
- people["person4"].uuid,
- people["person5"].uuid,
- ],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Other"),
- [people["person1"].uuid],
- )
-
- @also_test_with_materialized_columns(["$browser"])
- def test_funnel_step_breakdown_event_no_type(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown": ["$browser"],
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"$browser": "Chrome"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Safari"},
- }
- ],
- }
-
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=["Chrome"], count=1),
- FunnelStepResult(
- name="play movie",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Chrome"),
- [people["person1"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Chrome"),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["Safari"], count=2),
- FunnelStepResult(
- name="play movie",
- breakdown=["Safari"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(name="buy", breakdown=["Safari"], count=0),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person2"].uuid, people["person3"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Safari"),
- [people["person2"].uuid],
- )
-
- @also_test_with_materialized_columns(person_properties=["$browser"])
- def test_funnel_step_breakdown_person(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "person",
- "breakdown": ["$browser"],
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- person1 = _create_person(
- distinct_ids=["person1"],
- team_id=self.team.pk,
- properties={"$browser": "Chrome"},
- )
- person2 = _create_person(
- distinct_ids=["person2"],
- team_id=self.team.pk,
- properties={"$browser": "Safari"},
- )
-
- peoples_journeys = {
- "person1": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 12)},
- {"event": "play movie", "timestamp": datetime(2020, 1, 1, 13)},
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 15)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 14)},
- {"event": "play movie", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- journeys_for(peoples_journeys, self.team, create_people=False)
-
- result = funnel.run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=["Chrome"], count=1),
- FunnelStepResult(
- name="play movie",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=3600.0,
- median_conversion_time=3600.0,
- ),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=7200,
- median_conversion_time=7200,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Chrome"), [person1.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, "Chrome"), [person1.uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["Safari"], count=1),
- FunnelStepResult(
- name="play movie",
- breakdown=["Safari"],
- count=1,
- average_conversion_time=7200.0,
- median_conversion_time=7200.0,
- ),
- FunnelStepResult(name="buy", breakdown=["Safari"], count=0),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Safari"), [person2.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 3, "Safari"), [])
-
- @also_test_with_materialized_columns(["some_breakdown_val"])
- def test_funnel_step_breakdown_limit(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["some_breakdown_val"],
- "breakdown_limit": 5,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- events_by_person = {}
- for num in range(10):
- for i in range(num):
- person_id = f"person_{num}_{i}"
- events_by_person[person_id] = [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"some_breakdown_val": str(num)},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"some_breakdown_val": str(num)},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"some_breakdown_val": str(num)},
- },
- ]
- journeys_for(events_by_person, self.team)
-
- result = funnel.run()
-
- # assert that we give 5 at a time at most and that those values are the most popular ones
- breakdown_vals = sorted([res[0]["breakdown"] for res in result])
- self.assertEqual([["5"], ["6"], ["7"], ["8"], ["9"], ["Other"]], breakdown_vals)
-
- @also_test_with_materialized_columns(["some_breakdown_val"])
- def test_funnel_step_custom_breakdown_limit_with_nulls(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown_limit": 3,
- "breakdown": ["some_breakdown_val"],
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- events_by_person = {}
- for num in range(5):
- for i in range(num):
- person_id = f"person_{num}_{i}"
- events_by_person[person_id] = [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"some_breakdown_val": str(num)},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"some_breakdown_val": str(num)},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"some_breakdown_val": str(num)},
- },
- ]
-
- # no breakdown value for this guy
- events_by_person["person_null"] = [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 12)},
- {"event": "play movie", "timestamp": datetime(2020, 1, 1, 13)},
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 15)},
- ]
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
-
- breakdown_vals = sorted([res[0]["breakdown"] for res in result])
- self.assertEqual([["2"], ["3"], ["4"], ["Other"]], breakdown_vals)
- # skipped 1 and '' because the limit was 3.
- self.assertTrue(people["person_null"].uuid in self._get_actor_ids_at_step(filter, 1, "Other"))
-
- @also_test_with_materialized_columns(["some_breakdown_val"])
- def test_funnel_step_custom_breakdown_limit_with_nulls_included(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown_limit": 6,
- "breakdown": ["some_breakdown_val"],
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- events_by_person = {}
- for num in range(5):
- for i in range(num):
- person_id = f"person_{num}_{i}"
- events_by_person[person_id] = [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"some_breakdown_val": str(num)},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"some_breakdown_val": str(num)},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"some_breakdown_val": str(num)},
- },
- ]
-
- # no breakdown value for this guy
- events_by_person["person_null"] = [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 12)},
- {"event": "play movie", "timestamp": datetime(2020, 1, 1, 13)},
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 15)},
- ]
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
-
- breakdown_vals = sorted([res[0]["breakdown"] for res in result])
- self.assertEqual([[""], ["1"], ["2"], ["3"], ["4"]], breakdown_vals)
- # included 1 and '' because the limit was 6.
-
- for i in range(1, 5):
- self.assertEqual(len(self._get_actor_ids_at_step(filter, 3, str(i))), i)
-
- self.assertEqual([people["person_null"].uuid], self._get_actor_ids_at_step(filter, 1, ""))
- self.assertEqual([people["person_null"].uuid], self._get_actor_ids_at_step(filter, 3, ""))
-
- @also_test_with_materialized_columns(["$browser"])
- def test_funnel_step_breakdown_event_single_person_multiple_breakdowns(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "0",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$browser": "Safari"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- # mixed property type!
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- ]
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0], [FunnelStepResult(name="sign up", breakdown=["0"], count=1)]
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "0"), [people["person1"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [FunnelStepResult(name="sign up", count=1, breakdown=["Chrome"])],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Chrome"),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [FunnelStepResult(name="sign up", count=1, breakdown=["Mac"])],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Mac"), [people["person1"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[3],
- [FunnelStepResult(name="sign up", count=1, breakdown=["Safari"])],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person1"].uuid],
- )
-
- def test_funnel_step_breakdown_event_single_person_events_with_multiple_properties(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "all_events",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- people = journeys_for(
- {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 12, 30),
- "properties": {"$browser": "Safari"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Safari"},
- },
- ]
- },
- self.team,
- )
- result = funnel.run()
-
- self.assertEqual(len(result), 2)
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Chrome"]),
- FunnelStepResult(name="play movie", count=0, breakdown=["Chrome"]),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Chrome"),
- [people["person1"].uuid],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, "Chrome"), [])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Safari"]),
- FunnelStepResult(
- name="play movie",
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- breakdown=["Safari"],
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person1"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, "Safari"),
- [people["person1"].uuid],
- )
-
- @also_test_with_materialized_columns(person_properties=["key"], verify_no_jsonextract=False)
- def test_funnel_cohort_breakdown(self):
- # This caused some issues with SQL parsing
- _create_person(
- distinct_ids=[f"person1"],
- team_id=self.team.pk,
- properties={"key": "value"},
- )
- people = journeys_for(
- {"person1": [{"event": "sign up", "timestamp": datetime(2020, 1, 2, 12)}]},
- self.team,
- create_people=False,
- )
-
- cohort = Cohort.objects.create(
- team=self.team,
- name="test_cohort",
- groups=[{"properties": [{"key": "key", "value": "value", "type": "person"}]}],
- )
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "cohort",
- "breakdown": ["all", cohort.pk],
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": 0,
- # first touch means same user can't be in 'all' and the other cohort both
- }
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
- self.assertEqual(len(result[0]), 3)
- self.assertEqual(result[0][0]["breakdown"], "all users")
- self.assertEqual(len(result[1]), 3)
- self.assertEqual(result[1][0]["breakdown"], "test_cohort")
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, cohort.pk),
- [people["person1"].uuid],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, cohort.pk), [])
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ALL_USERS_COHORT_ID),
- [people["person1"].uuid],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, ALL_USERS_COHORT_ID), [])
-
- # non array
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "cohort",
- "breakdown": cohort.pk,
- }
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
- self.assertEqual(len(result[0]), 3)
- self.assertEqual(result[0][0]["breakdown"], "test_cohort")
- self.assertEqual(result[0][0]["breakdown_value"], cohort.pk)
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, cohort.pk),
- [people["person1"].uuid],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, cohort.pk), [])
-
- def test_basic_funnel_default_funnel_days_breakdown_event(self):
- events_by_person = {
- "user_1": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$current_url": "https://posthog.com/docs/x"},
- },
- {
- "event": "paid",
- "timestamp": datetime(2020, 1, 10, 14),
- "properties": {"$current_url": "https://posthog.com/docs/x"},
- },
- ]
- }
- # Dummy events to make sure that breakdown is not confused
- # It was confused before due to the nature of fetching breakdown values with a LIMIT based on value popularity
- # See https://github.com/PostHog/posthog/pull/5496
- for current_url_letter in ascii_lowercase[:20]:
- # Twenty dummy breakdown values
- for _ in range(2):
- # Each twice, so that the breakdown values from dummy events rank higher in raw order
- # This test makes sure that events are prefiltered properly to avoid problems with this raw order
- events_by_person["user_1"].append(
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$current_url": f"https://posthog.com/blog/{current_url_letter}"},
- }
- )
-
- journeys_for(events_by_person, self.team)
-
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [
- {
- "key": "$current_url",
- "operator": "icontains",
- "type": "event",
- "value": "https://posthog.com/docs",
- }
- ],
- },
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- "breakdown": ["$current_url"],
- "breakdown_type": "event",
- }
-
- result = Funnel(Filter(data=filters), self.team).run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(
- name="user signed up",
- count=1,
- breakdown=["https://posthog.com/docs/x"],
- ),
- FunnelStepResult(
- name="paid",
- count=1,
- average_conversion_time=691200.0,
- median_conversion_time=691200.0,
- breakdown=["https://posthog.com/docs/x"],
- ),
- ],
- )
-
- @also_test_with_materialized_columns(["$current_url"])
- def test_basic_funnel_default_funnel_days_breakdown_action(self):
- # Same case as test_basic_funnel_default_funnel_days_breakdown_event but with an action
- user_signed_up_action = _create_action(name="user signed up", event="user signed up", team=self.team)
-
- events_by_person = {
- "user_1": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$current_url": "https://posthog.com/docs/x"},
- },
- {
- "event": "paid",
- "timestamp": datetime(2020, 1, 10, 14),
- "properties": {"$current_url": "https://posthog.com/docs/x"},
- },
- ]
- }
- for current_url_letter in ascii_lowercase[:20]:
- for _ in range(2):
- events_by_person["user_1"].append(
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$current_url": f"https://posthog.com/blog/{current_url_letter}"},
- }
- )
-
- journeys_for(events_by_person, self.team)
-
- filters = {
- "actions": [
- {
- "id": user_signed_up_action.id,
- "order": 0,
- "properties": [
- {
- "key": "$current_url",
- "operator": "icontains",
- "type": "event",
- "value": "https://posthog.com/docs",
- }
- ],
- }
- ],
- "events": [{"id": "paid", "type": "events", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- "breakdown": ["$current_url"],
- "breakdown_type": "event",
- }
-
- result = Funnel(Filter(data=filters), self.team).run()
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(
- name="user signed up",
- count=1,
- breakdown=["https://posthog.com/docs/x"],
- type="actions",
- action_id=user_signed_up_action.id,
- ),
- FunnelStepResult(
- name="paid",
- count=1,
- average_conversion_time=691200.0,
- median_conversion_time=691200.0,
- breakdown=["https://posthog.com/docs/x"],
- ),
- ],
- )
-
- def test_funnel_step_breakdown_with_first_touch_attribution(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "first_touch",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)},
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # first touch means alakazam is disregarded
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- # no properties dude, represented by ''
- "person5": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 15)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 5)
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=[""], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=[""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ""), [people["person5"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["0"], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["0"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "0"), [people["person4"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Chrome"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Chrome"),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[3],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Mac"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Mac"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Mac"), [people["person3"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[4],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Safari"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Safari"],
- count=1,
- average_conversion_time=86400,
- median_conversion_time=86400,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person2"].uuid],
- )
-
- def test_funnel_step_breakdown_with_last_touch_attribution(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "last_touch",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)},
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # last touch means 0 is disregarded
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "Alakazam"},
- },
- ],
- # no properties dude, represented by ''
- "person5": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 15)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 5)
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=[""], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=[""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ""), [people["person5"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["Alakazam"], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["Alakazam"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Alakazam"),
- [people["person4"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Chrome"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Chrome"),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[3],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Mac"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Mac"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Mac"), [people["person3"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[4],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Safari"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Safari"],
- count=1,
- average_conversion_time=86400,
- median_conversion_time=86400,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person2"].uuid],
- )
-
- def test_funnel_step_breakdown_with_step_attribution(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "0",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)},
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # step attribution means alakazam is valid when step = 1
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 4)
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=[""], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=[""],
- count=1,
- average_conversion_time=86400,
- median_conversion_time=86400,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ""), [people["person2"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["0"], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["0"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "0"), [people["person4"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Chrome"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Chrome"),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[3],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Mac"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Mac"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Mac"), [people["person3"].uuid])
-
- def test_funnel_step_breakdown_with_step_one_attribution(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "1",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)},
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # step attribution means alakazam is valid when step = 1
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 3)
- # Chrome and Mac goes away, Safari comes back
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=[""], count=2),
- FunnelStepResult(
- name="buy",
- breakdown=[""],
- count=2,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ""),
- [people["person1"].uuid, people["person3"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Safari"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Safari"],
- count=1,
- average_conversion_time=86400,
- median_conversion_time=86400,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "Safari"),
- [people["person2"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="sign up", breakdown=["alakazam"], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["alakazam"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "alakazam"),
- [people["person4"].uuid],
- )
-
- def test_funnel_step_multiple_breakdown_with_first_touch_attribution(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser", "$version"],
- "breakdown_attribution_type": "first_touch",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome", "$version": "xyz"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari", "$version": "xyz"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$version": "no-mac"},
- },
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0, "$version": 0},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- # no properties dude, represented by ''
- "person5": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 15)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 5)
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=["", ""], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["", ""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["", ""]),
- [people["person5"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["0", "0"], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["0", "0"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["0", "0"]),
- [people["person4"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Chrome", "xyz"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome", "xyz"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Chrome", "xyz"]),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[3],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Mac", ""]),
- FunnelStepResult(
- name="buy",
- breakdown=["Mac", ""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Mac", ""]),
- [people["person3"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[4],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Safari", "xyz"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Safari", "xyz"],
- count=1,
- average_conversion_time=86400,
- median_conversion_time=86400,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Safari", "xyz"]),
- [people["person2"].uuid],
- )
-
- def test_funnel_step_multiple_breakdown_with_first_touch_attribution_incomplete_funnel(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser", "$version"],
- "breakdown_attribution_type": "first_touch",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome", "$version": "xyz"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari", "$version": "xyz"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 15), "properties": {"$version": "no-mac"}},
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0, "$version": 0},
- },
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 16), "properties": {"$browser": "alakazam"}},
- ],
- # no properties dude, represented by ''
- "person5": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 15)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 5)
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=["", ""], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["", ""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["", ""]),
- [people["person5"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["0", "0"], count=1),
- FunnelStepResult(name="buy", breakdown=["0", "0"], count=0),
- ],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["0", "0"]),
- [people["person4"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Chrome", "xyz"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Chrome", "xyz"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Chrome", "xyz"]),
- [people["person1"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[3],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Mac", ""]),
- FunnelStepResult(name="buy", breakdown=["Mac", ""], count=0),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Mac", ""]),
- [people["person3"].uuid],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, ["Mac", ""]), [])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[4],
- [
- FunnelStepResult(name="sign up", count=1, breakdown=["Safari", "xyz"]),
- FunnelStepResult(
- name="buy",
- breakdown=["Safari", "xyz"],
- count=1,
- average_conversion_time=86400,
- median_conversion_time=86400,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ["Safari", "xyz"]),
- [people["person2"].uuid],
- )
-
- def test_funnel_step_breakdown_with_step_one_attribution_incomplete_funnel(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "1",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 13), "properties": {"$browser": "Safari"}}
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)}
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # step attribution means alakazam is valid when step = 1
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- # Breakdown by step_1 means funnel items that never reach step_1 are NULLed out
- self.assertEqual(len(result), 2)
- # Chrome and Mac and Safari goes away
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=[""], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=[""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ""), [people["person1"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["alakazam"], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["alakazam"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "alakazam"),
- [people["person4"].uuid],
- )
-
- def test_funnel_step_non_array_breakdown_with_step_one_attribution_incomplete_funnel(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": "$browser",
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "1",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 13), "properties": {"$browser": "Safari"}}
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)}
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # step attribution means alakazam is valid when step = 1
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- # Breakdown by step_1 means funnel items that never reach step_1 are NULLed out
- self.assertEqual(len(result), 2)
- # Chrome and Mac and Safari goes away
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="sign up", breakdown=[""], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=[""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ""), [people["person1"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="sign up", breakdown=["alakazam"], count=1),
- FunnelStepResult(
- name="buy",
- breakdown=["alakazam"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, "alakazam"),
- [people["person4"].uuid],
- )
-
- @snapshot_clickhouse_queries
- def test_funnel_step_multiple_breakdown_snapshot(self):
- # No person querying here, so snapshots are more legible
-
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser", "$version"],
- "breakdown_attribution_type": "first_touch",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome", "$version": "xyz"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari", "$version": "xyz"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$version": "no-mac"},
- },
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0, "$version": 0},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- # no properties dude, represented by ''
- "person5": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 15)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 5)
-
- @snapshot_clickhouse_queries
- def test_funnel_breakdown_correct_breakdown_props_are_chosen(self):
- # No person querying here, so snapshots are more legible
-
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {
- "id": "buy",
- "properties": [{"type": "event", "key": "$version", "value": "xyz"}],
- "order": 1,
- },
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": "$browser",
- "breakdown_attribution_type": "first_touch",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome", "$version": "xyz"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$browser": "Chrome"},
- },
- # discarded at step 1 because doesn't meet criteria
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari", "$version": "xyz"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$version": "xyz", "$browser": "Mac"},
- },
- ],
- # no properties dude, represented by '', who finished step 0
- "person5": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 15)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 4)
-
- self.assertCountEqual(
- [res[0]["breakdown"] for res in result],
- [["Mac"], ["Chrome"], ["Safari"], [""]],
- )
-
- @snapshot_clickhouse_queries
- def test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step(self):
- # No person querying here, so snapshots are more legible
-
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {
- "id": "buy",
- "properties": [{"type": "event", "key": "$version", "value": "xyz"}],
- "order": 1,
- },
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": "$browser",
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "1",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome", "$version": "xyz"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$browser": "Chrome"},
- },
- # discarded because doesn't meet criteria
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari", "$version": "xyz"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$version": "xyz", "$browser": "Mac"},
- },
- ],
- # no properties dude, doesn't make it to step 1, and since breakdown on step 1, is discarded completely
- "person5": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 15)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 2)
-
- self.assertCountEqual([res[0]["breakdown"] for res in result], [["Mac"], ["Safari"]])
-
- def test_funnel_personless_events_are_supported_with_breakdown(self):
- personless_user = uuid.uuid4()
- _create_event(
- event="user signed up",
- distinct_id=personless_user,
- person_id=personless_user,
- properties={"cohort": "A"},
- team=self.team,
- )
- _create_event(
- event="added to cart",
- distinct_id=personless_user,
- person_id=personless_user,
- properties={"cohort": "A"},
- team=self.team,
- )
-
- filters = {
- "events": [
- {
- "type": "events",
- "id": "user signed up",
- "order": 0,
- "name": "user signed up",
- "math": "total",
- },
- {
- "type": "events",
- "id": "added to cart",
- "order": 1,
- "name": "added to cart",
- "math": "total",
- },
- ],
- "funnel_window_days": 14,
- "breakdown_value": ["cohort"],
- "breakdown": "event",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
- result = funnel.run()
- self.assertEqual(len(result), 1)
- self.assertEqual(result[0][0]["count"], 1)
- self.assertEqual(result[0][1]["count"], 1)
-
- return TestFunnelBreakdown
-
-
-def sort_breakdown_funnel_results(results: list[dict[int, Any]]):
- return sorted(results, key=lambda r: r[0]["breakdown_value"])
-
-
-def assert_funnel_results_equal(left: list[dict[str, Any]], right: list[dict[str, Any]]):
- """
- Helper to be able to compare two funnel results, but exclude people urls
- from the comparison, as these include:
-
- 1. all the params from the request, and will thus almost always be
- different for varying inputs
- 2. contain timestamps which are not stable across runs
- """
-
- def _filter(steps: list[dict[str, Any]]) -> list[dict[str, Any]]:
- return [{**step, "converted_people_url": None, "dropped_people_url": None} for step in steps]
-
- assert len(left) == len(right)
-
- for index, item in enumerate(_filter(left)):
- other = _filter(right)[index]
- assert item.keys() == other.keys()
- for key in item.keys():
- try:
- assert item[key] == other[key]
- except AssertionError as e:
- e.args += (
- f"failed comparing ${key}",
- f'Got "{item[key]}" and "{other[key]}"',
- )
- raise
diff --git a/posthog/queries/funnels/test/conversion_time_cases.py b/posthog/queries/funnels/test/conversion_time_cases.py
deleted file mode 100644
index 70761285757a..000000000000
--- a/posthog/queries/funnels/test/conversion_time_cases.py
+++ /dev/null
@@ -1,213 +0,0 @@
-from datetime import datetime
-
-from posthog.test.base import APIBaseTest
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.filters import Filter
-from posthog.test.test_journeys import journeys_for
-
-
-def funnel_conversion_time_test_factory(Funnel, FunnelPerson, _create_event, _create_person):
- class TestFunnelConversionTime(APIBaseTest):
- def _get_actor_ids_at_step(self, filter, funnel_step, breakdown_value=None):
- person_filter = filter.shallow_clone({"funnel_step": funnel_step, "funnel_step_breakdown": breakdown_value})
- _, serialized_result, _ = FunnelPerson(person_filter, self.team).get_actors()
-
- return [val["id"] for val in serialized_result]
-
- def test_funnel_with_multiple_incomplete_tries(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "$pageview", "type": "events", "order": 1},
- {"id": "something else", "type": "events", "order": 2},
- ],
- "funnel_window_days": 1,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "insight": INSIGHT_FUNNELS,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- people = journeys_for(
- {
- "person1": [
- # person1 completed funnel on 2021-05-01
- {
- "event": "user signed up",
- "timestamp": datetime(2021, 5, 1, 1),
- },
- {"event": "$pageview", "timestamp": datetime(2021, 5, 1, 2)},
- {
- "event": "something else",
- "timestamp": datetime(2021, 5, 1, 3),
- },
- # person1 completed part of funnel on 2021-05-03 and took 2 hours to convert
- {
- "event": "user signed up",
- "timestamp": datetime(2021, 5, 3, 4),
- },
- {"event": "$pageview", "timestamp": datetime(2021, 5, 3, 5)},
- # person1 completed part of funnel on 2021-05-04 and took 3 hours to convert
- {
- "event": "user signed up",
- "timestamp": datetime(2021, 5, 4, 7),
- },
- {"event": "$pageview", "timestamp": datetime(2021, 5, 4, 10)},
- ]
- },
- self.team,
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(
- result[1]["average_conversion_time"], 3600
- ) # one hour to convert, disregard the incomplete tries
- self.assertEqual(result[1]["median_conversion_time"], 3600)
-
- # check ordering of people in every step
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [people["person1"].uuid])
-
- def test_funnel_step_conversion_times(self):
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- journeys_for(
- {
- "person1": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 12)},
- {"event": "play movie", "timestamp": datetime(2020, 1, 1, 13)},
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 15)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 14)},
- {"event": "play movie", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- "person3": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 14)},
- {"event": "play movie", "timestamp": datetime(2020, 1, 2, 16)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 17)},
- ],
- },
- self.team,
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["average_conversion_time"], None)
- self.assertEqual(result[1]["average_conversion_time"], 6000)
- self.assertEqual(result[2]["average_conversion_time"], 5400)
-
- self.assertEqual(result[0]["median_conversion_time"], None)
- self.assertEqual(result[1]["median_conversion_time"], 7200)
- self.assertEqual(result[2]["median_conversion_time"], 5400)
-
- def test_funnel_times_with_different_conversion_windows(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "pageview", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_interval": 14,
- "funnel_window_interval_unit": "day",
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- people = journeys_for(
- {
- "stopped_after_signup1": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 14),
- },
- {"event": "pageview", "timestamp": datetime(2020, 1, 2, 14, 5)},
- ],
- "stopped_after_signup2": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 14, 3),
- }
- ],
- "stopped_after_signup3": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 1, 2, 12),
- },
- {
- "event": "pageview",
- "timestamp": datetime(2020, 1, 2, 12, 15),
- },
- ],
- },
- self.team,
- )
-
- result = funnel.run()
- self.assertEqual(result[0]["count"], 3)
- self.assertEqual(result[1]["count"], 2)
- self.assertEqual(result[1]["average_conversion_time"], 600)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- people["stopped_after_signup1"].uuid,
- people["stopped_after_signup2"].uuid,
- people["stopped_after_signup3"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- people["stopped_after_signup1"].uuid,
- people["stopped_after_signup3"].uuid,
- ],
- )
-
- filter = filter.shallow_clone({"funnel_window_interval": 5, "funnel_window_interval_unit": "minute"})
-
- funnel = Funnel(filter, self.team)
- result4 = funnel.run()
-
- self.assertNotEqual(result, result4)
- self.assertEqual(result4[0]["count"], 3)
- self.assertEqual(result4[1]["count"], 1)
- self.assertEqual(result4[1]["average_conversion_time"], 300)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- people["stopped_after_signup1"].uuid,
- people["stopped_after_signup2"].uuid,
- people["stopped_after_signup3"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [people["stopped_after_signup1"].uuid],
- )
-
- return TestFunnelConversionTime
diff --git a/posthog/queries/funnels/test/test_breakdowns_by_current_url.py b/posthog/queries/funnels/test/test_breakdowns_by_current_url.py
deleted file mode 100644
index edc1b933fc57..000000000000
--- a/posthog/queries/funnels/test/test_breakdowns_by_current_url.py
+++ /dev/null
@@ -1,209 +0,0 @@
-from datetime import datetime
-from typing import Optional
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
-
-from posthog.models import Filter
-from posthog.queries.funnels import ClickhouseFunnel
-from posthog.test.test_journeys import journeys_for
-
-
-class TestBreakdownsByCurrentURL(ClickhouseTestMixin, APIBaseTest):
- def setUp(self):
- super().setUp()
- journey = {
- "person1": [
- # no trailing slash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com",
- "$pathname": "",
- },
- },
- # trailing question mark
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 2),
- "properties": {
- "$current_url": "https://example.com?",
- "$pathname": "?",
- },
- },
- {
- "event": "terminate funnel",
- "timestamp": datetime(2020, 1, 2, 12, 3),
- },
- ],
- "person2": [
- # trailing slash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com/",
- "$pathname": "/",
- },
- },
- # trailing hash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 2),
- "properties": {
- "$current_url": "https://example.com#",
- "$pathname": "#",
- },
- },
- {
- "event": "terminate funnel",
- "timestamp": datetime(2020, 1, 2, 12, 3),
- },
- ],
- "person3": [
- # no trailing slash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com/home",
- "$pathname": "/home",
- },
- },
- {
- "event": "terminate funnel",
- "timestamp": datetime(2020, 1, 2, 12, 2),
- },
- ],
- "person4": [
- # trailing slash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com/home/",
- "$pathname": "/home/",
- },
- },
- # trailing hash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 2),
- "properties": {
- "$current_url": "https://example.com/home#",
- "$pathname": "/home#",
- },
- },
- # all the things
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 3),
- "properties": {
- "$current_url": "https://example.com/home/?#",
- "$pathname": "/home/?#",
- },
- },
- {
- "event": "terminate funnel",
- "timestamp": datetime(2020, 1, 2, 12, 4),
- },
- ],
- }
-
- journeys_for(journey, team=self.team, create_people=True)
-
- def _run(self, extra: Optional[dict] = None, events_extra: Optional[dict] = None):
- if events_extra is None:
- events_extra = {}
- if extra is None:
- extra = {}
- response = ClickhouseFunnel(
- Filter(
- data={
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- **events_extra,
- },
- {
- "id": "terminate funnel",
- "name": "terminate funnel",
- "type": "events",
- "order": 1,
- **events_extra,
- },
- ],
- "funnel_viz_type": "steps",
- "insight": "FUNNELS",
- "date_from": "2020-01-02T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown_limit": 100, # never have other
- **extra,
- }
- ),
- self.team,
- ).run()
- return response
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_pathname(self) -> None:
- response = self._run(
- {
- "breakdown": "$pathname",
- "breakdown_type": "event",
- "breakdown_normalize_url": True,
- }
- )
-
- actual = []
- for breakdown_value in response:
- for funnel_step in breakdown_value:
- actual.append(
- (
- funnel_step["name"],
- funnel_step["count"],
- funnel_step["breakdown"],
- )
- )
- # The query to get results does not order them.
- want = [
- ("watched movie", 2, ["/"]),
- ("terminate funnel", 2, ["/"]),
- ("watched movie", 2, ["/home"]),
- ("terminate funnel", 2, ["/home"]),
- ]
- key_func = lambda x: (x[2][0], x[0])
- assert sorted(want, key=key_func) == sorted(actual, key=key_func)
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_current_url(self) -> None:
- response = self._run(
- {
- "breakdown": "$current_url",
- "breakdown_type": "event",
- "breakdown_normalize_url": True,
- }
- )
-
- actual = []
- for breakdown_value in response:
- for funnel_step in breakdown_value:
- actual.append(
- (
- funnel_step["name"],
- funnel_step["count"],
- funnel_step["breakdown"],
- )
- )
-
- want = [
- ("watched movie", 2, ["https://example.com/home"]),
- ("terminate funnel", 2, ["https://example.com/home"]),
- ("watched movie", 2, ["https://example.com"]),
- ("terminate funnel", 2, ["https://example.com"]),
- ]
- key_func = lambda x: (x[2][0], x[0])
- assert sorted(want, key=key_func) == sorted(actual, key=key_func)
diff --git a/posthog/queries/funnels/test/test_funnel.py b/posthog/queries/funnels/test/test_funnel.py
deleted file mode 100644
index ed18a217bb97..000000000000
--- a/posthog/queries/funnels/test/test_funnel.py
+++ /dev/null
@@ -1,3709 +0,0 @@
-import uuid
-from datetime import datetime
-
-from freezegun import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_action,
- _create_event,
- _create_person,
- also_test_with_materialized_columns,
- create_person_id_override_by_distinct_id,
- snapshot_clickhouse_queries,
-)
-from unittest.case import skip
-
-from django.test import override_settings
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.clickhouse.client import sync_execute
-from posthog.constants import FILTER_TEST_ACCOUNTS, INSIGHT_FUNNELS
-from posthog.models import Element
-from posthog.models.filters import Filter
-from posthog.models.instance_setting import get_instance_setting
-from posthog.queries.funnels import ClickhouseFunnel, ClickhouseFunnelActors
-from posthog.queries.funnels.test.breakdown_cases import assert_funnel_results_equal, funnel_breakdown_test_factory
-from posthog.queries.funnels.test.conversion_time_cases import funnel_conversion_time_test_factory
-from posthog.test.test_journeys import journeys_for
-
-from products.actions.backend.models.action import Action
-from products.cohorts.backend.models.cohort import Cohort
-
-
-class TestFunnelBreakdown(
- ClickhouseTestMixin,
- funnel_breakdown_test_factory( # type: ignore[misc]
- ClickhouseFunnel,
- ClickhouseFunnelActors,
- _create_event,
- _create_action,
- _create_person,
- ),
-):
- maxDiff = None
- pass
-
-
-class TestFunnelConversionTime(
- ClickhouseTestMixin,
- funnel_conversion_time_test_factory( # type: ignore[misc]
- ClickhouseFunnel, ClickhouseFunnelActors, _create_event, _create_person
- ),
-):
- maxDiff = None
- pass
-
-
-def funnel_test_factory(Funnel, event_factory, person_factory):
- class TestGetFunnel(ClickhouseTestMixin, APIBaseTest):
- def _get_actor_ids_at_step(self, filter, funnel_step, breakdown_value=None):
- person_filter = filter.shallow_clone({"funnel_step": funnel_step, "funnel_step_breakdown": breakdown_value})
- _, serialized_result, _ = ClickhouseFunnelActors(person_filter, self.team).get_actors()
-
- return [val["id"] for val in serialized_result]
-
- def _signup_event(self, **kwargs):
- event_factory(team=self.team, event="user signed up", **kwargs)
-
- def _add_to_cart_event(self, **kwargs):
- event_factory(team=self.team, event="added to cart", **kwargs)
-
- def _checkout_event(self, **kwargs):
- event_factory(team=self.team, event="checked out", **kwargs)
-
- def _pay_event(self, **kwargs):
- event_factory(
- team=self.team,
- event="$autocapture",
- elements=[Element(nth_of_type=1, nth_child=0, tag_name="button", text="Pay $10")],
- **kwargs,
- )
-
- def _movie_event(self, **kwargs):
- event_factory(
- team=self.team,
- event="$autocapture",
- elements=[Element(nth_of_type=1, nth_child=0, tag_name="a", href="/movie")],
- **kwargs,
- )
-
- def _single_step_funnel(self, properties=None, filters=None):
- if filters is None:
- filters = {
- "events": [{"id": "user signed up", "type": "events", "order": 0}],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
-
- if properties is not None:
- filters.update({"properties": properties})
-
- filter = Filter(data=filters)
- return Funnel(filter=filter, team=self.team)
-
- def _basic_funnel(self, properties=None, filters=None):
- action_credit_card = Action.objects.create(
- team=self.team,
- name="paid",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "button",
- "text": "Pay $10",
- }
- ],
- )
- action_play_movie = Action.objects.create(
- team=self.team,
- name="watched movie",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "a",
- "href": "/movie",
- }
- ],
- )
-
- if filters is None:
- filters = {
- "events": [{"id": "user signed up", "type": "events", "order": 0}],
- "actions": [
- {"id": action_credit_card.pk, "type": "actions", "order": 1},
- {"id": action_play_movie.pk, "type": "actions", "order": 2},
- ],
- "funnel_window_days": 14,
- }
-
- if properties is not None:
- filters.update({"properties": properties})
-
- filters["insight"] = INSIGHT_FUNNELS # ty: ignore[invalid-assignment]
- filter = Filter(data=filters, team=self.team)
- return Funnel(filter=filter, team=self.team)
-
- def test_funnel_default(self):
- funnel = self._single_step_funnel()
-
- with freeze_time("2012-01-01T03:21:34.000Z"):
- # event
- person_factory(distinct_ids=["stopped_after_signup1"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup1")
-
- person_factory(distinct_ids=["stopped_after_signup2"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup2")
-
- result = funnel.run()
- self.assertEqual(result[0]["count"], 0)
-
- def test_funnel_with_single_step(self):
- funnel = self._single_step_funnel()
-
- # event
- person_factory(distinct_ids=["stopped_after_signup1"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup1")
-
- person_factory(distinct_ids=["stopped_after_signup2"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup2")
-
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- def test_funnel_events(self):
- funnel = self._basic_funnel()
-
- # events
- person_factory(distinct_ids=["stopped_after_signup"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup")
-
- person_factory(distinct_ids=["stopped_after_pay"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_pay")
- self._pay_event(distinct_id="stopped_after_pay")
-
- person_factory(
- distinct_ids=["had_anonymous_id", "completed_movie"],
- team_id=self.team.pk,
- )
- self._signup_event(distinct_id="had_anonymous_id")
- self._pay_event(distinct_id="completed_movie")
- self._movie_event(distinct_id="completed_movie")
-
- person_factory(distinct_ids=["just_did_movie"], team_id=self.team.pk)
- self._movie_event(distinct_id="just_did_movie")
-
- person_factory(distinct_ids=["wrong_order"], team_id=self.team.pk)
- self._pay_event(distinct_id="wrong_order")
- self._signup_event(distinct_id="wrong_order")
- self._movie_event(distinct_id="wrong_order")
-
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 4)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 2)
- self.assertEqual(result[2]["name"], "watched movie")
- self.assertEqual(result[2]["count"], 1)
-
- @override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=True)
- @snapshot_clickhouse_queries
- def test_funnel_events_with_person_on_events_v2(self):
- # KLUDGE: We need to do this to ensure create_person_id_override_by_distinct_id
- # works correctly. Worth considering other approaches as we generally like to
- # avoid truncating tables in tests for speed.
- sync_execute("TRUNCATE TABLE sharded_events")
- with freeze_time("2012-01-01T03:21:34.000Z"):
- funnel = self._basic_funnel()
-
- with freeze_time("2012-01-01T03:21:35.000Z"):
- # events
- stopped_after_signup_person_id = uuid.uuid4()
- person_factory(distinct_ids=["stopped_after_signup"], team_id=self.team.pk)
- self._signup_event(
- distinct_id="stopped_after_signup",
- person_id=stopped_after_signup_person_id,
- )
-
- with freeze_time("2012-01-01T03:21:36.000Z"):
- stopped_after_pay_person_id = uuid.uuid4()
- person_factory(distinct_ids=["stopped_after_pay"], team_id=self.team.pk)
- self._signup_event(
- distinct_id="stopped_after_pay",
- person_id=stopped_after_pay_person_id,
- )
- with freeze_time("2012-01-01T03:21:37.000Z"):
- self._pay_event(
- distinct_id="stopped_after_pay",
- person_id=stopped_after_pay_person_id,
- )
-
- with freeze_time("2012-01-01T03:21:38.000Z"):
- had_anonymous_id_person_id = uuid.uuid4()
- person_factory(
- distinct_ids=["had_anonymous_id", "completed_movie"],
- team_id=self.team.pk,
- )
- self._signup_event(distinct_id="had_anonymous_id", person_id=had_anonymous_id_person_id)
- with freeze_time("2012-01-01T03:21:39.000Z"):
- self._pay_event(distinct_id="completed_movie", person_id=had_anonymous_id_person_id)
- with freeze_time("2012-01-01T03:21:40.000Z"):
- self._movie_event(distinct_id="completed_movie", person_id=had_anonymous_id_person_id)
-
- with freeze_time("2012-01-01T03:21:41.000Z"):
- just_did_movie_person_id = uuid.uuid4()
- person_factory(distinct_ids=["just_did_movie"], team_id=self.team.pk)
- self._movie_event(distinct_id="just_did_movie", person_id=just_did_movie_person_id)
-
- with freeze_time("2012-01-01T03:21:42.000Z"):
- wrong_order_person_id = uuid.uuid4()
- person_factory(distinct_ids=["wrong_order"], team_id=self.team.pk)
- self._pay_event(distinct_id="wrong_order", person_id=wrong_order_person_id)
- with freeze_time("2012-01-01T03:21:43.000Z"):
- self._signup_event(distinct_id="wrong_order", person_id=wrong_order_person_id)
- with freeze_time("2012-01-01T03:21:44.000Z"):
- self._movie_event(distinct_id="wrong_order", person_id=wrong_order_person_id)
-
- with freeze_time("2012-01-01T03:21:45.000Z"):
- create_person_id_override_by_distinct_id("stopped_after_signup", "stopped_after_pay", self.team.pk)
-
- with freeze_time("2012-01-01T03:21:46.000Z"):
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
-
- # key difference between this test and test_funnel_events.
- # we merged two people and thus the count here is 3 and not 4
- self.assertEqual(result[0]["count"], 3)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 2)
- self.assertEqual(result[2]["name"], "watched movie")
- self.assertEqual(result[2]["count"], 1)
-
- def test_funnel_with_messed_up_order(self):
- action_play_movie = Action.objects.create(
- team=self.team,
- name="watched movie",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "a",
- "href": "/movie",
- }
- ],
- )
-
- funnel = self._basic_funnel(
- filters={
- "events": [{"id": "user signed up", "type": "events", "order": 0}],
- "actions": [{"id": action_play_movie.pk, "type": "actions", "order": 2}],
- "funnel_window_days": 14,
- }
- )
-
- # events
- person_factory(distinct_ids=["stopped_after_signup"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup")
-
- person_factory(distinct_ids=["stopped_after_pay"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_pay")
- self._movie_event(distinct_id="completed_movie")
-
- person_factory(
- distinct_ids=["had_anonymous_id", "completed_movie"],
- team_id=self.team.pk,
- )
- self._signup_event(distinct_id="had_anonymous_id")
- self._movie_event(distinct_id="completed_movie")
-
- person_factory(distinct_ids=["just_did_movie"], team_id=self.team.pk)
- self._movie_event(distinct_id="just_did_movie")
-
- person_factory(distinct_ids=["wrong_order"], team_id=self.team.pk)
- self._movie_event(distinct_id="wrong_order")
- self._signup_event(distinct_id="wrong_order")
-
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 4)
-
- self.assertEqual(result[1]["name"], "watched movie")
- self.assertEqual(result[1]["count"], 1)
-
- def test_funnel_with_any_event(self):
- funnel = self._basic_funnel(
- filters={
- "events": [
- {"id": None, "type": "events", "order": 0},
- {"id": None, "type": "events", "order": 1},
- {"id": None, "type": "events", "order": 2},
- ],
- "funnel_window_days": 14,
- }
- )
-
- # events
- person_factory(distinct_ids=["stopped_after_signup"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup")
-
- person_factory(distinct_ids=["stopped_after_pay"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_pay")
- self._movie_event(distinct_id="stopped_after_pay")
-
- person_factory(distinct_ids=["completed_movie"], team_id=self.team.pk)
- self._signup_event(distinct_id="completed_movie")
- self._movie_event(distinct_id="completed_movie")
-
- person_factory(distinct_ids=["just_did_movie"], team_id=self.team.pk)
- self._movie_event(distinct_id="just_did_movie")
-
- person_factory(distinct_ids=["wrong_order"], team_id=self.team.pk)
- self._movie_event(distinct_id="wrong_order")
- self._signup_event(distinct_id="wrong_order")
- self._movie_event(distinct_id="wrong_order")
-
- result = funnel.run()
- self.assertEqual(result[0]["name"], None)
- self.assertEqual(result[0]["count"], 5)
-
- self.assertEqual(result[1]["name"], None)
- self.assertEqual(result[1]["count"], 3)
-
- self.assertEqual(result[2]["name"], None)
- self.assertEqual(result[2]["count"], 1)
-
- def test_funnel_with_new_entities_that_mess_up_order(self):
- action_play_movie = Action.objects.create(
- team=self.team,
- name="watched movie",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "a",
- "href": "/movie",
- }
- ],
- )
-
- funnel = self._basic_funnel(
- filters={
- "events": [{"id": "user signed up", "type": "events", "order": 1}],
- "actions": [{"id": action_play_movie.pk, "type": "actions", "order": 2}],
- "new_entities": [
- {"id": "first", "type": "new_entity", "order": 0},
- {"id": "last", "type": "new_entity", "order": 3},
- ],
- "funnel_window_days": 14,
- }
- )
-
- # events
- person_factory(distinct_ids=["stopped_after_signup"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup")
-
- person_factory(distinct_ids=["stopped_after_pay"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_pay")
- self._movie_event(distinct_id="completed_movie")
-
- person_factory(
- distinct_ids=["had_anonymous_id", "completed_movie"],
- team_id=self.team.pk,
- )
- self._signup_event(distinct_id="had_anonymous_id")
- self._movie_event(distinct_id="completed_movie")
-
- person_factory(distinct_ids=["just_did_movie"], team_id=self.team.pk)
- self._movie_event(distinct_id="just_did_movie")
-
- person_factory(distinct_ids=["wrong_order"], team_id=self.team.pk)
- self._movie_event(distinct_id="wrong_order")
- self._signup_event(distinct_id="wrong_order")
-
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 4)
-
- self.assertEqual(result[1]["name"], "watched movie")
- self.assertEqual(result[1]["count"], 1)
-
- def test_funnel_no_events(self):
- funnel = Funnel(filter=Filter(data={"some": "prop"}), team=self.team)
- self.assertEqual(funnel.run(), [])
-
- def test_funnel_skipped_step(self):
- funnel = self._basic_funnel()
-
- person_factory(distinct_ids=["wrong_order"], team_id=self.team.pk)
- self._signup_event(distinct_id="wrong_order")
- self._movie_event(distinct_id="wrong_order")
-
- result = funnel.run()
- self.assertEqual(result[1]["count"], 0)
- self.assertEqual(result[2]["count"], 0)
-
- @also_test_with_materialized_columns(["$browser"])
- def test_funnel_prop_filters(self):
- funnel = self._basic_funnel(properties={"$browser": "Safari"})
-
- # events
- person_factory(distinct_ids=["with_property"], team_id=self.team.pk)
- self._signup_event(distinct_id="with_property", properties={"$browser": "Safari"})
- self._pay_event(distinct_id="with_property", properties={"$browser": "Safari"})
-
- # should not add a count
- person_factory(distinct_ids=["without_property"], team_id=self.team.pk)
- self._signup_event(distinct_id="without_property")
- self._pay_event(distinct_id="without_property")
-
- # will add to first step
- person_factory(distinct_ids=["half_property"], team_id=self.team.pk)
- self._signup_event(distinct_id="half_property", properties={"$browser": "Safari"})
- self._pay_event(distinct_id="half_property")
-
- result = funnel.run()
- self.assertEqual(result[0]["count"], 2)
- self.assertEqual(result[1]["count"], 1)
-
- @also_test_with_materialized_columns(["$browser"])
- def test_funnel_prop_filters_per_entity(self):
- action_credit_card = Action.objects.create(
- team_id=self.team.pk,
- name="paid",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "button",
- "text": "Pay $10",
- }
- ],
- )
- action_play_movie = Action.objects.create(
- team_id=self.team.pk,
- name="watched movie",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "a",
- "href": "/movie",
- }
- ],
- )
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [
- {"key": "$browser", "value": "Safari"},
- {
- "key": "$browser",
- "operator": "is_not",
- "value": "Chrome",
- },
- ],
- }
- ],
- "actions": [
- {
- "id": action_credit_card.pk,
- "type": "actions",
- "order": 1,
- "properties": [{"key": "$browser", "value": "Safari"}],
- },
- {
- "id": action_play_movie.pk,
- "type": "actions",
- "order": 2,
- "properties": [{"key": "$browser", "value": "Firefox"}],
- },
- ],
- "funnel_window_days": 14,
- }
- funnel = self._basic_funnel(filters=filters)
-
- # events
- person_factory(
- distinct_ids=["with_property"],
- team_id=self.team.pk,
- properties={"$browser": "Safari"},
- )
- self._signup_event(distinct_id="with_property", properties={"$browser": "Safari"})
- self._pay_event(distinct_id="with_property", properties={"$browser": "Safari"})
- self._movie_event(distinct_id="with_property")
-
- # should not add a count
- person_factory(distinct_ids=["without_property"], team_id=self.team.pk)
- self._signup_event(distinct_id="without_property")
- self._pay_event(distinct_id="without_property", properties={"$browser": "Safari"})
-
- # will add to first step
- person_factory(distinct_ids=["half_property"], team_id=self.team.pk)
- self._signup_event(distinct_id="half_property")
- self._pay_event(distinct_id="half_property")
- self._movie_event(distinct_id="half_property")
-
- result = funnel.run()
-
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(result[1]["count"], 1)
- self.assertEqual(result[2]["count"], 0)
-
- @also_test_with_materialized_columns(person_properties=["email"])
- def test_funnel_person_prop(self):
- action_credit_card = Action.objects.create(
- team_id=self.team.pk,
- name="paid",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "button",
- "text": "Pay $10",
- }
- ],
- )
- action_play_movie = Action.objects.create(
- team_id=self.team.pk,
- name="watched movie",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "a",
- "href": "/movie",
- }
- ],
- )
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [
- {
- "key": "email",
- "value": "[email protected]",
- "type": "person",
- }
- ],
- }
- ],
- "actions": [
- {"id": action_credit_card.pk, "type": "actions", "order": 1},
- {"id": action_play_movie.pk, "type": "actions", "order": 2},
- ],
- "funnel_window_days": 14,
- }
- funnel = self._basic_funnel(filters=filters)
-
- # events
- person_factory(
- distinct_ids=["with_property"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- self._signup_event(distinct_id="with_property")
- self._pay_event(distinct_id="with_property")
- self._movie_event(distinct_id="with_property")
-
- result = funnel.run()
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(result[1]["count"], 1)
- self.assertEqual(result[2]["count"], 1)
-
- @also_test_with_materialized_columns(["test_propX"])
- def test_funnel_multiple_actions(self):
- # we had an issue on clickhouse where multiple actions with different property filters would incorrectly grab only the last
- # properties.
- # This test prevents a regression
- person_factory(distinct_ids=["person1"], team_id=self.team.pk)
- event_factory(distinct_id="person1", event="event1", team=self.team)
- event_factory(
- distinct_id="person1",
- event="event2",
- properties={"test_propX": "a"},
- team=self.team,
- )
-
- action1 = Action.objects.create(
- team_id=self.team.pk,
- name="event2",
- steps_json=[
- {
- "event": "event2",
- "properties": [{"key": "test_propX", "value": "a"}],
- }
- ],
- )
- action2 = Action.objects.create(
- team_id=self.team.pk,
- name="event2",
- steps_json=[
- {
- "event": "event2",
- "properties": [{"key": "test_propX", "value": "c"}],
- }
- ],
- )
-
- result = Funnel(
- filter=Filter(
- data={
- "events": [{"id": "event1", "order": 0}],
- "actions": [
- {"id": action1.pk, "order": 1},
- {"id": action2.pk, "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
- ),
- team=self.team,
- ).run()
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(result[1]["count"], 1)
- self.assertEqual(result[2]["count"], 0)
-
- @also_test_with_materialized_columns(person_properties=["email"])
- def test_funnel_filter_test_accounts(self):
- person_factory(
- distinct_ids=["person1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- person_factory(distinct_ids=["person2"], team_id=self.team.pk)
- event_factory(distinct_id="person1", event="event1", team=self.team)
- event_factory(distinct_id="person2", event="event1", team=self.team)
- result = Funnel(
- filter=Filter(
- data={
- "events": [{"id": "event1", "order": 0}],
- "insight": INSIGHT_FUNNELS,
- FILTER_TEST_ACCOUNTS: True,
- "funnel_window_days": 14,
- },
- team=self.team,
- ),
- team=self.team,
- ).run()
- self.assertEqual(result[0]["count"], 1)
-
- @also_test_with_materialized_columns(person_properties=["email"])
- def test_funnel_with_entity_person_property_filters(self):
- person_factory(
- distinct_ids=["person1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- person_factory(
- distinct_ids=["person2"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- person_factory(distinct_ids=["person3"], team_id=self.team.pk)
- event_factory(distinct_id="person1", event="event1", team=self.team)
- event_factory(distinct_id="person2", event="event1", team=self.team)
- event_factory(distinct_id="person3", event="event1", team=self.team)
-
- result = Funnel(
- filter=Filter(
- data={
- "events": [
- {
- "id": "event1",
- "order": 0,
- "properties": [
- {
- "key": "email",
- "value": "is_set",
- "operator": "is_set",
- "type": "person",
- }
- ],
- }
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
- ),
- team=self.team,
- ).run()
- self.assertEqual(result[0]["count"], 2)
-
- @also_test_with_materialized_columns(person_properties=["email"], verify_no_jsonextract=False)
- def test_funnel_filter_by_action_with_person_properties(self):
- person_factory(
- distinct_ids=["person1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- person_factory(
- distinct_ids=["person2"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- person_factory(distinct_ids=["person3"], team_id=self.team.pk)
- event_factory(distinct_id="person1", event="event1", team=self.team)
- event_factory(distinct_id="person2", event="event1", team=self.team)
- event_factory(distinct_id="person3", event="event1", team=self.team)
-
- action = Action.objects.create(
- team_id=self.team.pk,
- name="event1",
- steps_json=[
- {
- "event": "event1",
- "properties": [
- {
- "key": "email",
- "value": "is_set",
- "operator": "is_set",
- "type": "person",
- }
- ],
- }
- ],
- )
-
- result = Funnel(
- filter=Filter(
- data={
- "actions": [{"id": action.pk, "type": "actions", "order": 0}],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
- ),
- team=self.team,
- ).run()
-
- self.assertEqual(result[0]["count"], 2)
-
- def test_basic_funnel_default_funnel_days(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- _create_person(distinct_ids=["user_1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_1",
- timestamp="2020-01-02T14:00:00Z",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="user_1",
- timestamp="2020-01-10T14:00:00Z",
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 1)
-
- def test_basic_funnel_with_repeat_steps(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user signed up", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- person1_stopped_after_two_signups = _create_person(
- distinct_ids=["stopped_after_signup1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- )
-
- person2_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup2",
- )
-
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["count"], 1)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [person1_stopped_after_two_signups.uuid],
- )
-
- @also_test_with_materialized_columns(["key"])
- def test_basic_funnel_with_derivative_steps(self):
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": {"key": "val"},
- },
- {"id": "user signed up", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- person1_stopped_after_two_signups = _create_person(
- distinct_ids=["stopped_after_signup1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- )
-
- person2_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup2",
- properties={"key": "val"},
- )
-
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["count"], 1)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [person1_stopped_after_two_signups.uuid],
- )
-
- def test_basic_funnel_with_repeat_step_updated_param(self):
- people = journeys_for(
- {
- "stopped_after_signup1": [
- {"event": "user signed up"},
- {"event": "user signed up"},
- ],
- "stopped_after_signup2": [{"event": "user signed up"}],
- },
- self.team,
- )
-
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user signed up", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_interval": 14,
- "funnel_window_interval_unit": "day",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["count"], 1)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- people["stopped_after_signup1"].uuid,
- people["stopped_after_signup2"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [people["stopped_after_signup1"].uuid],
- )
-
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user signed up", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_interval": 2,
- "funnel_window_interval_unit": "week",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
- result2 = funnel.run()
-
- assert_funnel_results_equal(result, result2)
-
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user signed up", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- "funnel_window_interval": 1,
- "funnel_window_interval_unit": "hour",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
- result3 = funnel.run()
-
- assert_funnel_results_equal(result, result3)
-
- def test_funnel_exclusions_full_window(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "exclusions": [
- {
- "id": "x 1 name with numbers 2",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- }
- ],
- }
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event 1
- person1 = _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person1",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person1",
- timestamp="2021-05-01 02:00:00",
- )
-
- # event 2
- _create_person(distinct_ids=["person2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person2",
- timestamp="2021-05-01 03:00:00",
- )
- _create_event(
- team=self.team,
- event="x 1 name with numbers 2",
- distinct_id="person2",
- timestamp="2021-05-01 03:30:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person2",
- timestamp="2021-05-01 04:00:00",
- )
-
- # event 3
- person3 = _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person3",
- timestamp="2021-05-01 06:00:00",
- )
-
- result = funnel.run()
- self.assertEqual(len(result), 2)
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 2)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person1.uuid, person3.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2), [person1.uuid, person3.uuid])
-
- def test_advanced_funnel_exclusions_between_steps(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "$pageview", "type": "events", "order": 1},
- {"id": "insight viewed", "type": "events", "order": 2},
- {"id": "invite teammate", "type": "events", "order": 3},
- {"id": "pageview2", "type": "events", "order": 4},
- ],
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "insight": INSIGHT_FUNNELS,
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- }
- ],
- }
-
- person1 = _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- # this dude is discarded when funnel_from_step = 1
- # this dude is discarded when funnel_from_step = 2
- # this dude is discarded when funnel_from_step = 3
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person1",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person1",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person1",
- timestamp="2021-05-01 03:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person1",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person1",
- timestamp="2021-05-01 04:30:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person1",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person1",
- timestamp="2021-05-01 05:30:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person1",
- timestamp="2021-05-01 06:00:00",
- )
-
- person2 = _create_person(distinct_ids=["person2"], team_id=self.team.pk)
- # this dude is discarded when funnel_from_step = 2
- # this dude is discarded when funnel_from_step = 3
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person2",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person2",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person2",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person2",
- timestamp="2021-05-01 04:30:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person2",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person2",
- timestamp="2021-05-01 05:30:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person2",
- timestamp="2021-05-01 06:00:00",
- )
-
- person3 = _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- # this dude is discarded when funnel_from_step = 0
- # this dude is discarded when funnel_from_step = 3
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person3",
- timestamp="2021-05-01 01:30:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person3",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person3",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person3",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person3",
- timestamp="2021-05-01 05:30:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person3",
- timestamp="2021-05-01 06:00:00",
- )
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[4]["count"], 2)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person1.uuid, person2.uuid])
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 1,
- "funnel_to_step": 2,
- }
- ]
- }
- )
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[4]["count"], 2)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person2.uuid, person3.uuid])
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 2,
- "funnel_to_step": 3,
- }
- ]
- }
- )
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[4]["count"], 1)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person3.uuid])
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 3,
- "funnel_to_step": 4,
- }
- ]
- }
- )
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 0)
-
- self.assertEqual(result[4]["count"], 0)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [])
-
- #  bigger step window
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 1,
- "funnel_to_step": 3,
- }
- ]
- }
- )
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[4]["count"], 1)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person3.uuid])
-
- def test_advanced_funnel_with_repeat_steps(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "$pageview", "type": "events", "order": 1},
- {"id": "$pageview", "type": "events", "order": 2},
- {"id": "$pageview", "type": "events", "order": 3},
- {"id": "$pageview", "type": "events", "order": 4},
- ],
- "insight": INSIGHT_FUNNELS,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- people = journeys_for(
- {
- "stopped_after_signup1": [{"event": "user signed up"}],
- "stopped_after_pageview1": [
- {"event": "user signed up"},
- {"event": "$pageview"},
- ],
- "stopped_after_pageview2": [
- {"event": "user signed up"},
- {"event": "$pageview"},
- {"event": "blaah blaa"},
- {"event": "$pageview"},
- ],
- "stopped_after_pageview3": [
- {"event": "user signed up"},
- {"event": "$pageview"},
- {"event": "blaah blaa"},
- {"event": "$pageview"},
- {"event": "$pageview"},
- {"event": "blaah blaa"},
- ],
- "stopped_after_pageview4": [
- {"event": "user signed up"},
- {"event": "$pageview"},
- {"event": "$pageview"},
- {"event": "$pageview"},
- {"event": "$pageview"},
- ],
- },
- self.team,
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[1]["name"], "$pageview")
- self.assertEqual(result[4]["name"], "$pageview")
- self.assertEqual(result[0]["count"], 5)
-
- self.assertEqual(result[1]["count"], 4)
-
- self.assertEqual(result[2]["count"], 3)
-
- self.assertEqual(result[3]["count"], 2)
-
- self.assertEqual(result[4]["count"], 1)
-
- # check ordering of people in every step
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- people["stopped_after_signup1"].uuid,
- people["stopped_after_pageview1"].uuid,
- people["stopped_after_pageview2"].uuid,
- people["stopped_after_pageview3"].uuid,
- people["stopped_after_pageview4"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- people["stopped_after_pageview1"].uuid,
- people["stopped_after_pageview2"].uuid,
- people["stopped_after_pageview3"].uuid,
- people["stopped_after_pageview4"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [
- people["stopped_after_pageview2"].uuid,
- people["stopped_after_pageview3"].uuid,
- people["stopped_after_pageview4"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 4),
- [
- people["stopped_after_pageview3"].uuid,
- people["stopped_after_pageview4"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 5),
- [people["stopped_after_pageview4"].uuid],
- )
-
- def test_advanced_funnel_with_repeat_steps_out_of_order_events(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "$pageview", "type": "events", "order": 1},
- {"id": "$pageview", "type": "events", "order": 2},
- {"id": "$pageview", "type": "events", "order": 3},
- {"id": "$pageview", "type": "events", "order": 4},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- person1_stopped_after_signup = _create_person(
- distinct_ids=["random", "stopped_after_signup1"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="$pageview", distinct_id="random")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- )
-
- person2_stopped_after_one_pageview = _create_person(
- distinct_ids=["stopped_after_pageview1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview1",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview1")
-
- person3_stopped_after_two_pageview = _create_person(
- distinct_ids=["stopped_after_pageview2"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview2")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview2",
- )
- _create_event(
- team=self.team,
- event="blaah blaa",
- distinct_id="stopped_after_pageview2",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview2")
-
- person4_stopped_after_three_pageview = _create_person(
- distinct_ids=["stopped_after_pageview3"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="blaah blaa",
- distinct_id="stopped_after_pageview3",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview3")
- _create_event(
- team=self.team,
- event="blaah blaa",
- distinct_id="stopped_after_pageview3",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview3")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview3",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview3")
-
- person5_stopped_after_many_pageview = _create_person(
- distinct_ids=["stopped_after_pageview4"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview4",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview4")
- _create_event(
- team=self.team,
- event="blaah blaa",
- distinct_id="stopped_after_pageview4",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview4")
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview4")
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview4")
-
- _create_person(distinct_ids=["stopped_after_pageview5"], team_id=self.team.pk)
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview5")
- _create_event(
- team=self.team,
- event="blaah blaa",
- distinct_id="stopped_after_pageview5",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview5")
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview5")
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview5")
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[1]["name"], "$pageview")
- self.assertEqual(result[4]["name"], "$pageview")
- self.assertEqual(result[0]["count"], 5)
-
- self.assertEqual(result[1]["count"], 4)
-
- self.assertEqual(result[2]["count"], 1)
-
- self.assertEqual(result[3]["count"], 1)
-
- self.assertEqual(result[4]["count"], 1)
-
- # check ordering of people in every step
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_signup.uuid,
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_two_pageview.uuid,
- person4_stopped_after_three_pageview.uuid,
- person5_stopped_after_many_pageview.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_two_pageview.uuid,
- person4_stopped_after_three_pageview.uuid,
- person5_stopped_after_many_pageview.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [person5_stopped_after_many_pageview.uuid],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 4),
- [person5_stopped_after_many_pageview.uuid],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 5),
- [person5_stopped_after_many_pageview.uuid],
- )
-
- @also_test_with_materialized_columns(["key"])
- def test_funnel_with_actions(self):
- sign_up_action = _create_action(
- name="sign up",
- team=self.team,
- properties=[
- {
- "key": "key",
- "type": "event",
- "value": ["val"],
- "operator": "exact",
- }
- ],
- )
-
- filters = {
- "actions": [
- {"id": sign_up_action.id, "math": "dau", "order": 0},
- {"id": sign_up_action.id, "math": "weekly_active", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- person1_stopped_after_two_signups = _create_person(
- distinct_ids=["stopped_after_signup1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
-
- person2_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup2",
- properties={"key": "val"},
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "sign up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["count"], 1)
-
- # check ordering of people in first step
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [person1_stopped_after_two_signups.uuid],
- )
-
- def test_funnel_with_different_actions_at_same_time_count_as_converted(self):
- sign_up_action = _create_action(
- name="sign up",
- team=self.team,
- properties=[
- {
- "key": "key",
- "type": "event",
- "value": ["val"],
- "operator": "exact",
- }
- ],
- )
-
- filters = {
- "actions": [{"id": sign_up_action.id, "order": 0}],
- "events": [{"id": "$pageview", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- with freeze_time("2020-01-03"):
- # event
- person1_stopped_after_two_signups = _create_person(
- distinct_ids=["stopped_after_signup1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
-
- person2_stopped_after_signup = _create_person(
- distinct_ids=["stopped_after_signup2"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup2",
- properties={"key": "val"},
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "sign up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["count"], 1)
-
- # check ordering of people in first step
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [person1_stopped_after_two_signups.uuid],
- )
-
- def test_funnel_with_actions_and_props(self):
- sign_up_action = _create_action(
- name="sign up",
- team=self.team,
- properties=[
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- )
-
- filters = {
- "actions": [
- {"id": sign_up_action.id, "math": "dau", "order": 0},
- {"id": sign_up_action.id, "math": "weekly_active", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- person1_stopped_after_two_signups = _create_person(
- distinct_ids=["stopped_after_signup1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
-
- person2_stopped_after_signup = _create_person(
- distinct_ids=["stopped_after_signup2"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup2",
- properties={"key": "val"},
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "sign up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["count"], 1)
-
- # check ordering of people in first step
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [person1_stopped_after_two_signups.uuid],
- )
-
- def test_funnel_with_actions_and_props_with_zero_person_ids(self):
- # only a person-on-event test
- if not get_instance_setting("PERSON_ON_EVENTS_ENABLED"):
- return True
-
- sign_up_action = _create_action(
- name="sign up",
- team=self.team,
- properties=[
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ],
- )
-
- filters = {
- "actions": [
- {"id": sign_up_action.id, "math": "dau", "order": 0},
- {"id": sign_up_action.id, "math": "weekly_active", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- person1_stopped_after_two_signups = _create_person(
- distinct_ids=["stopped_after_signup1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- )
-
- person2_stopped_after_signup = _create_person(
- distinct_ids=["stopped_after_signup2"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup2",
- properties={"key": "val"},
- )
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="zero_person_id",
- properties={"key": "val"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="zero_person_id",
- properties={"key": "val"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "sign up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["count"], 1)
-
- # check ordering of people in first step
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [person1_stopped_after_two_signups.uuid],
- )
-
- @also_test_with_materialized_columns(["key"])
- @skip("Flaky funnel test")
- def test_funnel_with_actions_and_events(self):
- sign_up_action = _create_action(
- name="sign up",
- team=self.team,
- properties=[
- {
- "key": "key",
- "type": "event",
- "value": ["val"],
- "operator": "exact",
- }
- ],
- )
-
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "user signed up", "type": "events", "order": 1},
- ],
- "actions": [
- {"id": sign_up_action.id, "math": "dau", "order": 2},
- {"id": sign_up_action.id, "math": "weekly_active", "order": 3},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
-
- filter = Filter(data=filters, team=self.team)
-
- # event
- person1_stopped_after_two_signups = _create_person(
- distinct_ids=["stopped_after_signup1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- timestamp="2021-05-01 00:00:00",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- timestamp="2021-05-01 00:00:01",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- timestamp="2021-05-01 00:00:02",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup1",
- properties={"key": "val"},
- timestamp="2021-05-01 00:00:03",
- )
-
- person2_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup2",
- timestamp="2021-05-01 00:00:04",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup2",
- timestamp="2021-05-01 00:00:05",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_signup2",
- properties={"key": "val"},
- timestamp="2021-05-01 00:00:06",
- )
-
- person3 = _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 00:00:07",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person3",
- properties={"key": "val"},
- timestamp="2021-05-01 00:00:08",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 00:00:09",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person3",
- properties={"key": "val"},
- timestamp="2021-05-01 00:00:10",
- )
-
- person4 = _create_person(distinct_ids=["person4"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person4",
- timestamp="2021-05-01 00:00:11",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person4",
- properties={"key": "val"},
- timestamp="2021-05-01 00:00:12",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person4",
- timestamp="2021-05-01 00:00:13",
- )
-
- _create_person(distinct_ids=["person5"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person5",
- properties={"key": "val"},
- timestamp="2021-05-01 00:00:14",
- )
-
- with freeze_time("2021-05-02"):
- result = Funnel(filter, self.team).run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 4)
- self.assertEqual(result[1]["count"], 4)
- self.assertEqual(result[2]["count"], 3)
- self.assertEqual(result[3]["count"], 1)
-
- # check ordering of people in steps
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- person3.uuid,
- person4.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- person3.uuid,
- person4.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [
- person1_stopped_after_two_signups.uuid,
- person2_stopped_after_signup.uuid,
- person3.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 4),
- [person1_stopped_after_two_signups.uuid],
- )
-
- @also_test_with_materialized_columns(["$current_url"])
- def test_funnel_with_matching_properties(self):
- filters = {
- "events": [
- {"id": "user signed up", "order": 0},
- {
- "id": "$pageview",
- "order": 1,
- "properties": {"$current_url": "aloha.com"},
- },
- {
- "id": "$pageview",
- "order": 2,
- "properties": {"$current_url": "aloha2.com"},
- }, # different event to above
- {
- "id": "$pageview",
- "order": 3,
- "properties": {"$current_url": "aloha2.com"},
- },
- {"id": "$pageview", "order": 4},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- people = journeys_for(
- {
- "stopped_after_signup1": [{"event": "user signed up"}],
- "stopped_after_pageview1": [
- {"event": "user signed up"},
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha.com"},
- },
- ],
- "stopped_after_pageview2": [
- {"event": "user signed up"},
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha.com"},
- },
- {
- "event": "blaah blaa",
- "properties": {"$current_url": "aloha.com"},
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha2.com"},
- },
- ],
- "stopped_after_pageview3": [
- {"event": "user signed up"},
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha.com"},
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha2.com"},
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha2.com"},
- },
- {"event": "blaah blaa"},
- ],
- "stopped_after_pageview4": [
- {"event": "user signed up"},
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha.com"},
- },
- {"event": "blaah blaa"},
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha2.com"},
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha.com"},
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha2.com"},
- },
- ],
- },
- self.team,
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[1]["name"], "$pageview")
- self.assertEqual(result[4]["name"], "$pageview")
- self.assertEqual(result[0]["count"], 5)
- self.assertEqual(result[1]["count"], 4)
- self.assertEqual(result[2]["count"], 3)
- self.assertEqual(result[3]["count"], 2)
- self.assertEqual(result[4]["count"], 0)
- # check ordering of people in every step
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- people["stopped_after_signup1"].uuid,
- people["stopped_after_pageview1"].uuid,
- people["stopped_after_pageview2"].uuid,
- people["stopped_after_pageview3"].uuid,
- people["stopped_after_pageview4"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- people["stopped_after_pageview1"].uuid,
- people["stopped_after_pageview2"].uuid,
- people["stopped_after_pageview3"].uuid,
- people["stopped_after_pageview4"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [
- people["stopped_after_pageview2"].uuid,
- people["stopped_after_pageview3"].uuid,
- people["stopped_after_pageview4"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 4),
- [
- people["stopped_after_pageview3"].uuid,
- people["stopped_after_pageview4"].uuid,
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 5), [])
-
- def test_funnel_conversion_window(self):
- ids_to_compare = []
- for i in range(10):
- person = _create_person(distinct_ids=[f"user_{i}"], team=self.team)
- ids_to_compare.append(str(person.uuid))
- _create_event(
- event="step one",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-01 00:00:00",
- )
- _create_event(
- event="step two",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-02 00:00:00",
- )
-
- for i in range(10, 25):
- _create_person(distinct_ids=[f"user_{i}"], team=self.team)
- _create_event(
- event="step one",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-01 00:00:00",
- )
- _create_event(
- event="step two",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-10 00:00:00",
- )
-
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- filter = Filter(data={**data})
- results = Funnel(filter, self.team).run()
-
- self.assertEqual(results[0]["count"], 25)
- self.assertEqual(results[1]["count"], 10)
- self.assertEqual(results[2]["count"], 0)
-
- self.assertCountEqual(
- [str(id) for id in self._get_actor_ids_at_step(filter, 2)],
- ids_to_compare,
- )
-
- @snapshot_clickhouse_queries
- def test_funnel_conversion_window_seconds(self):
- ids_to_compare = []
- for i in range(10):
- person = _create_person(distinct_ids=[f"user_{i}"], team=self.team)
- ids_to_compare.append(str(person.uuid))
- _create_event(
- event="step one",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-01 00:00:00",
- )
- _create_event(
- event="step two",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-01 00:00:10",
- )
-
- for i in range(10, 25):
- _create_person(distinct_ids=[f"user_{i}"], team=self.team)
- _create_event(
- event="step one",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-01 00:00:00",
- )
- _create_event(
- event="step two",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-01 00:00:20",
- )
-
- data = {
- "insight": INSIGHT_FUNNELS,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "funnel_window_interval": 15,
- "funnel_window_interval_unit": "second",
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- filter = Filter(data={**data})
- results = Funnel(filter, self.team).run()
-
- self.assertEqual(results[0]["count"], 25)
- self.assertEqual(results[1]["count"], 10)
- self.assertEqual(results[2]["count"], 0)
-
- self.assertCountEqual(
- [str(id) for id in self._get_actor_ids_at_step(filter, 2)],
- ids_to_compare,
- )
-
- def test_funnel_exclusions_invalid_params(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 1,
- "funnel_to_step": 1,
- }
- ],
- }
- filter = Filter(data=filters)
- self.assertRaises(ValidationError, lambda: Funnel(filter, self.team))
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 1,
- "funnel_to_step": 2,
- }
- ]
- }
- )
- self.assertRaises(ValidationError, lambda: Funnel(filter, self.team))
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 2,
- "funnel_to_step": 1,
- }
- ]
- }
- )
- self.assertRaises(ValidationError, lambda: Funnel(filter, self.team))
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 2,
- }
- ]
- }
- )
- self.assertRaises(ValidationError, lambda: Funnel(filter, self.team))
-
- def test_funnel_exclusion_no_end_event(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 1,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- }
- ],
- }
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event 1
- person1 = _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person1",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person1",
- timestamp="2021-05-01 02:00:00",
- )
-
- # event 2
- _create_person(distinct_ids=["person2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person2",
- timestamp="2021-05-01 03:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person2",
- timestamp="2021-05-01 03:30:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person2",
- timestamp="2021-05-01 04:00:00",
- )
-
- # event 3
- _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- # should be discarded, even if nothing happened after x, since within conversion window
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person3",
- timestamp="2021-05-01 06:00:00",
- )
-
- # event 4 - outside conversion window
- person4 = _create_person(distinct_ids=["person4"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person4",
- timestamp="2021-05-01 07:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person4",
- timestamp="2021-05-02 08:00:00",
- )
-
- result = funnel.run()
- self.assertEqual(len(result), 2)
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 1)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person1.uuid, person4.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2), [person1.uuid])
-
- @also_test_with_materialized_columns(["key"])
- def test_funnel_exclusions_with_actions(self):
- sign_up_action = _create_action(
- name="sign up",
- team=self.team,
- properties=[
- {
- "key": "key",
- "type": "event",
- "value": ["val"],
- "operator": "exact",
- }
- ],
- )
-
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "exclusions": [
- {
- "id": sign_up_action.id,
- "type": "actions",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- }
- ],
- }
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event 1
- person1 = _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person1",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person1",
- timestamp="2021-05-01 02:00:00",
- )
-
- # event 2
- _create_person(distinct_ids=["person2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person2",
- timestamp="2021-05-01 03:00:00",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person2",
- properties={"key": "val"},
- timestamp="2021-05-01 03:30:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person2",
- timestamp="2021-05-01 04:00:00",
- )
-
- # event 3
- person3 = _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person3",
- timestamp="2021-05-01 06:00:00",
- )
-
- result = funnel.run()
- self.assertEqual(len(result), 2)
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 2)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person1.uuid, person3.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2), [person1.uuid, person3.uuid])
-
- @also_test_with_materialized_columns(["test_prop"])
- def test_funnel_with_denormalised_properties(self):
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [{"key": "test_prop", "value": "hi"}],
- },
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "properties": [{"key": "test_prop", "value": "hi"}],
- "date_to": "2020-01-14",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- _create_person(distinct_ids=["user_1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_1",
- timestamp="2020-01-02T14:00:00Z",
- properties={"test_prop": "hi"},
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="user_1",
- timestamp="2020-01-10T14:00:00Z",
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- def test_advanced_funnel_multiple_exclusions_between_steps(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "$pageview", "type": "events", "order": 1},
- {"id": "insight viewed", "type": "events", "order": 2},
- {"id": "invite teammate", "type": "events", "order": 3},
- {"id": "pageview2", "type": "events", "order": 4},
- ],
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "insight": INSIGHT_FUNNELS,
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- },
- {
- "id": "y",
- "type": "events",
- "funnel_from_step": 2,
- "funnel_to_step": 3,
- },
- ],
- }
-
- _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person1",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person1",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person1",
- timestamp="2021-05-01 03:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person1",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="y",
- distinct_id="person1",
- timestamp="2021-05-01 04:30:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person1",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person1",
- timestamp="2021-05-01 06:00:00",
- )
-
- _create_person(distinct_ids=["person2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person2",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="y",
- distinct_id="person2",
- timestamp="2021-05-01 01:30:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person2",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person2",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="y",
- distinct_id="person2",
- timestamp="2021-05-01 04:30:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person2",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person2",
- timestamp="2021-05-01 05:30:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person2",
- timestamp="2021-05-01 06:00:00",
- )
-
- _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person3",
- timestamp="2021-05-01 01:30:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person3",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person3",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person3",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person3",
- timestamp="2021-05-01 05:30:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person3",
- timestamp="2021-05-01 06:00:00",
- )
-
- person4 = _create_person(distinct_ids=["person4"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person4",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person4",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person4",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person4",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person4",
- timestamp="2021-05-01 06:00:00",
- )
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[4]["count"], 1)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person4.uuid])
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- },
- {
- "id": "y",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- },
- ]
- }
- )
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[4]["count"], 1)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person4.uuid])
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- },
- {
- "id": "y",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- },
- ]
- }
- )
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[4]["count"], 1)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person4.uuid])
-
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 4,
- },
- {
- "id": "y",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 4,
- },
- ]
- }
- )
- funnel = Funnel(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[4]["count"], 1)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person4.uuid])
-
- def test_funnel_with_elements_chain(self):
- person1 = _create_person(distinct_ids=["test"], team_id=self.team.pk)
- _create_event(team=self.team, event="user signed up", distinct_id="test")
- _create_event(
- team=self.team,
- event="$autocapture",
- distinct_id="test",
- properties={"$current_url": "http://example.com/something_else"},
- elements=[Element(tag_name="img"), Element(tag_name="svg")],
- )
-
- person2 = _create_person(distinct_ids=["test2"], team_id=self.team.pk)
- _create_event(team=self.team, event="user signed up", distinct_id="test2")
-
- for tag_name in ["img", "svg"]:
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {
- "id": "$autocapture",
- "name": "$autocapture",
- "order": 1,
- "properties": [
- {
- "key": "tag_name",
- "value": [tag_name],
- "operator": "exact",
- "type": "element",
- }
- ],
- "type": "events",
- },
- ],
- "insight": INSIGHT_FUNNELS,
- }
-
- filter = Filter(data=filters)
- result = Funnel(filter, self.team).run()
-
- self.assertEqual(len(result), 2)
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
-
- self.assertEqual(result[1]["name"], "$autocapture")
- self.assertEqual(result[1]["count"], 1)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1), [person1.uuid, person2.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2), [person1.uuid])
-
- def test_breakdown_values_is_set_on_the_query_with_fewer_than_two_entities(self):
- filter_with_breakdown = {
- "events": [{"id": "with one entity", "type": "events", "order": 0}],
- "breakdown": "something",
- }
-
- try:
- ClickhouseFunnel(Filter(data=filter_with_breakdown), self.team).run()
- except KeyError as ke:
- raise AssertionError(f"Should not have raised a key error: {ke}")
-
- @snapshot_clickhouse_queries
- def test_funnel_with_cohorts_step_filter(self):
- _create_person(
- distinct_ids=["user_1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_1",
- timestamp="2020-01-02T14:00:00Z",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="user_1",
- timestamp="2020-01-10T14:00:00Z",
- )
-
- _create_person(distinct_ids=["user_2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_2",
- timestamp="2020-01-02T14:00:00Z",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="user_2",
- timestamp="2020-01-10T14:00:00Z",
- )
-
- cohort = Cohort.objects.create(
- team=self.team,
- groups=[
- {
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ]
- }
- ],
- )
-
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [{"type": "cohort", "key": "id", "value": cohort.pk}],
- },
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- }
-
- result = ClickhouseFunnel(Filter(data=filters), self.team).run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 1)
-
- @snapshot_clickhouse_queries
- def test_funnel_with_precalculated_cohort_step_filter(self):
- _create_person(
- distinct_ids=["user_1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_1",
- timestamp="2020-01-02T14:00:00Z",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="user_1",
- timestamp="2020-01-10T14:00:00Z",
- )
-
- _create_person(distinct_ids=["user_2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_2",
- timestamp="2020-01-02T14:00:00Z",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="user_2",
- timestamp="2020-01-10T14:00:00Z",
- )
-
- cohort = Cohort.objects.create(
- team=self.team,
- groups=[
- {
- "properties": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- }
- ]
- }
- ],
- )
-
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [
- {
- "type": "precalculated-cohort",
- "key": "id",
- "value": cohort.pk,
- }
- ],
- },
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- }
-
- # converts to precalculated-cohort due to simplify filters
- cohort.calculate_people_ch(pending_version=0)
-
- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- result = ClickhouseFunnel(Filter(data=filters), self.team).run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 1)
-
- @snapshot_clickhouse_queries
- def test_funnel_with_static_cohort_step_filter(self):
- _create_person(
- distinct_ids=["user_1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]"},
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_1",
- timestamp="2020-01-02T14:00:00Z",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="user_1",
- timestamp="2020-01-10T14:00:00Z",
- )
-
- _create_person(distinct_ids=["user_2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_2",
- timestamp="2020-01-02T14:00:00Z",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="user_2",
- timestamp="2020-01-10T14:00:00Z",
- )
-
- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)
- cohort.insert_users_by_list(["user_2", "rando"])
-
- filters = {
- "events": [
- {
- "id": "user signed up",
- "type": "events",
- "order": 0,
- "properties": [{"type": "static-cohort", "key": "id", "value": cohort.pk}],
- },
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- }
-
- result = ClickhouseFunnel(Filter(data=filters), self.team).run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 1)
-
- self.assertEqual(result[1]["name"], "paid")
- self.assertEqual(result[1]["count"], 1)
-
- @snapshot_clickhouse_queries
- @also_test_with_materialized_columns(["$current_url"], person_properties=["email", "age"])
- def test_funnel_with_property_groups(self):
- filters = {
- "date_from": "2020-01-01 00:00:00",
- "date_to": "2020-07-01 00:00:00",
- "events": [
- {"id": "user signed up", "order": 0},
- {
- "id": "$pageview",
- "order": 1,
- "properties": {"$current_url": "aloha.com"},
- },
- {
- "id": "$pageview",
- "order": 2,
- "properties": {"$current_url": "aloha2.com"},
- }, # different event to above
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".com",
- "type": "person",
- },
- {
- "key": "age",
- "operator": "exact",
- "value": "20",
- "type": "person",
- },
- ],
- },
- {
- "type": "OR",
- "values": [
- {
- "key": "email",
- "operator": "icontains",
- "value": ".org",
- "type": "person",
- },
- {
- "key": "age",
- "operator": "exact",
- "value": "28",
- "type": "person",
- },
- ],
- },
- ],
- },
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- people = {}
- people["stopped_after_signup1"] = _create_person(
- distinct_ids=["stopped_after_signup1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]", "age": "18"},
- )
- people["stopped_after_pageview1"] = _create_person(
- distinct_ids=["stopped_after_pageview1"],
- team_id=self.team.pk,
- properties={"email": "[email protected]", "age": "28"},
- )
- people["stopped_after_pageview2"] = _create_person(
- distinct_ids=["stopped_after_pageview2"],
- team_id=self.team.pk,
- properties={"email": "[email protected]", "age": "28"},
- )
- people["stopped_after_pageview3"] = _create_person(
- distinct_ids=["stopped_after_pageview3"],
- team_id=self.team.pk,
- properties={"email": "[email protected]", "age": "28"},
- )
- people["stopped_after_pageview4"] = _create_person(
- distinct_ids=["stopped_after_pageview4"],
- team_id=self.team.pk,
- properties={"email": "[email protected]", "age": "18"},
- )
-
- # event
- journeys_for(
- {
- "stopped_after_signup1": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- "stopped_after_pageview1": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- "stopped_after_pageview2": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 5, 1, 0),
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha.com"},
- "timestamp": datetime(2020, 5, 2, 0),
- },
- ],
- "stopped_after_pageview3": [
- {
- "event": "user signed up",
- "timestamp": datetime(2020, 5, 1, 0),
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha.com"},
- "timestamp": datetime(2020, 5, 2, 0),
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha2.com"},
- "timestamp": datetime(2020, 5, 3, 0),
- },
- ],
- "stopped_after_pageview4": [
- # {"event": "user signed up"}, # no signup, so not in funnel
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha.com"},
- "timestamp": datetime(2020, 5, 2, 0),
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha2.com"},
- "timestamp": datetime(2020, 5, 3, 0),
- },
- {
- "event": "$pageview",
- "properties": {"$current_url": "aloha2.com"},
- "timestamp": datetime(2020, 5, 4, 0),
- },
- ],
- },
- self.team,
- create_people=False,
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[1]["name"], "$pageview")
- self.assertEqual(result[2]["name"], "$pageview")
- self.assertEqual(result[0]["count"], 3)
- self.assertEqual(result[1]["count"], 2)
- self.assertEqual(result[2]["count"], 1)
- # check ordering of people in every step
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- people["stopped_after_pageview1"].uuid,
- people["stopped_after_pageview2"].uuid,
- people["stopped_after_pageview3"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- people["stopped_after_pageview2"].uuid,
- people["stopped_after_pageview3"].uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [people["stopped_after_pageview3"].uuid],
- )
-
- @snapshot_clickhouse_queries
- def test_timezones(self):
- self.team.timezone = "US/Pacific"
- self.team.save()
-
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-14",
- }
-
- filter = Filter(data=filters)
- funnel = Funnel(filter, self.team)
-
- # event
- _create_person(distinct_ids=["user_1"], team_id=self.team.pk)
- #  this event shouldn't appear as in US/Pacific this would be the previous day
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="user_1",
- timestamp="2020-01-01T01:00:00Z",
- )
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 0)
-
- def test_funnel_with_sampling(self):
- action_play_movie = Action.objects.create(
- team=self.team,
- name="watched movie",
- steps_json=[
- {
- "event": "$autocapture",
- "tag_name": "a",
- "href": "/movie",
- }
- ],
- )
-
- funnel = self._basic_funnel(
- filters={
- "events": [{"id": "user signed up", "type": "events", "order": 0}],
- "actions": [{"id": action_play_movie.pk, "type": "actions", "order": 2}],
- "funnel_window_days": 14,
- "sampling_factor": 1,
- }
- )
-
- # events
- person_factory(distinct_ids=["stopped_after_signup"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_signup")
-
- person_factory(distinct_ids=["stopped_after_pay"], team_id=self.team.pk)
- self._signup_event(distinct_id="stopped_after_pay")
- self._movie_event(distinct_id="completed_movie")
-
- person_factory(
- distinct_ids=["had_anonymous_id", "completed_movie"],
- team_id=self.team.pk,
- )
- self._signup_event(distinct_id="had_anonymous_id")
- self._movie_event(distinct_id="completed_movie")
-
- person_factory(distinct_ids=["just_did_movie"], team_id=self.team.pk)
- self._movie_event(distinct_id="just_did_movie")
-
- person_factory(distinct_ids=["wrong_order"], team_id=self.team.pk)
- self._movie_event(distinct_id="wrong_order")
- self._signup_event(distinct_id="wrong_order")
-
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 4)
-
- self.assertEqual(result[1]["name"], "watched movie")
- self.assertEqual(result[1]["count"], 1)
-
- def test_hogql_aggregation(self):
- # first person
- person_factory(
- distinct_ids=["user"],
- team_id=self.team.pk,
- properties={"email": "[email protected]", "common_prop": "yes"},
- )
- self._signup_event(distinct_id="user", properties={"$session_id": "1"})
- self._add_to_cart_event(distinct_id="user", properties={"$session_id": "1"})
- self._checkout_event(distinct_id="user", properties={"$session_id": "1"})
-
- self._signup_event(distinct_id="user", properties={"$session_id": "2"})
- self._add_to_cart_event(distinct_id="user", properties={"$session_id": "2"})
-
- # second person
- person_factory(
- distinct_ids=["second"],
- team_id=self.team.pk,
- properties={"email": "[email protected]", "common_prop": "yes"},
- )
- self._signup_event(distinct_id="second", properties={"$session_id": "3"})
-
- basic_filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "added to cart", "type": "events", "order": 0},
- {"id": "checked out", "type": "events", "order": 0},
- ],
- "funnel_window_days": 14,
- }
-
- # without hogql aggregation
- result = self._basic_funnel(filters=basic_filters).run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[0]["count"], 2)
- self.assertEqual(result[1]["count"], 1)
- self.assertEqual(result[2]["count"], 1)
-
- # properties.$session_id
- result = self._basic_funnel(
- filters={
- **basic_filters,
- "funnel_aggregate_by_hogql": "properties.$session_id",
- }
- ).run()
- self.assertEqual(result[0]["count"], 3)
- self.assertEqual(result[1]["count"], 2)
- self.assertEqual(result[2]["count"], 1)
-
- # distinct_id
- result = self._basic_funnel(filters={**basic_filters, "funnel_aggregate_by_hogql": "distinct_id"}).run()
- self.assertEqual(result[0]["count"], 2)
- self.assertEqual(result[1]["count"], 1)
- self.assertEqual(result[2]["count"], 1)
-
- # person_id
- result = self._basic_funnel(filters={**basic_filters, "funnel_aggregate_by_hogql": "person_id"}).run()
- self.assertEqual(result[0]["count"], 2)
- self.assertEqual(result[1]["count"], 1)
- self.assertEqual(result[2]["count"], 1)
-
- # # person.properties.common_prop - not supported!
- # result = self._basic_funnel(
- # filters={**basic_filters, "funnel_aggregate_by_hogql": "person.properties.common_prop"}
- # ).run()
- # self.assertEqual(result[0]["count"], 1)
- # self.assertEqual(result[1]["count"], 1)
- # self.assertEqual(result[2]["count"], 1)
-
- def test_funnel_all_events_with_properties(self):
- person_factory(distinct_ids=["user"], team_id=self.team.pk)
- self._signup_event(distinct_id="user")
- self._add_to_cart_event(distinct_id="user", properties={"is_saved": True})
-
- filters = {
- "events": [
- {
- "type": "events",
- "id": "user signed up",
- "order": 0,
- "name": "user signed up",
- "math": "total",
- },
- {
- "type": "events",
- "id": None,
- "order": 1,
- "name": "All events",
- "math": "total",
- "properties": [
- {
- "key": "is_saved",
- "value": ["true"],
- "operator": "exact",
- "type": "event",
- }
- ],
- },
- ],
- "funnel_window_days": 14,
- }
-
- result = self._basic_funnel(filters=filters).run()
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(result[1]["count"], 1)
-
- def test_funnel_all_events_via_action(self):
- person_factory(distinct_ids=["user"], team_id=self.team.pk)
- self._signup_event(distinct_id="user")
- self._add_to_cart_event(distinct_id="user", properties={"is_saved": True})
-
- action_checkout_all = Action.objects.create(
- team=self.team,
- name="user signed up",
- steps_json=[
- {"event": "checked out"}, # not performed
- {"event": None}, # matches all
- ],
- )
-
- filters = {
- "events": [{"id": "user signed up", "type": "events", "order": 0}],
- "actions": [{"id": action_checkout_all.pk, "type": "actions", "order": 1}],
- "funnel_window_days": 14,
- }
-
- result = self._basic_funnel(filters=filters).run()
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(result[1]["count"], 1)
-
- def test_funnel_personless_events_are_supported(self):
- personless_user = uuid.uuid4()
- self._signup_event(distinct_id=personless_user, person_id=personless_user)
- self._add_to_cart_event(distinct_id=personless_user, person_id=personless_user)
-
- filters = {
- "events": [
- {
- "type": "events",
- "id": "user signed up",
- "order": 0,
- "name": "user signed up",
- "math": "total",
- },
- {
- "type": "events",
- "id": "added to cart",
- "order": 1,
- "name": "added to cart",
- "math": "total",
- },
- ],
- "funnel_window_days": 14,
- }
-
- result = self._basic_funnel(filters=filters).run()
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(result[1]["count"], 1)
-
- return TestGetFunnel
-
-
-class TestFOSSFunnel(funnel_test_factory(ClickhouseFunnel, _create_event, _create_person)): # type: ignore[misc]
- maxDiff = None
diff --git a/posthog/queries/funnels/test/test_funnel_persons.py b/posthog/queries/funnels/test/test_funnel_persons.py
deleted file mode 100644
index f96641d2f28d..000000000000
--- a/posthog/queries/funnels/test/test_funnel_persons.py
+++ /dev/null
@@ -1,619 +0,0 @@
-from datetime import datetime, timedelta
-from uuid import UUID
-
-from freezegun import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_event,
- _create_person,
- also_test_with_materialized_columns,
- flush_persons_and_events,
- snapshot_clickhouse_queries,
-)
-
-from django.utils import timezone
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models import Filter
-from posthog.models.event.util import bulk_create_events
-from posthog.queries.funnels.funnel_persons import ClickhouseFunnelActors
-from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
-from posthog.test.test_journeys import journeys_for
-
-from products.cohorts.backend.models.cohort import Cohort
-
-FORMAT_TIME = "%Y-%m-%d 00:00:00"
-MAX_STEP_COLUMN = 0
-COUNT_COLUMN = 1
-PERSON_ID_COLUMN = 2
-
-
-class TestFunnelPersons(ClickhouseTestMixin, APIBaseTest):
- def _create_sample_data_multiple_dropoffs(self):
- for i in range(35):
- _create_person(distinct_ids=[f"user_{i}"], team=self.team)
- flush_persons_and_events()
- events = []
- for i in range(5):
- events.append(
- {
- "event": "step one",
- "distinct_id": f"user_{i}",
- "team": self.team,
- "timestamp": "2021-05-01 00:00:00",
- }
- )
- events.append(
- {
- "event": "step two",
- "distinct_id": f"user_{i}",
- "team": self.team,
- "timestamp": "2021-05-03 00:00:00",
- }
- )
- events.append(
- {
- "event": "step three",
- "distinct_id": f"user_{i}",
- "team": self.team,
- "timestamp": "2021-05-05 00:00:00",
- }
- )
-
- for i in range(5, 15):
- events.append(
- {
- "event": "step one",
- "distinct_id": f"user_{i}",
- "team": self.team,
- "timestamp": "2021-05-01 00:00:00",
- }
- )
- events.append(
- {
- "event": "step two",
- "distinct_id": f"user_{i}",
- "team": self.team,
- "timestamp": "2021-05-03 00:00:00",
- }
- )
-
- for i in range(15, 35):
- events.append(
- {
- "event": "step one",
- "distinct_id": f"user_{i}",
- "team": self.team,
- "timestamp": "2021-05-01 00:00:00",
- }
- )
- bulk_create_events(events)
-
- def _create_browser_breakdown_events(self):
- person1 = _create_person(
- distinct_ids=["person1"],
- team_id=self.team.pk,
- properties={"$country": "PL"},
- )
- person2 = _create_person(
- distinct_ids=["person2"],
- team_id=self.team.pk,
- properties={"$country": "EE"},
- )
- journeys_for(
- {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome", "$browser_version": "95"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$browser": "Chrome", "$browser_version": "95"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 15),
- "properties": {"$browser": "Chrome", "$browser_version": "95"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Safari", "$browser_version": "14"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "Safari", "$browser_version": "14"},
- },
- ],
- },
- self.team,
- create_people=False,
- )
-
- return person1, person2
-
- def test_first_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(35, len(results))
-
- def test_last_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 3,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(5, len(results))
-
- def test_second_step_dropoff(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": -2,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(20, len(results))
-
- def test_last_step_dropoff(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": -3,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(10, len(results))
-
- def _create_sample_data(self):
- for i in range(110):
- _create_person(distinct_ids=[f"user_{i}"], team=self.team)
- _create_event(
- event="step one",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-01 00:00:00",
- )
- _create_event(
- event="step two",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-03 00:00:00",
- )
- _create_event(
- event="step three",
- distinct_id=f"user_{i}",
- team=self.team,
- timestamp="2021-05-05 00:00:00",
- )
-
- def test_basic_offset(self):
- self._create_sample_data()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- filter = Filter(data=data)
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(100, len(results))
-
- filter_offset = Filter(data={**data, "offset": 100})
- _, results, _ = ClickhouseFunnelActors(filter_offset, self.team).get_actors()
- self.assertEqual(10, len(results))
-
- def test_steps_with_custom_steps_parameter_are_equivalent_to_funnel_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- base_filter = Filter(data=data)
-
- parameters = [
- #  funnel_step, custom_steps, expected_results
- (1, [1, 2, 3], 35),
- (2, [2, 3], 15),
- (3, [3], 5),
- (-2, [1], 20),
- (-3, [2], 10),
- ]
-
- for funnel_step, custom_steps, expected_count in parameters:
- filter = base_filter.shallow_clone({"funnel_step": funnel_step})
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
-
- new_filter = base_filter.shallow_clone({"funnel_custom_steps": custom_steps})
- _, new_results, _ = ClickhouseFunnelActors(new_filter, self.team).get_actors()
-
- self.assertEqual(new_results, results)
- self.assertEqual(len(results), expected_count)
-
- def test_steps_with_custom_steps_parameter_where_funnel_step_equivalence_isnt_possible(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- base_filter = Filter(data=data)
-
- parameters = [
- # custom_steps, expected_results
- ([1, 2], 30),
- ([1, 3], 25),
- ([3, 1], 25),
- ([1, 3, 3, 1], 25),
- ]
-
- for custom_steps, expected_count in parameters:
- new_filter = base_filter.shallow_clone({"funnel_custom_steps": custom_steps})
- _, new_results, _ = ClickhouseFunnelActors(new_filter, self.team).get_actors()
-
- self.assertEqual(len(new_results), expected_count)
-
- def test_steps_with_custom_steps_parameter_overrides_funnel_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 1, # means custom steps = [1,2,3]
- "funnel_custom_steps": [3],
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- _, results, _ = ClickhouseFunnelActors(Filter(data=data), self.team).get_actors()
-
- self.assertEqual(len(results), 5)
-
- @also_test_with_materialized_columns(["$browser"])
- def test_first_step_breakdowns(self):
- person1, person2 = self._create_browser_breakdown_events()
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "breakdown_type": "event",
- "breakdown": "$browser",
- }
- )
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
-
- self.assertCountEqual([val["id"] for val in results], [person1.uuid, person2.uuid])
-
- _, results, _ = ClickhouseFunnelActors(
- filter.shallow_clone({"funnel_step_breakdown": "Chrome"}), self.team
- ).get_actors()
-
- self.assertCountEqual([val["id"] for val in results], [person1.uuid])
-
- _, results, _ = ClickhouseFunnelActors(
- filter.shallow_clone({"funnel_step_breakdown": "Safari"}), self.team
- ).get_actors()
-
- self.assertCountEqual([val["id"] for val in results], [person2.uuid])
-
- def test_first_step_breakdowns_with_multi_property_breakdown(self):
- person1, person2 = self._create_browser_breakdown_events()
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "breakdown_type": "event",
- "breakdown": ["$browser", "$browser_version"],
- }
- )
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
-
- self.assertCountEqual([val["id"] for val in results], [person1.uuid, person2.uuid])
-
- _, results, _ = ClickhouseFunnelActors(
- filter.shallow_clone({"funnel_step_breakdown": ["Chrome", "95"]}), self.team
- ).get_actors()
-
- self.assertCountEqual([val["id"] for val in results], [person1.uuid])
-
- _, results, _ = ClickhouseFunnelActors(
- filter.shallow_clone({"funnel_step_breakdown": ["Safari", "14"]}), self.team
- ).get_actors()
- self.assertCountEqual([val["id"] for val in results], [person2.uuid])
-
- @also_test_with_materialized_columns(person_properties=["$country"])
- def test_first_step_breakdown_person(self):
- person1, person2 = self._create_browser_breakdown_events()
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "breakdown_type": "person",
- "breakdown": "$country",
- }
- )
-
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertCountEqual([val["id"] for val in results], [person1.uuid, person2.uuid])
-
- _, results, _ = ClickhouseFunnelActors(
- filter.shallow_clone({"funnel_step_breakdown": "EE"}), self.team
- ).get_actors()
- self.assertCountEqual([val["id"] for val in results], [person2.uuid])
-
- # Check custom_steps give same answers for breakdowns
- _, custom_step_results, _ = ClickhouseFunnelActors(
- filter.shallow_clone({"funnel_step_breakdown": "EE", "funnel_custom_steps": [1, 2, 3]}),
- self.team,
- ).get_actors()
- self.assertEqual(results, custom_step_results)
-
- _, results, _ = ClickhouseFunnelActors(
- filter.shallow_clone({"funnel_step_breakdown": "PL"}), self.team
- ).get_actors()
- self.assertCountEqual([val["id"] for val in results], [person1.uuid])
-
- # Check custom_steps give same answers for breakdowns
- _, custom_step_results, _ = ClickhouseFunnelActors(
- filter.shallow_clone({"funnel_step_breakdown": "PL", "funnel_custom_steps": [1, 2, 3]}),
- self.team,
- ).get_actors()
- self.assertEqual(results, custom_step_results)
-
- @also_test_with_materialized_columns(["$browser"], verify_no_jsonextract=False)
- def test_funnel_cohort_breakdown_persons(self):
- person = _create_person(distinct_ids=[f"person1"], team_id=self.team.pk, properties={"key": "value"})
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id=f"person1",
- properties={},
- timestamp="2020-01-02T12:00:00Z",
- )
- cohort = Cohort.objects.create(
- team=self.team,
- name="test_cohort",
- groups=[{"properties": [{"key": "key", "value": "value", "type": "person"}]}],
- )
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {"id": "play movie", "order": 1},
- {"id": "buy", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "breakdown_type": "cohort",
- "breakdown": [cohort.pk],
- }
- filter = Filter(data=filters)
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(results[0]["id"], person.uuid)
-
- @snapshot_clickhouse_queries
- @freeze_time("2021-01-02 00:00:00.000Z")
- def test_funnel_person_recordings(self):
- p1 = _create_person(distinct_ids=[f"user_1"], team=self.team)
- _create_event(
- event="step one",
- distinct_id="user_1",
- team=self.team,
- timestamp=timezone.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
- properties={"$session_id": "s1", "$window_id": "w1"},
- event_uuid="11111111-1111-1111-1111-111111111111",
- )
- _create_event(
- event="step two",
- distinct_id="user_1",
- team=self.team,
- timestamp=(timezone.now() + timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S.%f"),
- properties={"$session_id": "s2", "$window_id": "w2"},
- event_uuid="21111111-1111-1111-1111-111111111111",
- )
- timestamp = datetime(2021, 1, 3, 0, 0, 0)
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s2",
- distinct_id="user_1",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- )
-
- # First event, but no recording
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "include_recordings": "true",
- }
- )
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(results[0]["id"], p1.uuid)
- self.assertEqual(results[0]["matched_recordings"], [])
-
- # Second event, with recording
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": 2,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "include_recordings": "true",
- }
- )
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(results[0]["id"], p1.uuid)
- self.assertEqual(
- results[0]["matched_recordings"],
- [
- {
- "session_id": "s2",
- "events": [
- {
- "uuid": UUID("21111111-1111-1111-1111-111111111111"),
- "timestamp": timezone.now() + timedelta(days=1),
- "window_id": "w2",
- }
- ],
- }
- ],
- )
-
- # Third event dropoff, with recording
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": -3,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "include_recordings": "true",
- }
- )
- _, results, _ = ClickhouseFunnelActors(filter, self.team).get_actors()
- self.assertEqual(results[0]["id"], p1.uuid)
- self.assertEqual(
- results[0]["matched_recordings"],
- [
- {
- "session_id": "s2",
- "events": [
- {
- "uuid": UUID("21111111-1111-1111-1111-111111111111"),
- "timestamp": timezone.now() + timedelta(days=1),
- "window_id": "w2",
- }
- ],
- }
- ],
- )
diff --git a/posthog/queries/funnels/test/test_funnel_strict.py b/posthog/queries/funnels/test/test_funnel_strict.py
deleted file mode 100644
index 3dca4aaebabf..000000000000
--- a/posthog/queries/funnels/test/test_funnel_strict.py
+++ /dev/null
@@ -1,603 +0,0 @@
-from datetime import datetime
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_action, _create_event, _create_person
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.filters import Filter
-from posthog.models.instance_setting import override_instance_config
-from posthog.queries.funnels.funnel_strict import ClickhouseFunnelStrict
-from posthog.queries.funnels.funnel_strict_persons import ClickhouseFunnelStrictActors
-from posthog.queries.funnels.test.breakdown_cases import assert_funnel_results_equal, funnel_breakdown_test_factory
-from posthog.queries.funnels.test.conversion_time_cases import funnel_conversion_time_test_factory
-from posthog.test.test_journeys import journeys_for
-
-FORMAT_TIME = "%Y-%m-%d 00:00:00"
-
-
-class TestFunnelStrictStepsBreakdown(
- ClickhouseTestMixin,
- funnel_breakdown_test_factory( # type: ignore
- ClickhouseFunnelStrict,
- ClickhouseFunnelStrictActors,
- _create_event,
- _create_action,
- _create_person,
- ),
-):
- maxDiff = None
-
- def test_basic_funnel_default_funnel_days_breakdown_event(self):
- # TODO: This test and the one below it fail, only for strict funnels. Figure out why and how to fix
- pass
-
- def test_basic_funnel_default_funnel_days_breakdown_action(self):
- pass
-
- def test_basic_funnel_default_funnel_days_breakdown_action_materialized(self):
- pass
-
- def test_strict_breakdown_events_with_multiple_properties(self):
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "play movie", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": "$browser",
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelStrict(filter, self.team)
-
- people = journeys_for(
- {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "blah",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 1, 14),
- "properties": {"$browser": "Chrome"},
- },
- ],
- "person2": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari"},
- },
- {
- "event": "play movie",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Safari"},
- },
- ],
- },
- self.team,
- )
-
- result = funnel.run()
-
- assert_funnel_results_equal(
- result[0],
- [
- {
- "action_id": "sign up",
- "name": "sign up",
- "custom_name": None,
- "order": 0,
- "people": [],
- "count": 1,
- "type": "events",
- "average_conversion_time": None,
- "median_conversion_time": None,
- "breakdown": ["Safari"],
- "breakdown_value": ["Safari"],
- },
- {
- "action_id": "play movie",
- "name": "play movie",
- "custom_name": None,
- "order": 1,
- "people": [],
- "count": 1,
- "type": "events",
- "average_conversion_time": 3600,
- "median_conversion_time": 3600,
- "breakdown": ["Safari"],
- "breakdown_value": ["Safari"],
- },
- ],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ["Safari"]), [people["person2"].uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, ["Safari"]), [people["person2"].uuid])
-
- assert_funnel_results_equal(
- result[1],
- [
- {
- "action_id": "sign up",
- "name": "sign up",
- "custom_name": None,
- "order": 0,
- "people": [],
- "count": 1,
- "type": "events",
- "average_conversion_time": None,
- "median_conversion_time": None,
- "breakdown": ["Chrome"],
- "breakdown_value": ["Chrome"],
- },
- {
- "action_id": "play movie",
- "name": "play movie",
- "custom_name": None,
- "order": 1,
- "people": [],
- "count": 0,
- "type": "events",
- "average_conversion_time": None,
- "median_conversion_time": None,
- "breakdown": ["Chrome"],
- "breakdown_value": ["Chrome"],
- },
- ],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ["Chrome"]), [people["person1"].uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, ["Chrome"]), [])
-
-
-class TestFunnelStrictStepsConversionTime(
- ClickhouseTestMixin,
- funnel_conversion_time_test_factory( # type: ignore
- ClickhouseFunnelStrict,
- ClickhouseFunnelStrictActors,
- _create_event,
- _create_person,
- ),
-):
- maxDiff = None
- pass
-
-
-class TestFunnelStrictSteps(ClickhouseTestMixin, APIBaseTest):
- maxDiff = None
-
- def _get_actor_ids_at_step(self, filter, funnel_step, breakdown_value=None):
- person_filter = filter.shallow_clone({"funnel_step": funnel_step, "funnel_step_breakdown": breakdown_value})
- _, serialized_result, _ = ClickhouseFunnelStrictActors(person_filter, self.team).get_actors()
-
- return [val["id"] for val in serialized_result]
-
- def test_basic_strict_funnel(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "events": [
- {"id": "user signed up", "order": 0},
- {"id": "$pageview", "order": 1},
- {"id": "insight viewed", "order": 2},
- ],
- }
- )
-
- funnel = ClickhouseFunnelStrict(filter, self.team)
-
- person1_stopped_after_signup = _create_person(
- distinct_ids=["stopped_after_signup1"],
- team_id=self.team.pk,
- properties={"test": "okay"},
- )
- _create_event(team=self.team, event="user signed up", distinct_id="stopped_after_signup1")
-
- person2_stopped_after_one_pageview = _create_person(
- distinct_ids=["stopped_after_pageview1"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview1")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview1",
- )
-
- person3_stopped_after_insight_view = _create_person(
- distinct_ids=["stopped_after_insightview"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview")
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview",
- )
-
- person4_stopped_after_insight_view_not_strict_order = _create_person(
- distinct_ids=["stopped_after_insightview2"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview2",
- )
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview2")
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview2")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview2",
- )
-
- person5_stopped_after_insight_view_random = _create_person(
- distinct_ids=["stopped_after_insightview3"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview3")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview3",
- )
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview3")
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview3")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview3",
- )
-
- person6 = _create_person(distinct_ids=["person6"], team_id=self.team.pk)
- _create_event(team=self.team, event="blaah blaa", distinct_id="person6")
- _create_event(team=self.team, event="user signed up", distinct_id="person6")
- _create_event(team=self.team, event="blaah blaa", distinct_id="person6")
- _create_event(team=self.team, event="$pageview", distinct_id="person6")
-
- person7 = _create_person(distinct_ids=["person7"], team_id=self.team.pk)
- _create_event(team=self.team, event="blaah blaa", distinct_id="person7")
- _create_event(team=self.team, event="user signed up", distinct_id="person7")
- _create_event(team=self.team, event="$pageview", distinct_id="person7")
- _create_event(team=self.team, event="insight viewed", distinct_id="person7")
- _create_event(team=self.team, event="blaah blaa", distinct_id="person7")
-
- _create_person(distinct_ids=["stopped_after_insightview6"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview6",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview6")
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[1]["name"], "$pageview")
- self.assertEqual(result[2]["name"], "insight viewed")
- self.assertEqual(result[0]["count"], 7)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_signup.uuid,
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- person4_stopped_after_insight_view_not_strict_order.uuid,
- person5_stopped_after_insight_view_random.uuid,
- person6.uuid,
- person7.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [person3_stopped_after_insight_view.uuid, person7.uuid],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 3), [person7.uuid])
-
- with override_instance_config("AGGREGATE_BY_DISTINCT_IDS_TEAMS", f"{self.team.pk}"):
- result = funnel.run()
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[1]["name"], "$pageview")
- self.assertEqual(result[2]["name"], "insight viewed")
- self.assertEqual(result[0]["count"], 7)
-
- def test_advanced_strict_funnel(self):
- sign_up_action = _create_action(
- name="sign up",
- team=self.team,
- properties=[{"key": "key", "type": "event", "value": ["val"], "operator": "exact"}],
- )
-
- view_action = _create_action(
- name="pageview",
- team=self.team,
- properties=[{"key": "key", "type": "event", "value": ["val"], "operator": "exact"}],
- )
-
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "$pageview", "type": "events", "order": 2},
- ],
- "actions": [
- {"id": sign_up_action.id, "math": "dau", "order": 1},
- {"id": view_action.id, "math": "weekly_active", "order": 3},
- ],
- "insight": INSIGHT_FUNNELS,
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelStrict(filter, self.team)
-
- person1_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup1"], team_id=self.team.pk)
- _create_event(team=self.team, event="user signed up", distinct_id="stopped_after_signup1")
-
- person2_stopped_after_one_pageview = _create_person(
- distinct_ids=["stopped_after_pageview1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview1",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview1")
-
- person3_stopped_after_insight_view = _create_person(
- distinct_ids=["stopped_after_insightview"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_insightview",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="stopped_after_insightview",
- properties={"key": "val2"},
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview")
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview",
- )
-
- person4 = _create_person(distinct_ids=["person4"], team_id=self.team.pk)
- _create_event(team=self.team, event="blaah blaa", distinct_id="person4")
- _create_event(team=self.team, event="user signed up", distinct_id="person4")
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person4",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person4",
- properties={"key": "val"},
- )
- _create_event(team=self.team, event="blaah blaa", distinct_id="person4")
-
- person5 = _create_person(distinct_ids=["person5"], team_id=self.team.pk)
- _create_event(team=self.team, event="blaah blaa", distinct_id="person5")
- _create_event(team=self.team, event="user signed up", distinct_id="person5")
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person5",
- properties={"key": "val"},
- )
- _create_event(team=self.team, event="$pageview", distinct_id="person5")
- _create_event(team=self.team, event="blaah blaa", distinct_id="person5")
-
- person6 = _create_person(distinct_ids=["person6"], team_id=self.team.pk)
- _create_event(team=self.team, event="blaah blaa", distinct_id="person6")
- _create_event(team=self.team, event="user signed up", distinct_id="person6")
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person6",
- properties={"key": "val"},
- )
- _create_event(team=self.team, event="$pageview", distinct_id="person6")
- _create_event(
- team=self.team,
- event="pageview",
- distinct_id="person6",
- properties={"key": "val1"},
- )
-
- person7 = _create_person(distinct_ids=["person7"], team_id=self.team.pk)
- _create_event(team=self.team, event="blaah blaa", distinct_id="person7")
- _create_event(team=self.team, event="user signed up", distinct_id="person7")
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person7",
- properties={"key": "val"},
- )
- _create_event(team=self.team, event="$pageview", distinct_id="person7")
- _create_event(team=self.team, event="user signed up", distinct_id="person7")
- _create_event(
- team=self.team,
- event="pageview",
- distinct_id="person7",
- properties={"key": "val"},
- )
-
- person8 = _create_person(distinct_ids=["person8"], team_id=self.team.pk)
- _create_event(team=self.team, event="blaah blaa", distinct_id="person8")
- _create_event(team=self.team, event="user signed up", distinct_id="person8")
- _create_event(team=self.team, event="user signed up", distinct_id="person8")
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person8",
- properties={"key": "val"},
- )
- _create_event(team=self.team, event="$pageview", distinct_id="person8")
- _create_event(
- team=self.team,
- event="pageview",
- distinct_id="person8",
- properties={"key": "val"},
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[1]["name"], "sign up")
- self.assertEqual(result[2]["name"], "$pageview")
- self.assertEqual(result[3]["name"], "pageview")
- self.assertEqual(result[0]["count"], 8)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_signup.uuid,
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- person4.uuid,
- person5.uuid,
- person6.uuid,
- person7.uuid,
- person8.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- person3_stopped_after_insight_view.uuid,
- person4.uuid,
- person5.uuid,
- person6.uuid,
- person7.uuid,
- person8.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [person4.uuid, person5.uuid, person6.uuid, person7.uuid, person8.uuid],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 4), [person8.uuid])
-
- def test_basic_strict_funnel_conversion_times(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "events": [
- {"id": "user signed up", "order": 0},
- {"id": "$pageview", "order": 1},
- {"id": "insight viewed", "order": 2},
- ],
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 23:59:59",
- }
- )
-
- funnel = ClickhouseFunnelStrict(filter, self.team)
-
- person1_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- timestamp="2021-05-02 00:00:00",
- )
-
- person2_stopped_after_one_pageview = _create_person(
- distinct_ids=["stopped_after_pageview1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview1",
- timestamp="2021-05-02 00:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="stopped_after_pageview1",
- timestamp="2021-05-02 01:00:00",
- )
-
- person3_stopped_after_insight_view = _create_person(
- distinct_ids=["stopped_after_insightview"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-02 00:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-02 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-02 04:00:00",
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "user signed up")
- self.assertEqual(result[1]["name"], "$pageview")
- self.assertEqual(result[2]["name"], "insight viewed")
- self.assertEqual(result[0]["count"], 3)
-
- self.assertEqual(result[1]["average_conversion_time"], 5400)
- # 1 hour for Person 2, 2 hours for Person 3, average = 1.5 hours
-
- self.assertEqual(result[2]["average_conversion_time"], 7200)
- # 2 hours for Person 3
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_signup.uuid,
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [person3_stopped_after_insight_view.uuid],
- )
diff --git a/posthog/queries/funnels/test/test_funnel_strict_persons.py b/posthog/queries/funnels/test/test_funnel_strict_persons.py
deleted file mode 100644
index 755c5c8a4db6..000000000000
--- a/posthog/queries/funnels/test/test_funnel_strict_persons.py
+++ /dev/null
@@ -1,257 +0,0 @@
-from datetime import datetime, timedelta
-from uuid import UUID
-
-from freezegun import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_event,
- _create_person,
- snapshot_clickhouse_queries,
-)
-
-from django.utils import timezone
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.filters import Filter
-from posthog.queries.funnels.funnel_strict_persons import ClickhouseFunnelStrictActors
-from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
-from posthog.test.test_journeys import journeys_for
-
-FORMAT_TIME = "%Y-%m-%d 00:00:00"
-
-
-class TestFunnelStrictStepsPersons(ClickhouseTestMixin, APIBaseTest):
- def _create_sample_data_multiple_dropoffs(self):
- events_by_person = {}
- for i in range(5):
- events_by_person[f"user_{i}"] = [
- {"event": "step one", "timestamp": datetime(2021, 5, 1)},
- {"event": "step fake", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ]
-
- for i in range(5, 15):
- events_by_person[f"user_{i}"] = [
- {"event": "step one", "timestamp": datetime(2021, 5, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- ]
-
- for i in range(15, 35):
- events_by_person[f"user_{i}"] = [{"event": "step one", "timestamp": datetime(2021, 5, 1)}]
-
- journeys_for(events_by_person, self.team)
-
- def test_first_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, serialized_results, _ = ClickhouseFunnelStrictActors(filter, self.team).get_actors()
- self.assertEqual(35, len(serialized_results))
-
- def test_second_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 2,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, serialized_results, _ = ClickhouseFunnelStrictActors(filter, self.team).get_actors()
- self.assertEqual(10, len(serialized_results))
-
- def test_second_step_dropoff(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": -2,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, serialized_results, _ = ClickhouseFunnelStrictActors(filter, self.team).get_actors()
- self.assertEqual(25, len(serialized_results))
-
- def test_third_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 3,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, serialized_results, _ = ClickhouseFunnelStrictActors(filter, self.team).get_actors()
- self.assertEqual(0, len(serialized_results))
-
- @snapshot_clickhouse_queries
- @freeze_time("2021-01-02 00:00:00.000Z")
- def test_strict_funnel_person_recordings(self):
- p1 = _create_person(distinct_ids=[f"user_1"], team=self.team)
- _create_event(
- event="step one",
- distinct_id="user_1",
- team=self.team,
- timestamp=timezone.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
- properties={"$session_id": "s1", "$window_id": "w1"},
- event_uuid="11111111-1111-1111-1111-111111111111",
- )
- _create_event(
- event="step two",
- distinct_id="user_1",
- team=self.team,
- timestamp=(timezone.now() + timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S.%f"),
- properties={"$session_id": "s2", "$window_id": "w2"},
- event_uuid="21111111-1111-1111-1111-111111111111",
- )
- _create_event(
- event="interupting step",
- distinct_id="user_1",
- team=self.team,
- timestamp=(timezone.now() + timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S.%f"),
- properties={"$session_id": "s2", "$window_id": "w2"},
- event_uuid="21111111-1111-1111-1111-111111111111",
- )
- _create_event(
- event="step three",
- distinct_id="user_1",
- team=self.team,
- timestamp=(timezone.now() + timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S.%f"),
- properties={"$session_id": "s2", "$window_id": "w2"},
- event_uuid="21111111-1111-1111-1111-111111111111",
- )
- timestamp = datetime(2021, 1, 3, 0, 0, 0)
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s2",
- distinct_id="user_1",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- ensure_analytics_event_in_session=False, # Would mess up the strict funnel
- )
-
- # First event, but no recording
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "include_recordings": "true",
- }
- )
- _, results, _ = ClickhouseFunnelStrictActors(filter, self.team).get_actors()
- self.assertEqual(results[0]["id"], p1.uuid)
- self.assertEqual(results[0]["matched_recordings"], [])
-
- # Second event, with recording
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": 2,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "include_recordings": "true",
- }
- )
- _, results, _ = ClickhouseFunnelStrictActors(filter, self.team).get_actors()
- self.assertEqual(results[0]["id"], p1.uuid)
- self.assertEqual(
- results[0]["matched_recordings"],
- [
- {
- "session_id": "s2",
- "events": [
- {
- "uuid": UUID("21111111-1111-1111-1111-111111111111"),
- "timestamp": timezone.now() + timedelta(days=1),
- "window_id": "w2",
- }
- ],
- }
- ],
- )
-
- # Third event dropoff, with recording
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": -3,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "include_recordings": "true",
- }
- )
- _, results, _ = ClickhouseFunnelStrictActors(filter, self.team).get_actors()
- self.assertEqual(results[0]["id"], p1.uuid)
- self.assertEqual(
- results[0]["matched_recordings"],
- [
- {
- "session_id": "s2",
- "events": [
- {
- "uuid": UUID("21111111-1111-1111-1111-111111111111"),
- "timestamp": timezone.now() + timedelta(days=1),
- "window_id": "w2",
- }
- ],
- }
- ],
- )
diff --git a/posthog/queries/funnels/test/test_funnel_time_to_convert.py b/posthog/queries/funnels/test/test_funnel_time_to_convert.py
deleted file mode 100644
index c0a40a6a7840..000000000000
--- a/posthog/queries/funnels/test/test_funnel_time_to_convert.py
+++ /dev/null
@@ -1,639 +0,0 @@
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_event,
- _create_person,
- snapshot_clickhouse_queries,
-)
-from unittest.case import skip
-
-from posthog.constants import INSIGHT_FUNNELS, TRENDS_LINEAR, FunnelOrderType
-from posthog.models.filters import Filter
-from posthog.queries.funnels.funnel_time_to_convert import ClickhouseFunnelTimeToConvert
-
-FORMAT_TIME = "%Y-%m-%d %H:%M:%S"
-FORMAT_TIME_DAY_END = "%Y-%m-%d 23:59:59"
-
-
-class TestFunnelTimeToConvert(ClickhouseTestMixin, APIBaseTest):
- maxDiff = None
-
- @snapshot_clickhouse_queries
- def test_auto_bin_count_single_step(self):
- _create_person(distinct_ids=["user a"], team=self.team)
- _create_person(distinct_ids=["user b"], team=self.team)
- _create_person(distinct_ids=["user c"], team=self.team)
-
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 18:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 19:00:00",
- )
- # Converted from 0 to 1 in 3600 s
- _create_event(
- event="step three",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 21:00:00",
- )
-
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:37:00",
- )
- # Converted from 0 to 1 in 2200 s
-
- _create_event(
- event="step one",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-11 07:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-12 06:00:00",
- )
- # Converted from 0 to 1 in 82_800 s
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- funnel_trends = ClickhouseFunnelTimeToConvert(filter, self.team)
- results = funnel_trends.run()
-
- # Autobinned using the minimum time to convert, maximum time to convert, and sample count
- self.assertEqual(
- results,
- {
- "bins": [
- (
- 2220.0,
- 2,
- ), # Reached step 1 from step 0 in at least 2200 s but less than 29_080 s - users A and B
- (
- 42510.0,
- 0,
- ), # Analogous to above, just an interval (in this case 26_880 s) up - no users
- (
- 82800.0,
- 1,
- ), # Reached step 1 from step 0 in at least 82_800 s but less than 109_680 s - user C
- ],
- "average_conversion_time": 29_540,
- },
- )
-
- def test_auto_bin_count_single_step_duplicate_events(self):
- # Test for CH bug that used to haunt us: https://github.com/ClickHouse/ClickHouse/issues/26580
-
- _create_person(distinct_ids=["user a"], team=self.team)
- _create_person(distinct_ids=["user b"], team=self.team)
- _create_person(distinct_ids=["user c"], team=self.team)
-
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 18:00:00",
- )
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 19:00:00",
- )
- # Converted from 0 to 1 in 3600 s
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 21:00:00",
- )
-
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:00:00",
- )
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:37:00",
- )
- # Converted from 0 to 1 in 2200 s
-
- _create_event(
- event="step one",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-11 07:00:00",
- )
- _create_event(
- event="step one",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-12 06:00:00",
- )
- # Converted from 0 to 1 in 82_800 s
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step one", "order": 1},
- {"id": "step one", "order": 2},
- ],
- }
- )
-
- funnel_trends = ClickhouseFunnelTimeToConvert(filter, self.team)
- results = funnel_trends.run()
-
- # Autobinned using the minimum time to convert, maximum time to convert, and sample count
- self.assertEqual(
- results,
- {
- "bins": [
- (
- 2220.0,
- 2,
- ), # Reached step 1 from step 0 in at least 2200 s but less than 29_080 s - users A and B
- (
- 42510.0,
- 0,
- ), # Analogous to above, just an interval (in this case 26_880 s) up - no users
- (
- 82800.0,
- 1,
- ), # Reached step 1 from step 0 in at least 82_800 s but less than 109_680 s - user C
- ],
- "average_conversion_time": 29_540,
- },
- )
-
- def test_custom_bin_count_single_step(self):
- _create_person(distinct_ids=["user a"], team=self.team)
- _create_person(distinct_ids=["user b"], team=self.team)
- _create_person(distinct_ids=["user c"], team=self.team)
-
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 18:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 19:00:00",
- )
- # Converted from 0 to 1 in 3600 s
- _create_event(
- event="step three",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 21:00:00",
- )
-
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:37:00",
- )
- # Converted from 0 to 1 in 2200 s
-
- _create_event(
- event="step one",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-11 07:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-12 06:00:00",
- )
- # Converted from 0 to 1 in 82_800 s
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- "funnel_window_days": 7,
- "bin_count": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- funnel_trends = ClickhouseFunnelTimeToConvert(filter, self.team)
- results = funnel_trends.run()
-
- # 7 bins, autoscaled to work best with minimum time to convert and maximum time to convert at hand
- self.assertEqual(
- results,
- {
- "bins": [
- (
- 2220.0,
- 2,
- ), # Reached step 1 from step 0 in at least 2200 s but less than 13_732 s - users A and B
- (
- 13732.0,
- 0,
- ), # Analogous to above, just an interval (in this case 13_732 s) up - no users
- (25244.0, 0), # And so on
- (36756.0, 0),
- (48268.0, 0),
- (59780.0, 0),
- (
- 71292.0,
- 1,
- ), # Reached step 1 from step 0 in at least 71_292 s but less than 82_804 s - user C
- (82804.0, 0),
- ],
- "average_conversion_time": 29_540,
- },
- )
-
- @skip("Compatibility issue CH 23.12 (see #21318)")
- @snapshot_clickhouse_queries
- def test_auto_bin_count_total(self):
- _create_person(distinct_ids=["user a"], team=self.team)
- _create_person(distinct_ids=["user b"], team=self.team)
- _create_person(distinct_ids=["user c"], team=self.team)
-
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 18:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 19:00:00",
- )
- _create_event(
- event="step three",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 21:00:00",
- )
- # Converted from 0 to 2 in 10_800 s
-
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:37:00",
- )
-
- _create_event(
- event="step one",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-11 07:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-12 06:00:00",
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- funnel_trends = ClickhouseFunnelTimeToConvert(filter, self.team)
- results = funnel_trends.run()
-
- self.assertEqual(
- results,
- {
- "bins": [
- (
- 10800.0,
- 1,
- ), # Reached step 2 from step 0 in at least 10_800 s but less than 10_860 s - user A
- (
- 10860.0,
- 0,
- ), # Analogous to above, just an interval (in this case 60 s) up - no users
- ],
- "average_conversion_time": 10_800.0,
- },
- )
-
- # Let's verify that behavior with steps unspecified is the same as when first and last steps specified
- funnel_trends_steps_specified = ClickhouseFunnelTimeToConvert(
- Filter(data={**filter._data, "funnel_from_step": 0, "funnel_to_step": 2}),
- self.team,
- )
- results_steps_specified = funnel_trends_steps_specified.run()
-
- self.assertEqual(results, results_steps_specified)
-
- @snapshot_clickhouse_queries
- def test_basic_unordered(self):
- _create_person(distinct_ids=["user a"], team=self.team)
- _create_person(distinct_ids=["user b"], team=self.team)
- _create_person(distinct_ids=["user c"], team=self.team)
-
- _create_event(
- event="step three",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 18:00:00",
- )
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 19:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 21:00:00",
- )
- # Converted from 0 to 1 in 7200 s
-
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:37:00",
- )
- # Converted from 0 to 1 in 2200 s
-
- _create_event(
- event="step two",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-11 07:00:00",
- )
- _create_event(
- event="step one",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-12 06:00:00",
- )
- # Converted from 0 to 1 in 82_800 s
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- "funnel_window_days": 7,
- "funnel_order_type": FunnelOrderType.UNORDERED,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- funnel_trends = ClickhouseFunnelTimeToConvert(filter, self.team)
- results = funnel_trends.run()
-
- # Autobinned using the minimum time to convert, maximum time to convert, and sample count
- self.assertEqual(
- results,
- {
- "bins": [
- (
- 2220.0,
- 2,
- ), # Reached step 1 from step 0 in at least 2200 s but less than 29_080 s - users A and B
- (
- 42510.0,
- 0,
- ), # Analogous to above, just an interval (in this case 26_880 s) up - no users
- (
- 82800.0,
- 1,
- ), # Reached step 1 from step 0 in at least 82_800 s but less than 109_680 s - user C
- ],
- "average_conversion_time": 29540,
- },
- )
-
- @snapshot_clickhouse_queries
- def test_basic_strict(self):
- _create_person(distinct_ids=["user a"], team=self.team)
- _create_person(distinct_ids=["user b"], team=self.team)
- _create_person(distinct_ids=["user c"], team=self.team)
- _create_person(distinct_ids=["user d"], team=self.team)
-
- _create_event(
- event="step one",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 18:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 19:00:00",
- )
- # Converted from 0 to 1 in 3600 s
- _create_event(
- event="step three",
- distinct_id="user a",
- team=self.team,
- timestamp="2021-06-08 21:00:00",
- )
-
- _create_event(
- event="step one",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:37:00",
- )
- # Converted from 0 to 1 in 2200 s
- _create_event(
- event="blah",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:38:00",
- )
- _create_event(
- event="step three",
- distinct_id="user b",
- team=self.team,
- timestamp="2021-06-09 13:39:00",
- )
-
- _create_event(
- event="step one",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-11 07:00:00",
- )
- _create_event(
- event="step two",
- distinct_id="user c",
- team=self.team,
- timestamp="2021-06-12 06:00:00",
- )
- # Converted from 0 to 1 in 82_800 s
-
- _create_event(
- event="step one",
- distinct_id="user d",
- team=self.team,
- timestamp="2021-06-11 07:00:00",
- )
- _create_event(
- event="blah",
- distinct_id="user d",
- team=self.team,
- timestamp="2021-06-12 07:00:00",
- )
- # Blah cancels conversion
- _create_event(
- event="step two",
- distinct_id="user d",
- team=self.team,
- timestamp="2021-06-12 09:00:00",
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- "funnel_window_days": 7,
- "funnel_order_type": FunnelOrderType.STRICT,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- funnel_trends = ClickhouseFunnelTimeToConvert(filter, self.team)
- results = funnel_trends.run()
-
- # Autobinned using the minimum time to convert, maximum time to convert, and sample count
- self.assertEqual(
- results,
- {
- "bins": [
- (
- 2220.0,
- 2,
- ), # Reached step 1 from step 0 in at least 2200 s but less than 29_080 s - users A and B
- (
- 42510.0,
- 0,
- ), # Analogous to above, just an interval (in this case 26_880 s) up - no users
- (
- 82800.0,
- 1,
- ), # Reached step 1 from step 0 in at least 82_800 s but less than 109_680 s - user C
- ],
- "average_conversion_time": 29540,
- },
- )
diff --git a/posthog/queries/funnels/test/test_funnel_trends.py b/posthog/queries/funnels/test/test_funnel_trends.py
deleted file mode 100644
index 135613058b44..000000000000
--- a/posthog/queries/funnels/test/test_funnel_trends.py
+++ /dev/null
@@ -1,1358 +0,0 @@
-from datetime import date, datetime, timedelta
-from zoneinfo import ZoneInfo
-
-from freezegun.api import freeze_time
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_person, snapshot_clickhouse_queries
-
-from posthog.constants import INSIGHT_FUNNELS, TRENDS_LINEAR, FunnelOrderType
-from posthog.models.filters import Filter
-from posthog.queries.funnels.funnel_trends import ClickhouseFunnelTrends
-from posthog.queries.funnels.funnel_trends_persons import ClickhouseFunnelTrendsActors
-from posthog.test.test_journeys import journeys_for
-
-from products.cohorts.backend.models.cohort import Cohort
-
-FORMAT_TIME = "%Y-%m-%d %H:%M:%S"
-FORMAT_TIME_DAY_END = "%Y-%m-%d 23:59:59"
-
-
-class TestFunnelTrends(ClickhouseTestMixin, APIBaseTest):
- maxDiff = None
-
- def _get_actors_at_step(self, filter, entrance_period_start, drop_off):
- person_filter = filter.shallow_clone({"entrance_period_start": entrance_period_start, "drop_off": drop_off})
- funnel_query_builder = ClickhouseFunnelTrendsActors(person_filter, self.team)
- _, serialized_result, _ = funnel_query_builder.get_actors()
-
- return serialized_result
-
- def _create_sample_data(self):
- # five people, three steps
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_two": [
- {"event": "step one", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4)},
- ],
- "user_three": [{"event": "step one", "timestamp": datetime(2021, 5, 6)}],
- "user_four": [{"event": "step none", "timestamp": datetime(2021, 5, 6)}],
- "user_five": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 2)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 3)},
- ],
- "user_six": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_seven": [
- {"event": "step one", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4)},
- ],
- "user_eight": [],
- },
- self.team,
- )
-
- def test_no_event_in_period(self):
- journeys_for(
- {"user a": [{"event": "Step one", "timestamp": datetime(2021, 6, 6, 21)}]},
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- funnel_trends = ClickhouseFunnelTrends(filter, self.team)
- results = funnel_trends._exec_query()
- formatted_results = funnel_trends._format_results(results)
-
- self.assertEqual(len(results), 7)
- self.assertEqual(formatted_results[0]["days"][0], "2021-06-07")
-
- def test_only_one_user_reached_one_step(self):
- journeys_for(
- {"user a": [{"event": "step one", "timestamp": datetime(2021, 6, 7, 19)}]},
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-06-07 00:00:00",
- "date_to": "2021-06-13 23:59:59",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- funnel_trends = ClickhouseFunnelTrends(filter, self.team)
- results = funnel_trends._exec_query()
-
- self.assertEqual(
- results,
- [
- {
- "reached_to_step_count": 0,
- "conversion_rate": 0,
- "reached_from_step_count": 1,
- "timestamp": datetime(2021, 6, 7, 0, 0).replace(tzinfo=ZoneInfo("UTC")),
- },
- {
- "reached_to_step_count": 0,
- "conversion_rate": 0,
- "reached_from_step_count": 0,
- "timestamp": datetime(2021, 6, 8, 0, 0).replace(tzinfo=ZoneInfo("UTC")),
- },
- {
- "reached_to_step_count": 0,
- "conversion_rate": 0,
- "reached_from_step_count": 0,
- "timestamp": datetime(2021, 6, 9, 0, 0).replace(tzinfo=ZoneInfo("UTC")),
- },
- {
- "reached_to_step_count": 0,
- "conversion_rate": 0,
- "reached_from_step_count": 0,
- "timestamp": datetime(2021, 6, 10, 0, 0).replace(tzinfo=ZoneInfo("UTC")),
- },
- {
- "reached_to_step_count": 0,
- "conversion_rate": 0,
- "reached_from_step_count": 0,
- "timestamp": datetime(2021, 6, 11, 0, 0).replace(tzinfo=ZoneInfo("UTC")),
- },
- {
- "reached_to_step_count": 0,
- "conversion_rate": 0,
- "reached_from_step_count": 0,
- "timestamp": datetime(2021, 6, 12, 0, 0).replace(tzinfo=ZoneInfo("UTC")),
- },
- {
- "reached_to_step_count": 0,
- "conversion_rate": 0,
- "reached_from_step_count": 0,
- "timestamp": datetime(2021, 6, 13, 0, 0).replace(tzinfo=ZoneInfo("UTC")),
- },
- ],
- )
-
- # 1 user who dropped off starting 2021-06-07
- funnel_trends_persons_existent_dropped_off_results = self._get_actors_at_step(
- filter, "2021-06-07 00:00:00", True
- )
-
- self.assertEqual(len(funnel_trends_persons_existent_dropped_off_results), 1)
- self.assertEqual(
- [person["distinct_ids"] for person in funnel_trends_persons_existent_dropped_off_results],
- [["user a"]],
- )
-
- # No users converted 2021-06-07
- funnel_trends_persons_nonexistent_converted_results = self._get_actors_at_step(
- filter, "2021-06-07 00:00:00", False
- )
-
- self.assertEqual(len(funnel_trends_persons_nonexistent_converted_results), 0)
-
- # No users dropped off 2021-06-08
- funnel_trends_persons_nonexistent_converted_results = self._get_actors_at_step(
- filter, "2021-06-08 00:00:00", True
- )
-
- self.assertEqual(len(funnel_trends_persons_nonexistent_converted_results), 0)
-
- # minute, hour, day, week, month
- def test_hour_interval(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "hour",
- "date_from": "2021-05-01 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- with freeze_time("2021-05-06T23:40:59Z"):
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
- self.assertEqual(len(results), 144)
-
- def test_day_interval(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 0)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 2)},
- ]
- },
- self.team,
- )
-
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
- self.assertEqual(7, len(results))
-
- persons = self._get_actors_at_step(filter, "2021-05-01 00:00:00", False)
-
- self.assertEqual([person["distinct_ids"] for person in persons], [["user_one"]])
-
- @snapshot_clickhouse_queries
- def test_week_interval(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "week",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 0)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 2)},
- ]
- },
- self.team,
- )
-
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
- persons = self._get_actors_at_step(filter, "2021-04-25 00:00:00", False)
-
- self.assertEqual(2, len(results))
- self.assertEqual([person["distinct_ids"] for person in persons], [["user_one"]])
-
- def test_month_interval(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "month",
- "date_from": "2020-01-01 00:00:00",
- "date_to": "2020-07-01 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2020, 5, 1, 0)},
- {"event": "step two", "timestamp": datetime(2020, 5, 1, 1)},
- {"event": "step three", "timestamp": datetime(2020, 5, 1, 2)},
- ]
- },
- self.team,
- )
-
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
- self.assertEqual(
- results,
- [
- {
- "conversion_rate": 0.0,
- "reached_from_step_count": 0,
- "reached_to_step_count": 0,
- "timestamp": date(2020, 1, 1),
- },
- {
- "conversion_rate": 0.0,
- "reached_from_step_count": 0,
- "reached_to_step_count": 0,
- "timestamp": date(2020, 2, 1),
- },
- {
- "conversion_rate": 0.0,
- "reached_from_step_count": 0,
- "reached_to_step_count": 0,
- "timestamp": date(2020, 3, 1),
- },
- {
- "conversion_rate": 0.0,
- "reached_from_step_count": 0,
- "reached_to_step_count": 0,
- "timestamp": date(2020, 4, 1),
- },
- {
- "conversion_rate": 100.0,
- "reached_from_step_count": 1,
- "reached_to_step_count": 1,
- "timestamp": date(2020, 5, 1),
- },
- {
- "conversion_rate": 0.0,
- "reached_from_step_count": 0,
- "reached_to_step_count": 0,
- "timestamp": date(2020, 6, 1),
- },
- {
- "conversion_rate": 0.0,
- "reached_from_step_count": 0,
- "reached_to_step_count": 0,
- "timestamp": date(2020, 7, 1),
- },
- ],
- )
-
- persons = self._get_actors_at_step(filter, "2020-05-01 00:00:00", False)
-
- self.assertEqual([person["distinct_ids"] for person in persons], [["user_one"]])
-
- def test_all_date_range(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "all",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
-
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 0)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 2)},
- ]
- },
- self.team,
- )
-
- with freeze_time("2021-05-20T13:01:01Z"):
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
- self.assertEqual(20, len(results))
-
- persons = self._get_actors_at_step(filter, "2021-05-01 00:00:00", False)
-
- self.assertEqual([person["distinct_ids"] for person in persons], [["user_one"]])
-
- def test_all_results_for_day_interval(self):
- self._create_sample_data()
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- saturday = results[0] # 5/1
- self.assertEqual(3, saturday["reached_to_step_count"])
- self.assertEqual(3, saturday["reached_from_step_count"])
- self.assertEqual(100, saturday["conversion_rate"])
-
- sunday = results[1] # 5/2
- self.assertEqual(0, sunday["reached_to_step_count"])
- self.assertEqual(2, sunday["reached_from_step_count"])
- self.assertEqual(0, sunday["conversion_rate"])
-
- monday = results[2] # 5/3
- self.assertEqual(0, monday["reached_to_step_count"])
- self.assertEqual(0, monday["reached_from_step_count"])
- self.assertEqual(0, monday["conversion_rate"])
-
- tuesday = results[3] # 5/4
- self.assertEqual(0, tuesday["reached_to_step_count"])
- self.assertEqual(0, tuesday["reached_from_step_count"])
- self.assertEqual(0, tuesday["conversion_rate"])
-
- wednesday = results[4] # 5/5
- self.assertEqual(0, wednesday["reached_to_step_count"])
- self.assertEqual(0, wednesday["reached_from_step_count"])
- self.assertEqual(0, wednesday["conversion_rate"])
-
- thursday = results[5] # 5/6
- self.assertEqual(0, thursday["reached_to_step_count"])
- self.assertEqual(1, thursday["reached_from_step_count"])
- self.assertEqual(0, thursday["conversion_rate"])
-
- friday = results[6] # 5/7
- self.assertEqual(0, friday["reached_to_step_count"])
- self.assertEqual(0, friday["reached_from_step_count"])
- self.assertEqual(0, friday["conversion_rate"])
-
- def test_window_size_one_day(self):
- self._create_sample_data()
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- saturday = results[0] # 5/1
- self.assertEqual(1, saturday["reached_to_step_count"])
- self.assertEqual(3, saturday["reached_from_step_count"])
- self.assertEqual(33.33, saturday["conversion_rate"])
-
- sunday = results[1] # 5/2
- self.assertEqual(0, sunday["reached_to_step_count"])
- self.assertEqual(2, sunday["reached_from_step_count"])
- self.assertEqual(0, sunday["conversion_rate"])
-
- monday = results[2] # 5/3
- self.assertEqual(0, monday["reached_to_step_count"])
- self.assertEqual(0, monday["reached_from_step_count"])
- self.assertEqual(0, monday["conversion_rate"])
-
- tuesday = results[3] # 5/4
- self.assertEqual(0, tuesday["reached_to_step_count"])
- self.assertEqual(0, tuesday["reached_from_step_count"])
- self.assertEqual(0, tuesday["conversion_rate"])
-
- wednesday = results[4] # 5/5
- self.assertEqual(0, wednesday["reached_to_step_count"])
- self.assertEqual(0, wednesday["reached_from_step_count"])
- self.assertEqual(0, wednesday["conversion_rate"])
-
- thursday = results[5] # 5/6
- self.assertEqual(0, thursday["reached_to_step_count"])
- self.assertEqual(1, thursday["reached_from_step_count"])
- self.assertEqual(0, thursday["conversion_rate"])
-
- friday = results[6] # 5/7
- self.assertEqual(0, friday["reached_to_step_count"])
- self.assertEqual(0, friday["reached_from_step_count"])
- self.assertEqual(0, friday["conversion_rate"])
-
- @freeze_time("2021-05-02 12:00:00")
- def test_period_not_final(self):
- now = datetime(2021, 5, 2, 12, 0, 0)
-
- journeys_for(
- {
- "user_eight": [
- {"event": "step one", "timestamp": now},
- {"event": "step two", "timestamp": now + timedelta(minutes=1)},
- {"event": "step three", "timestamp": now + timedelta(minutes=2)},
- ]
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-02 23:59:59",
- "funnel_window_days": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.assertEqual(len(results), 2)
-
- day = results[0] # yesterday
- self.assertEqual(day["reached_from_step_count"], 0)
- self.assertEqual(day["reached_to_step_count"], 0)
- self.assertEqual(day["conversion_rate"], 0)
- self.assertEqual(
- day["timestamp"].replace(tzinfo=ZoneInfo("UTC")),
- datetime(2021, 5, 1, tzinfo=ZoneInfo("UTC")),
- )
-
- day = results[1] # today
- self.assertEqual(day["reached_from_step_count"], 1)
- self.assertEqual(day["reached_to_step_count"], 1)
- self.assertEqual(day["conversion_rate"], 100)
- self.assertEqual(
- day["timestamp"].replace(tzinfo=ZoneInfo("UTC")),
- datetime(2021, 5, 2, tzinfo=ZoneInfo("UTC")),
- )
-
- def test_two_runs_by_single_user_in_one_period(self):
- journeys_for(
- {
- "user_one": [
- # 1st full run
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 0)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 2)},
- # 2nd full run
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 13)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 14)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 15)},
- ]
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-01 23:59:59",
- "funnel_window_days": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.assertEqual(len(results), 1)
-
- day = results[0] # 2021-05-01
- self.assertEqual(day["reached_from_step_count"], 1)
- self.assertEqual(day["reached_to_step_count"], 1)
- self.assertEqual(day["conversion_rate"], 100)
-
- def test_steps_performed_in_period_but_in_reverse(self):
- journeys_for(
- {
- "user_one": [
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 2)},
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 3)},
- ]
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-01 23:59:59",
- "funnel_window_days": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.assertEqual(len(results), 1)
-
- day_1 = results[0] # 2021-05-01
- self.assertEqual(day_1["reached_from_step_count"], 1)
- self.assertEqual(day_1["reached_to_step_count"], 0)
- self.assertEqual(day_1["conversion_rate"], 0)
-
- def test_one_person_in_multiple_periods_and_windows(self):
- journeys_for(
- {
- "user_one": [
- # 1st user's 1st complete run
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 2)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 3)},
- # 1st user's incomplete run
- {"event": "step one", "timestamp": datetime(2021, 5, 3, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3, 2)},
- # 1st user's 2nd complete run
- {"event": "step one", "timestamp": datetime(2021, 5, 4, 11)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4, 12)},
- {"event": "step three", "timestamp": datetime(2021, 5, 4, 13)},
- ],
- "user_two": [
- # 2nd user's incomplete run
- {"event": "step one", "timestamp": datetime(2021, 5, 4, 18)}
- ],
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-04 23:59:59",
- "funnel_window_days": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.assertEqual(len(results), 4)
-
- day_1 = results[0] # 2021-05-01
- self.assertEqual(day_1["reached_from_step_count"], 1)
- self.assertEqual(day_1["reached_to_step_count"], 1)
- self.assertEqual(day_1["conversion_rate"], 100)
-
- day_2 = results[1] # 2021-05-02
- self.assertEqual(day_2["reached_from_step_count"], 0)
- self.assertEqual(day_2["reached_to_step_count"], 0)
- self.assertEqual(day_2["conversion_rate"], 0)
-
- day_3 = results[2] # 2021-05-03
- self.assertEqual(day_3["reached_from_step_count"], 1)
- self.assertEqual(day_3["reached_to_step_count"], 0)
- self.assertEqual(day_3["conversion_rate"], 0)
-
- day_4 = results[3] # 2021-05-04
- self.assertEqual(day_4["reached_from_step_count"], 2)
- self.assertEqual(day_4["reached_to_step_count"], 1)
- self.assertEqual(day_4["conversion_rate"], 50)
-
- # 1 user who dropped off starting # 2021-05-04
- funnel_trends_persons_existent_dropped_off_results = self._get_actors_at_step(
- filter, "2021-05-04 00:00:00", True
- )
-
- self.assertEqual(len(funnel_trends_persons_existent_dropped_off_results), 1)
- self.assertEqual(
- [person["distinct_ids"] for person in funnel_trends_persons_existent_dropped_off_results],
- [["user_two"]],
- )
-
- # 1 user who converted starting # 2021-05-04
- funnel_trends_persons_existent_dropped_off_results = self._get_actors_at_step(
- filter, "2021-05-04 00:00:00", False
- )
-
- self.assertEqual(len(funnel_trends_persons_existent_dropped_off_results), 1)
- self.assertEqual(
- [person["distinct_ids"] for person in funnel_trends_persons_existent_dropped_off_results],
- [["user_one"]],
- )
-
- def test_from_second_step(self):
- journeys_for(
- {
- "user_one": [
- # 1st user's complete run - should fall into the 2021-05-01 bucket even though counting only from 2nd step
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 2, 2)},
- {"event": "step three", "timestamp": datetime(2021, 5, 2, 3)},
- ],
- "user_two": [
- # 2nd user's incomplete run - should not count at all since not reaching 2nd step
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)}
- ],
- "user_three": [
- # 3rd user's incomplete run - should not count at all since reaching 2nd step BUT not the 1st one
- {"event": "step two", "timestamp": datetime(2021, 5, 2, 2)},
- {"event": "step three", "timestamp": datetime(2021, 5, 2, 3)},
- ],
- "user_four": [
- # 4th user's incomplete run - should fall into the 2021-05-02 bucket as entered but not completed
- {"event": "step one", "timestamp": datetime(2021, 5, 2, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 2, 2)},
- ],
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-02 23:59:59",
- "funnel_window_days": 3,
- "funnel_from_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.assertEqual(len(results), 2)
-
- day_1 = results[0] # 2021-05-01
- self.assertEqual(day_1["reached_from_step_count"], 1)
- self.assertEqual(day_1["reached_to_step_count"], 1)
- self.assertEqual(day_1["conversion_rate"], 100)
-
- day_2 = results[1] # 2021-05-02
- self.assertEqual(day_2["reached_from_step_count"], 1)
- self.assertEqual(day_2["reached_to_step_count"], 0)
- self.assertEqual(day_2["conversion_rate"], 0)
-
- def test_to_second_step(self):
- journeys_for(
- {
- "user_one": [
- # 1st user's complete run - should fall into the 2021-05-01 bucket
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 2, 2)},
- {"event": "step three", "timestamp": datetime(2021, 5, 2, 3)},
- ],
- "user_two": [
- # 2nd user's incomplete run - should count as incomplete
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)}
- ],
- "user_three": [
- # 3rd user's incomplete run - should not count at all since reaching 2nd step BUT not the 1st one
- {"event": "step two", "timestamp": datetime(2021, 5, 2, 2)},
- {"event": "step three", "timestamp": datetime(2021, 5, 2, 3)},
- ],
- "user_four": [
- # 4th user's incomplete run - should fall into the 2021-05-02 bucket as entered and completed
- {"event": "step one", "timestamp": datetime(2021, 5, 2, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 2, 2)},
- ],
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-02 23:59:59",
- "funnel_window_days": 3,
- "funnel_to_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.assertEqual(len(results), 2)
-
- day_1 = results[0] # 2021-05-01
- self.assertEqual(day_1["reached_from_step_count"], 2)
- self.assertEqual(day_1["reached_to_step_count"], 1)
- self.assertEqual(day_1["conversion_rate"], 50)
-
- day_2 = results[1] # 2021-05-02
- self.assertEqual(day_2["reached_from_step_count"], 1)
- self.assertEqual(day_2["reached_to_step_count"], 1)
- self.assertEqual(day_2["conversion_rate"], 100)
-
- def test_one_person_in_multiple_periods_and_windows_in_unordered_funnel(self):
- journeys_for(
- {
- "user_one": [
- # 1st user's 1st complete run
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 3)},
- # 1st user's incomplete run
- {"event": "step two", "timestamp": datetime(2021, 5, 3, 1)},
- {"event": "step one", "timestamp": datetime(2021, 5, 3, 2)},
- # 1st user's 2nd complete run
- {"event": "step three", "timestamp": datetime(2021, 5, 4, 11)},
- {"event": "step one", "timestamp": datetime(2021, 5, 4, 12)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4, 13)},
- ],
- "user_two": [
- # 2nd user's incomplete run
- {"event": "step one", "timestamp": datetime(2021, 5, 4, 18)}
- ],
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-04 23:59:59",
- "funnel_window_days": 1,
- "funnel_order_type": FunnelOrderType.UNORDERED,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.assertEqual(len(results), 4)
-
- day_1 = results[0] # 2021-05-01
- self.assertEqual(day_1["reached_from_step_count"], 1)
- self.assertEqual(day_1["reached_to_step_count"], 1)
- self.assertEqual(day_1["conversion_rate"], 100)
-
- day_2 = results[1] # 2021-05-02
- self.assertEqual(day_2["reached_from_step_count"], 0)
- self.assertEqual(day_2["reached_to_step_count"], 0)
- self.assertEqual(day_2["conversion_rate"], 0)
-
- day_3 = results[2] # 2021-05-03
- self.assertEqual(day_3["reached_from_step_count"], 1)
- self.assertEqual(day_3["reached_to_step_count"], 0)
- self.assertEqual(day_3["conversion_rate"], 0)
-
- day_4 = results[3] # 2021-05-04
- self.assertEqual(day_4["reached_from_step_count"], 2)
- self.assertEqual(day_4["reached_to_step_count"], 1)
- self.assertEqual(day_4["conversion_rate"], 50)
-
- # 1 user who dropped off starting # 2021-05-04
- funnel_trends_persons_existent_dropped_off_results = self._get_actors_at_step(
- filter, "2021-05-04 00:00:00", True
- )
-
- self.assertEqual(len(funnel_trends_persons_existent_dropped_off_results), 1)
- self.assertEqual(
- [person["distinct_ids"] for person in funnel_trends_persons_existent_dropped_off_results],
- [["user_two"]],
- )
-
- # 1 user who converted starting # 2021-05-04
- funnel_trends_persons_existent_dropped_off_results = self._get_actors_at_step(
- filter, "2021-05-04 00:00:00", False
- )
-
- self.assertEqual(len(funnel_trends_persons_existent_dropped_off_results), 1)
- self.assertEqual(
- [person["distinct_ids"] for person in funnel_trends_persons_existent_dropped_off_results],
- [["user_one"]],
- )
-
- def test_one_person_in_multiple_periods_and_windows_in_strict_funnel(self):
- journeys_for(
- {
- "user_one": [
- # 1st user's 1st complete run
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 2)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 3)},
- # 1st user's incomplete run
- {"event": "step one", "timestamp": datetime(2021, 5, 3, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3, 2)},
- # broken because strict
- {"event": "blah", "timestamp": datetime(2021, 5, 3, 2, 30)},
- {"event": "step three", "timestamp": datetime(2021, 5, 3, 3)},
- # 1st user's 2nd complete run
- {"event": "step one", "timestamp": datetime(2021, 5, 4, 11)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4, 12)},
- {"event": "step three", "timestamp": datetime(2021, 5, 4, 13)},
- ],
- "user_two": [
- # 2nd user's incomplete run
- {"event": "step one", "timestamp": datetime(2021, 5, 4, 18)},
- # broken because strict
- {"event": "blah", "timestamp": datetime(2021, 5, 4, 18, 20)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4, 19)},
- ],
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-04 23:59:59",
- "funnel_order_type": FunnelOrderType.STRICT,
- "funnel_window_days": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.assertEqual(len(results), 4)
-
- day_1 = results[0] # 2021-05-01
- self.assertEqual(day_1["reached_from_step_count"], 1)
- self.assertEqual(day_1["reached_to_step_count"], 1)
- self.assertEqual(day_1["conversion_rate"], 100)
-
- day_2 = results[1] # 2021-05-02
- self.assertEqual(day_2["reached_from_step_count"], 0)
- self.assertEqual(day_2["reached_to_step_count"], 0)
- self.assertEqual(day_2["conversion_rate"], 0)
-
- day_3 = results[2] # 2021-05-03
- self.assertEqual(day_3["reached_from_step_count"], 1)
- self.assertEqual(day_3["reached_to_step_count"], 0)
- self.assertEqual(day_3["conversion_rate"], 0)
-
- day_4 = results[3] # 2021-05-04
- self.assertEqual(day_4["reached_from_step_count"], 2)
- self.assertEqual(day_4["reached_to_step_count"], 1)
- self.assertEqual(day_4["conversion_rate"], 50)
-
- def test_funnel_step_breakdown_event(self):
- journeys_for(
- {
- "user_one": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 1),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "step two",
- "timestamp": datetime(2021, 5, 3),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "step three",
- "timestamp": datetime(2021, 5, 5),
- "properties": {"$browser": "Chrome"},
- },
- ],
- "user_two": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 2),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "step two",
- "timestamp": datetime(2021, 5, 3),
- "properties": {"$browser": "Chrome"},
- },
- {
- "event": "step three",
- "timestamp": datetime(2021, 5, 5),
- "properties": {"$browser": "Chrome"},
- },
- ],
- "user_three": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 3),
- "properties": {"$browser": "Safari"},
- },
- {
- "event": "step two",
- "timestamp": datetime(2021, 5, 4),
- "properties": {"$browser": "Safari"},
- },
- {
- "event": "step three",
- "timestamp": datetime(2021, 5, 5),
- "properties": {"$browser": "Safari"},
- },
- ],
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-13 23:59:59",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "breakdown_type": "event",
- "breakdown": "$browser",
- }
- )
- funnel_trends = ClickhouseFunnelTrends(filter, self.team)
- result = funnel_trends.run()
-
- self.assertEqual(len(result), 2)
-
- for res in result:
- if res["breakdown_value"] == ["Chrome"]:
- self.assertEqual(
- res["data"],
- [
- 100.0,
- 100.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- ],
- )
- elif res["breakdown_value"] == ["Safari"]:
- self.assertEqual(
- res["data"],
- [0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- )
- else:
- self.fail(msg="Invalid breakdown value")
-
- def test_funnel_step_breakdown_person(self):
- _create_person(distinct_ids=["user_one"], team=self.team, properties={"$browser": "Chrome"})
- _create_person(distinct_ids=["user_two"], team=self.team, properties={"$browser": "Chrome"})
- _create_person(
- distinct_ids=["user_three"],
- team=self.team,
- properties={"$browser": "Safari"},
- )
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_two": [
- {"event": "step one", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_three": [
- {"event": "step one", "timestamp": datetime(2021, 5, 3)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-13 23:59:59",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "breakdown_type": "person",
- "breakdown": "$browser",
- }
- )
- funnel_trends = ClickhouseFunnelTrends(filter, self.team)
- result = funnel_trends.run()
-
- self.assertEqual(len(result), 2)
-
- for res in result:
- if res["breakdown_value"] == ["Chrome"]:
- self.assertEqual(
- res["data"],
- [
- 100.0,
- 100.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- ],
- )
- elif res["breakdown_value"] == ["Safari"]:
- self.assertEqual(
- res["data"],
- [0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- )
- else:
- self.fail(msg="Invalid breakdown value")
-
- def test_funnel_trend_cohort_breakdown(self):
- _create_person(distinct_ids=["user_one"], team=self.team, properties={"key": "value"})
- _create_person(distinct_ids=["user_two"], team=self.team, properties={"key": "value"})
- _create_person(
- distinct_ids=["user_three"],
- team=self.team,
- properties={"$browser": "Safari"},
- )
-
- journeys_for(
- {
- "user_one": [
- {"event": "step one", "timestamp": datetime(2021, 5, 1)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_two": [
- {"event": "step one", "timestamp": datetime(2021, 5, 2)},
- {"event": "step two", "timestamp": datetime(2021, 5, 3)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- "user_three": [
- {"event": "step one", "timestamp": datetime(2021, 5, 3)},
- {"event": "step two", "timestamp": datetime(2021, 5, 4)},
- {"event": "step three", "timestamp": datetime(2021, 5, 5)},
- ],
- },
- self.team,
- )
-
- cohort = Cohort.objects.create(
- team=self.team,
- name="test_cohort",
- groups=[{"properties": [{"key": "key", "value": "value", "type": "person"}]}],
- )
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-13 23:59:59",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "breakdown_type": "cohort",
- "breakdown": [cohort.pk],
- }
- )
- funnel_trends = ClickhouseFunnelTrends(filter, self.team)
-
- result = funnel_trends.run()
- self.assertEqual(len(result), 1)
- self.assertEqual(
- result[0]["data"],
- [100.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- )
-
- @snapshot_clickhouse_queries
- def test_timezones_trends(self):
- journeys_for(
- {
- "user_one": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 1, 10),
- }, # 04-30 in pacific
- {
- "event": "step two",
- "timestamp": datetime(2021, 5, 1, 11),
- }, # today in pacific
- {
- "event": "step three",
- "timestamp": datetime(2021, 5, 1, 12),
- }, # today in pacific
- ],
- "user_two": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 1, 1),
- }, # 04-30 in pacific
- {
- "event": "step two",
- "timestamp": datetime(2021, 5, 1, 2),
- }, # 04-30 in pacific
- {
- "event": "step three",
- "timestamp": datetime(2021, 5, 1, 3),
- }, # 04-30 in pacific
- ],
- "user_three": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 1, 1),
- }, # 04-30 in pacific
- {
- "event": "step two",
- "timestamp": datetime(2021, 5, 1, 10),
- }, # today in pacific
- {
- "event": "step three",
- "timestamp": datetime(2021, 5, 1, 11),
- }, # today in pacific
- ],
- "user_eight": [],
- },
- self.team,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "interval": "day",
- "date_from": "2021-04-30 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- self.team.timezone = "US/Pacific"
- self.team.save()
-
- results_pacific = ClickhouseFunnelTrends(filter, self.team)._exec_query()
-
- saturday = results[1] # 5/1
- self.assertEqual(3, saturday["reached_to_step_count"])
- self.assertEqual(3, saturday["reached_from_step_count"])
- self.assertEqual(100.0, saturday["conversion_rate"])
-
- friday_pacific = results_pacific[0]
- self.assertEqual(2, friday_pacific["reached_to_step_count"])
- self.assertEqual(2, friday_pacific["reached_from_step_count"])
- self.assertEqual(100.0, friday_pacific["conversion_rate"])
- saturday_pacific = results_pacific[1]
- self.assertEqual(1, saturday_pacific["reached_to_step_count"])
- self.assertEqual(1, saturday_pacific["reached_from_step_count"])
-
- def test_trend_for_hour_based_conversion_window(self):
- journeys_for(
- {
- "user_one": [
- # Converts in 2 hours
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 10)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 11)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 12)},
- ],
- "user_two": [
- # Converts in 4 hours (not fast enough)
- {"event": "step one", "timestamp": datetime(2021, 5, 1, 10)},
- {"event": "step two", "timestamp": datetime(2021, 5, 1, 11)},
- {"event": "step three", "timestamp": datetime(2021, 5, 1, 14)},
- ],
- },
- self.team,
- )
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "display": TRENDS_LINEAR,
- "funnel_window_interval": 3,
- "funnel_window_interval_unit": "hour",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- )
- with freeze_time("2021-05-06T23:40:59Z"):
- results = ClickhouseFunnelTrends(filter, self.team)._exec_query()
- conversion_rates = [row["conversion_rate"] for row in results]
- self.assertEqual(conversion_rates, [50.0, 0.0, 0.0, 0.0, 0.0, 0.0])
diff --git a/posthog/queries/funnels/test/test_funnel_trends_persons.py b/posthog/queries/funnels/test/test_funnel_trends_persons.py
deleted file mode 100644
index fa754438cbd8..000000000000
--- a/posthog/queries/funnels/test/test_funnel_trends_persons.py
+++ /dev/null
@@ -1,143 +0,0 @@
-from datetime import datetime, timedelta
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
-
-from posthog.constants import INSIGHT_FUNNELS, FunnelVizType
-from posthog.models.filters import Filter
-from posthog.queries.funnels.funnel_trends_persons import ClickhouseFunnelTrendsActors
-from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
-from posthog.test.test_journeys import journeys_for
-
-filter_data = {
- "insight": INSIGHT_FUNNELS,
- "funnel_viz_type": FunnelVizType.TRENDS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 23:59:59",
- "funnel_window_days": 14,
- "funnel_from_step": 0,
- "entrance_period_start": "2021-05-01 00:00:00",
- "drop_off": False,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "include_recordings": "true",
-}
-
-
-class TestFunnelTrendsPersons(ClickhouseTestMixin, APIBaseTest):
- @snapshot_clickhouse_queries
- def test_funnel_trend_persons_returns_recordings(self):
- persons = journeys_for(
- {
- "user_one": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 1),
- "properties": {"$session_id": "s1a"},
- },
- {
- "event": "step two",
- "timestamp": datetime(2021, 5, 2),
- "properties": {"$session_id": "s1b"},
- },
- {
- "event": "step three",
- "timestamp": datetime(2021, 5, 3),
- "properties": {"$session_id": "s1c"},
- },
- ]
- },
- self.team,
- )
- timestamp = datetime(2021, 5, 1)
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s1b",
- distinct_id="user_one",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- )
-
- filter = Filter(data={"funnel_to_step": 1, **filter_data})
- _, results, _ = ClickhouseFunnelTrendsActors(filter, self.team).get_actors()
- self.assertEqual([person["id"] for person in results], [persons["user_one"].uuid])
- self.assertEqual(
- [person["matched_recordings"][0]["session_id"] for person in results],
- ["s1b"],
- )
-
- @snapshot_clickhouse_queries
- def test_funnel_trend_persons_with_no_to_step(self):
- persons = journeys_for(
- {
- "user_one": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 1),
- "properties": {"$session_id": "s1a"},
- },
- {
- "event": "step two",
- "timestamp": datetime(2021, 5, 2),
- "properties": {"$session_id": "s1b"},
- },
- {
- "event": "step three",
- "timestamp": datetime(2021, 5, 3),
- "properties": {"$session_id": "s1c"},
- },
- ]
- },
- self.team,
- )
- # the session recording can start a little before the events in the funnel
- timestamp = datetime(2021, 5, 1) - timedelta(hours=12)
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s1c",
- distinct_id="user_one",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- )
-
- filter = Filter(data=filter_data)
- _, results, _ = ClickhouseFunnelTrendsActors(filter, self.team).get_actors()
- self.assertEqual([person["id"] for person in results], [persons["user_one"].uuid])
- self.assertEqual(
- [person["matched_recordings"][0]["session_id"] for person in results],
- ["s1c"],
- )
-
- @snapshot_clickhouse_queries
- def test_funnel_trend_persons_with_drop_off(self):
- persons = journeys_for(
- {
- "user_one": [
- {
- "event": "step one",
- "timestamp": datetime(2021, 5, 1),
- "properties": {"$session_id": "s1a"},
- }
- ]
- },
- self.team,
- )
- timestamp = datetime(2021, 5, 1)
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s1a",
- distinct_id="user_one",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- )
-
- filter = Filter(data={**filter_data, "drop_off": True})
- _, results, _ = ClickhouseFunnelTrendsActors(filter, self.team).get_actors()
- self.assertEqual([person["id"] for person in results], [persons["user_one"].uuid])
- self.assertEqual(
- [person["matched_recordings"][0].get("session_id") for person in results],
- ["s1a"],
- )
diff --git a/posthog/queries/funnels/test/test_funnel_unordered.py b/posthog/queries/funnels/test/test_funnel_unordered.py
deleted file mode 100644
index c5c73dd8614b..000000000000
--- a/posthog/queries/funnels/test/test_funnel_unordered.py
+++ /dev/null
@@ -1,1602 +0,0 @@
-from datetime import datetime
-
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_action,
- _create_event,
- _create_person,
- snapshot_clickhouse_queries,
-)
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.filters import Filter
-from posthog.queries.funnels.funnel_unordered import ClickhouseFunnelUnordered
-from posthog.queries.funnels.funnel_unordered_persons import ClickhouseFunnelUnorderedActors
-from posthog.queries.funnels.test.breakdown_cases import (
- FunnelStepResult,
- assert_funnel_results_equal,
- funnel_breakdown_test_factory,
-)
-from posthog.queries.funnels.test.conversion_time_cases import funnel_conversion_time_test_factory
-from posthog.test.test_journeys import journeys_for
-
-FORMAT_TIME = "%Y-%m-%d 00:00:00"
-
-
-class TestFunnelUnorderedStepsBreakdown(
- ClickhouseTestMixin,
- funnel_breakdown_test_factory( # type: ignore
- ClickhouseFunnelUnordered,
- ClickhouseFunnelUnorderedActors,
- _create_event,
- _create_action,
- _create_person,
- ),
-):
- maxDiff = None
-
- def test_funnel_step_breakdown_event_single_person_events_with_multiple_properties(self):
- # overriden from factory
-
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "play movie", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": "$browser",
- "breakdown_attribution_type": "all_events",
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- # event
- person1 = _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person1",
- properties={"key": "val", "$browser": "Chrome"},
- timestamp="2020-01-01T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="person1",
- properties={"key": "val", "$browser": "Safari"},
- timestamp="2020-01-02T13:00:00Z",
- )
- _create_event(
- team=self.team,
- event="play movie",
- distinct_id="person1",
- properties={"key": "val", "$browser": "Safari"},
- timestamp="2020-01-02T14:00:00Z",
- )
-
- result = funnel.run()
-
- assert_funnel_results_equal(
- result[0],
- [
- {
- "action_id": None,
- "name": "Completed 1 step",
- "custom_name": None,
- "order": 0,
- "people": [],
- "count": 1,
- "type": "events",
- "average_conversion_time": None,
- "median_conversion_time": None,
- "breakdown": ["Safari"],
- "breakdown_value": ["Safari"],
- },
- {
- "action_id": None,
- "name": "Completed 2 steps",
- "custom_name": None,
- "order": 1,
- "people": [],
- "count": 1,
- "type": "events",
- "average_conversion_time": 3600,
- "median_conversion_time": 3600,
- "breakdown": ["Safari"],
- "breakdown_value": ["Safari"],
- },
- ],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ["Safari"]), [person1.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, ["Safari"]), [person1.uuid])
-
- assert_funnel_results_equal(
- result[1],
- [
- {
- "action_id": None,
- "name": "Completed 1 step",
- "custom_name": None,
- "order": 0,
- "people": [],
- "count": 1,
- "type": "events",
- "average_conversion_time": None,
- "median_conversion_time": None,
- "breakdown": ["Chrome"],
- "breakdown_value": ["Chrome"],
- },
- {
- "action_id": None,
- "name": "Completed 2 steps",
- "custom_name": None,
- "order": 1,
- "people": [],
- "count": 0,
- "type": "events",
- "average_conversion_time": None,
- "median_conversion_time": None,
- "breakdown": ["Chrome"],
- "breakdown_value": ["Chrome"],
- },
- ],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ["Chrome"]), [person1.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2, ["Chrome"]), [])
-
- def test_funnel_step_breakdown_with_step_attribution(self):
- # overridden from factory, since with no order, step one is step zero, and vice versa
-
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "0",
- "funnel_order_type": "unordered",
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)},
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # step attribution means alakazam is valid when step = 1
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 6)
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Mac"), [people["person3"].uuid])
-
- def test_funnel_step_breakdown_with_step_one_attribution(self):
- # overridden from factory, since with no order, step one is step zero, and vice versa
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "1",
- "funnel_order_type": "unordered",
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)},
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # step attribution means alakazam is valid when step = 1
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 6)
- # unordered, so everything is step one too.
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=[""], count=3),
- FunnelStepResult(
- name="Completed 2 steps",
- breakdown=[""],
- count=2,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1, ""),
- [people["person1"].uuid, people["person2"].uuid, people["person3"].uuid],
- )
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2, ""),
- [people["person1"].uuid, people["person3"].uuid],
- )
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=["0"], count=1),
- FunnelStepResult(name="Completed 2 steps", breakdown=["0"], count=0),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "0"), [people["person4"].uuid])
-
- def test_funnel_step_breakdown_with_step_one_attribution_incomplete_funnel(self):
- # overridden from factory, since with no order, step one is step zero, and vice versa
-
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": ["$browser"],
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "1",
- "funnel_order_type": "unordered",
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 13), "properties": {"$browser": "Safari"}}
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)}
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # step attribution means alakazam is valid when step = 1
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- # Breakdown by step_1 means funnel items that never reach step_1 are NULLed out
- self.assertEqual(len(result), 4)
- # Chrome and Mac and Safari goes away
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=[""], count=1),
- FunnelStepResult(
- name="Completed 2 steps",
- breakdown=[""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ""), [people["person1"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=["0"], count=1),
- FunnelStepResult(name="Completed 2 steps", breakdown=["0"], count=0),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "0"), [people["person4"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=["Chrome"], count=1),
- FunnelStepResult(name="Completed 2 steps", breakdown=["Chrome"], count=0),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Chrome"), [people["person1"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[3],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=["alakazam"], count=1),
- FunnelStepResult(
- name="Completed 2 steps",
- breakdown=["alakazam"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "alakazam"), [people["person4"].uuid])
-
- def test_funnel_step_non_array_breakdown_with_step_one_attribution_incomplete_funnel(self):
- # overridden from factory, since with no order, step one is step zero, and vice versa
-
- filters = {
- "events": [{"id": "sign up", "order": 0}, {"id": "buy", "order": 1}],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": "$browser",
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "1",
- "funnel_order_type": "unordered",
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome"},
- },
- {"event": "buy", "timestamp": datetime(2020, 1, 1, 13)},
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 13), "properties": {"$browser": "Safari"}}
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- # {"event": "buy", "timestamp": datetime(2020, 1, 2, 15)}
- ],
- "person4": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$browser": 0},
- },
- # step attribution means alakazam is valid when step = 1
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 16),
- "properties": {"$browser": "alakazam"},
- },
- ],
- }
- people = journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- # Breakdown by step_1 means funnel items that never reach step_1 are NULLed out
- self.assertEqual(len(result), 4)
- # Chrome and Mac and Safari goes away
-
- self._assert_funnel_breakdown_result_is_correct(
- result[0],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=[""], count=1),
- FunnelStepResult(
- name="Completed 2 steps",
- breakdown=[""],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, ""), [people["person1"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[1],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=["0"], count=1),
- FunnelStepResult(name="Completed 2 steps", breakdown=["0"], count=0),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "0"), [people["person4"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[2],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=["Chrome"], count=1),
- FunnelStepResult(name="Completed 2 steps", breakdown=["Chrome"], count=0),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "Chrome"), [people["person1"].uuid])
-
- self._assert_funnel_breakdown_result_is_correct(
- result[3],
- [
- FunnelStepResult(name="Completed 1 step", breakdown=["alakazam"], count=1),
- FunnelStepResult(
- name="Completed 2 steps",
- breakdown=["alakazam"],
- count=1,
- average_conversion_time=3600,
- median_conversion_time=3600,
- ),
- ],
- )
-
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 1, "alakazam"), [people["person4"].uuid])
-
- @snapshot_clickhouse_queries
- def test_funnel_breakdown_correct_breakdown_props_are_chosen_for_step(self):
- # No person querying here, so snapshots are more legible
- # overridden from factory, since we need to add `funnel_order_type`
-
- filters = {
- "events": [
- {"id": "sign up", "order": 0},
- {
- "id": "buy",
- "properties": [{"type": "event", "key": "$version", "value": "xyz"}],
- "order": 1,
- },
- ],
- "insight": INSIGHT_FUNNELS,
- "date_from": "2020-01-01",
- "date_to": "2020-01-08",
- "funnel_window_days": 7,
- "breakdown_type": "event",
- "breakdown": "$browser",
- "breakdown_attribution_type": "step",
- "breakdown_attribution_value": "1",
- "funnel_order_type": "unordered",
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- # event
- events_by_person = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"$browser": "Chrome", "$version": "xyz"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 1, 13),
- "properties": {"$browser": "Chrome"},
- },
- # discarded because doesn't meet criteria
- ],
- "person2": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 1, 13)},
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$browser": "Safari", "$version": "xyz"},
- },
- ],
- "person3": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 14),
- "properties": {"$browser": "Mac"},
- },
- {
- "event": "buy",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$version": "xyz", "$browser": "Mac"},
- },
- ],
- # no properties dude, doesn't make it to step 1, and since breakdown on step 1, is discarded completely
- "person5": [
- {"event": "sign up", "timestamp": datetime(2020, 1, 2, 15)},
- {"event": "buy", "timestamp": datetime(2020, 1, 2, 16)},
- ],
- }
- journeys_for(events_by_person, self.team)
-
- result = funnel.run()
- result = sorted(result, key=lambda res: res[0]["breakdown"])
-
- self.assertEqual(len(result), 3)
-
- self.assertCountEqual([res[0]["breakdown"] for res in result], [[""], ["Mac"], ["Safari"]])
-
-
-class TestFunnelUnorderedStepsConversionTime(
- ClickhouseTestMixin,
- funnel_conversion_time_test_factory( # type: ignore
- ClickhouseFunnelUnordered,
- ClickhouseFunnelUnorderedActors,
- _create_event,
- _create_person,
- ),
-):
- maxDiff = None
- pass
-
-
-class TestFunnelUnorderedSteps(ClickhouseTestMixin, APIBaseTest):
- def _get_actor_ids_at_step(self, filter, funnel_step, breakdown_value=None):
- person_filter = filter.shallow_clone({"funnel_step": funnel_step, "funnel_step_breakdown": breakdown_value})
- _, serialized_result, _ = ClickhouseFunnelUnorderedActors(person_filter, self.team).get_actors()
-
- return [val["id"] for val in serialized_result]
-
- def test_basic_unordered_funnel(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "events": [
- {"id": "user signed up", "order": 0},
- {"id": "$pageview", "order": 1},
- {"id": "insight viewed", "order": 2},
- ],
- }
- )
-
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- person1_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup1"], team_id=self.team.pk)
- _create_event(team=self.team, event="user signed up", distinct_id="stopped_after_signup1")
-
- person2_stopped_after_one_pageview = _create_person(
- distinct_ids=["stopped_after_pageview1"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview1")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview1",
- )
-
- person3_stopped_after_insight_view = _create_person(
- distinct_ids=["stopped_after_insightview"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview")
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview",
- )
-
- person4_stopped_after_insight_view_reverse_order = _create_person(
- distinct_ids=["stopped_after_insightview2"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview2",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview2")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview2",
- )
-
- person5_stopped_after_insight_view_random = _create_person(
- distinct_ids=["stopped_after_insightview3"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview3")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview3",
- )
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview3")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview3",
- )
-
- person6_did_only_insight_view = _create_person(
- distinct_ids=["stopped_after_insightview4"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview4")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview4",
- )
-
- person7_did_only_pageview = _create_person(distinct_ids=["stopped_after_insightview5"], team_id=self.team.pk)
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview5")
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview5")
-
- person8_didnot_signup = _create_person(distinct_ids=["stopped_after_insightview6"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview6",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview6")
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "Completed 1 step")
- self.assertEqual(result[0]["count"], 8)
- self.assertEqual(result[1]["name"], "Completed 2 steps")
- self.assertEqual(result[1]["count"], 5)
- self.assertEqual(result[2]["name"], "Completed 3 steps")
- self.assertEqual(result[2]["count"], 3)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_signup.uuid,
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- person4_stopped_after_insight_view_reverse_order.uuid,
- person5_stopped_after_insight_view_random.uuid,
- person6_did_only_insight_view.uuid,
- person7_did_only_pageview.uuid,
- person8_didnot_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- person4_stopped_after_insight_view_reverse_order.uuid,
- person5_stopped_after_insight_view_random.uuid,
- person8_didnot_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, -2),
- [
- person1_stopped_after_signup.uuid,
- person6_did_only_insight_view.uuid,
- person7_did_only_pageview.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [
- person3_stopped_after_insight_view.uuid,
- person4_stopped_after_insight_view_reverse_order.uuid,
- person5_stopped_after_insight_view_random.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, -3),
- [person2_stopped_after_one_pageview.uuid, person8_didnot_signup.uuid],
- )
-
- def test_big_multi_step_unordered_funnel(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "events": [
- {"id": "user signed up", "order": 0},
- {"id": "$pageview", "order": 1},
- {"id": "insight viewed", "order": 2},
- {"id": "crying", "order": 3},
- ],
- }
- )
-
- person1_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup1"], team_id=self.team.pk)
- _create_event(team=self.team, event="user signed up", distinct_id="stopped_after_signup1")
-
- person2_stopped_after_one_pageview = _create_person(
- distinct_ids=["stopped_after_pageview1"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_pageview1")
- _create_event(team=self.team, event="crying", distinct_id="stopped_after_pageview1")
-
- person3_stopped_after_insight_view = _create_person(
- distinct_ids=["stopped_after_insightview"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview")
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview",
- )
-
- person4_stopped_after_insight_view_reverse_order = _create_person(
- distinct_ids=["stopped_after_insightview2"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview2",
- )
- _create_event(team=self.team, event="crying", distinct_id="stopped_after_insightview2")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview2",
- )
-
- person5_stopped_after_insight_view_random = _create_person(
- distinct_ids=["stopped_after_insightview3"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview3")
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview3",
- )
- _create_event(team=self.team, event="crying", distinct_id="stopped_after_insightview3")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview3",
- )
-
- person6_did_only_insight_view = _create_person(
- distinct_ids=["stopped_after_insightview4"], team_id=self.team.pk
- )
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview4")
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview4",
- )
-
- person7_did_only_pageview = _create_person(distinct_ids=["stopped_after_insightview5"], team_id=self.team.pk)
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview5")
- _create_event(team=self.team, event="blaah blaa", distinct_id="stopped_after_insightview5")
-
- person8_didnot_signup = _create_person(distinct_ids=["stopped_after_insightview6"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview6",
- )
- _create_event(team=self.team, event="$pageview", distinct_id="stopped_after_insightview6")
-
- funnel = ClickhouseFunnelUnordered(filter, self.team)
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "Completed 1 step")
- self.assertEqual(result[0]["count"], 8)
- self.assertEqual(result[1]["name"], "Completed 2 steps")
- self.assertEqual(result[1]["count"], 5)
- self.assertEqual(result[2]["name"], "Completed 3 steps")
- self.assertEqual(result[2]["count"], 3)
- self.assertEqual(result[3]["name"], "Completed 4 steps")
- self.assertEqual(result[3]["count"], 1)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_signup.uuid,
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- person4_stopped_after_insight_view_reverse_order.uuid,
- person5_stopped_after_insight_view_random.uuid,
- person6_did_only_insight_view.uuid,
- person7_did_only_pageview.uuid,
- person8_didnot_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- person4_stopped_after_insight_view_reverse_order.uuid,
- person5_stopped_after_insight_view_random.uuid,
- person8_didnot_signup.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [
- person3_stopped_after_insight_view.uuid,
- person4_stopped_after_insight_view_reverse_order.uuid,
- person5_stopped_after_insight_view_random.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 4),
- [person5_stopped_after_insight_view_random.uuid],
- )
-
- def test_basic_unordered_funnel_conversion_times(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "events": [
- {"id": "user signed up", "order": 0},
- {"id": "$pageview", "order": 1},
- {"id": "insight viewed", "order": 2},
- ],
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 23:59:59",
- "funnel_window_days": "1",
- }
- )
-
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- person1_stopped_after_signup = _create_person(distinct_ids=["stopped_after_signup1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- timestamp="2021-05-02 00:00:00",
- )
-
- person2_stopped_after_one_pageview = _create_person(
- distinct_ids=["stopped_after_pageview1"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="stopped_after_pageview1",
- timestamp="2021-05-02 00:00:00",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview1",
- timestamp="2021-05-02 01:00:00",
- )
-
- person3_stopped_after_insight_view = _create_person(
- distinct_ids=["stopped_after_insightview"], team_id=self.team.pk
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-02 00:00:00",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-02 02:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-02 04:00:00",
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-03 00:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-03 03:00:00",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_insightview",
- timestamp="2021-05-03 06:00:00",
- )
- # Person 3 completes the funnel 2 times:
- # First time: 2 hours + 2 hours = total 4 hours.
- # Second time: 3 hours + 3 hours = total 6 hours.
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "Completed 1 step")
- self.assertEqual(result[1]["name"], "Completed 2 steps")
- self.assertEqual(result[2]["name"], "Completed 3 steps")
- self.assertEqual(result[0]["count"], 3)
-
- self.assertEqual(result[1]["average_conversion_time"], 6300)
- # 1 hour for Person 2, (2+3)/2 hours for Person 3, total = 3.5 hours, average = 3.5/2 = 1.75 hours
-
- self.assertEqual(result[2]["average_conversion_time"], 9000)
- # (2+3)/2 hours for Person 3 = 2.5 hours
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [
- person1_stopped_after_signup.uuid,
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 2),
- [
- person2_stopped_after_one_pageview.uuid,
- person3_stopped_after_insight_view.uuid,
- ],
- )
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 3),
- [person3_stopped_after_insight_view.uuid],
- )
-
- def test_single_event_unordered_funnel(self):
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "events": [{"id": "user signed up", "order": 0}],
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 23:59:59",
- }
- )
-
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- _create_person(distinct_ids=["stopped_after_signup1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_signup1",
- timestamp="2021-05-02 00:00:00",
- )
-
- _create_person(distinct_ids=["stopped_after_pageview1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="stopped_after_pageview1",
- timestamp="2021-05-02 00:00:00",
- )
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="stopped_after_pageview1",
- timestamp="2021-05-02 01:00:00",
- )
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "Completed 1 step")
- self.assertEqual(result[0]["count"], 2)
-
- def test_funnel_exclusions_invalid_params(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "paid", "type": "events", "order": 1},
- {"id": "blah", "type": "events", "order": 2},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 1,
- "funnel_to_step": 1,
- }
- ],
- }
- filter = Filter(data=filters)
- self.assertRaises(ValidationError, lambda: ClickhouseFunnelUnordered(filter, self.team).run())
-
- # partial windows not allowed for unordered
- filter = filter.shallow_clone(
- {
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- }
- ]
- }
- )
- self.assertRaises(ValidationError, lambda: ClickhouseFunnelUnordered(filter, self.team).run())
-
- def test_funnel_exclusions_full_window(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "paid", "type": "events", "order": 1},
- ],
- "insight": INSIGHT_FUNNELS,
- "funnel_window_days": 14,
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 1,
- }
- ],
- }
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- # event 1
- person1 = _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person1",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person1",
- timestamp="2021-05-01 02:00:00",
- )
-
- # event 2
- person2 = _create_person(distinct_ids=["person2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person2",
- timestamp="2021-05-01 03:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person2",
- timestamp="2021-05-01 03:30:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person2",
- timestamp="2021-05-01 04:00:00",
- )
-
- # event 3
- person3 = _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="paid",
- distinct_id="person3",
- timestamp="2021-05-01 06:00:00",
- )
-
- result = funnel.run()
-
- self.assertEqual(len(result), 2)
- self.assertEqual(result[0]["name"], "Completed 1 step")
- self.assertEqual(result[0]["count"], 3)
- self.assertEqual(result[1]["name"], "Completed 2 steps")
- self.assertEqual(result[1]["count"], 2)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [person1.uuid, person2.uuid, person3.uuid],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2), [person1.uuid, person3.uuid])
-
- def test_advanced_funnel_multiple_exclusions_between_steps(self):
- filters = {
- "events": [
- {"id": "user signed up", "type": "events", "order": 0},
- {"id": "$pageview", "type": "events", "order": 1},
- {"id": "insight viewed", "type": "events", "order": 2},
- {"id": "invite teammate", "type": "events", "order": 3},
- {"id": "pageview2", "type": "events", "order": 4},
- ],
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-14 00:00:00",
- "insight": INSIGHT_FUNNELS,
- "exclusions": [
- {
- "id": "x",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 4,
- },
- {
- "id": "y",
- "type": "events",
- "funnel_from_step": 0,
- "funnel_to_step": 4,
- },
- ],
- }
-
- person1 = _create_person(distinct_ids=["person1"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person1",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person1",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person1",
- timestamp="2021-05-01 03:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person1",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="y",
- distinct_id="person1",
- timestamp="2021-05-01 04:30:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person1",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person1",
- timestamp="2021-05-01 06:00:00",
- )
-
- person2 = _create_person(distinct_ids=["person2"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person2",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="y",
- distinct_id="person2",
- timestamp="2021-05-01 01:30:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person2",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person2",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="y",
- distinct_id="person2",
- timestamp="2021-05-01 04:30:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person2",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person2",
- timestamp="2021-05-01 05:30:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person2",
- timestamp="2021-05-01 06:00:00",
- )
-
- person3 = _create_person(distinct_ids=["person3"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person3",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person3",
- timestamp="2021-05-01 01:30:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person3",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person3",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person3",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person3",
- timestamp="2021-05-01 05:30:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person3",
- timestamp="2021-05-01 06:00:00",
- )
-
- person4 = _create_person(distinct_ids=["person4"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person4",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person4",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person4",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person4",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person4",
- timestamp="2021-05-01 06:00:00",
- )
-
- person5 = _create_person(distinct_ids=["person5"], team_id=self.team.pk)
- _create_event(
- team=self.team,
- event="user signed up",
- distinct_id="person5",
- timestamp="2021-05-01 01:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person5",
- timestamp="2021-05-01 01:30:00",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="person5",
- timestamp="2021-05-01 02:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person5",
- timestamp="2021-05-01 02:30:00",
- )
- _create_event(
- team=self.team,
- event="insight viewed",
- distinct_id="person5",
- timestamp="2021-05-01 04:00:00",
- )
- _create_event(
- team=self.team,
- event="y",
- distinct_id="person5",
- timestamp="2021-05-01 04:30:00",
- )
- _create_event(
- team=self.team,
- event="invite teammate",
- distinct_id="person5",
- timestamp="2021-05-01 05:00:00",
- )
- _create_event(
- team=self.team,
- event="x",
- distinct_id="person5",
- timestamp="2021-05-01 05:30:00",
- )
- _create_event(
- team=self.team,
- event="pageview2",
- distinct_id="person5",
- timestamp="2021-05-01 06:00:00",
- )
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
-
- result = funnel.run()
-
- self.assertEqual(result[0]["name"], "Completed 1 step")
- self.assertEqual(result[0]["count"], 5)
- self.assertEqual(result[1]["count"], 2)
- self.assertEqual(result[2]["count"], 1)
- self.assertEqual(result[3]["count"], 1)
- self.assertEqual(result[4]["count"], 1)
-
- self.assertCountEqual(
- self._get_actor_ids_at_step(filter, 1),
- [person1.uuid, person2.uuid, person3.uuid, person4.uuid, person5.uuid],
- )
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 2), [person1.uuid, person4.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 3), [person4.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 4), [person4.uuid])
- self.assertCountEqual(self._get_actor_ids_at_step(filter, 5), [person4.uuid])
-
- def test_funnel_unordered_all_events_with_properties(self):
- _create_person(distinct_ids=["user"], team=self.team)
- _create_event(event="user signed up", distinct_id="user", team=self.team)
- _create_event(
- event="added to card",
- distinct_id="user",
- properties={"is_saved": True},
- team=self.team,
- )
-
- filters = {
- "events": [
- {
- "type": "events",
- "id": "user signed up",
- "order": 0,
- "name": "user signed up",
- "math": "total",
- },
- {
- "type": "events",
- "id": None,
- "order": 1,
- "name": "All events",
- "math": "total",
- "properties": [
- {
- "key": "is_saved",
- "value": ["true"],
- "operator": "exact",
- "type": "event",
- }
- ],
- },
- ],
- "funnel_window_days": 14,
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
- result = funnel.run()
-
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(result[1]["count"], 1)
-
- def test_funnel_unordered_entity_filters(self):
- _create_person(distinct_ids=["user"], team=self.team)
- _create_event(
- event="user signed up",
- distinct_id="user",
- properties={"prop_a": "some value"},
- team=self.team,
- )
- _create_event(
- event="user signed up",
- distinct_id="user",
- properties={"prop_b": "another value"},
- team=self.team,
- )
-
- filters = {
- "events": [
- {
- "type": "events",
- "id": "user signed up",
- "order": 0,
- "name": "user signed up",
- "math": "total",
- "properties": [
- {
- "key": "prop_a",
- "value": ["some value"],
- "operator": "exact",
- "type": "event",
- }
- ],
- },
- {
- "type": "events",
- "id": "user signed up",
- "order": 1,
- "name": "user signed up",
- "math": "total",
- "properties": [
- {
- "key": "prop_b",
- "value": "another",
- "operator": "icontains",
- "type": "event",
- }
- ],
- },
- ],
- }
-
- filter = Filter(data=filters)
- funnel = ClickhouseFunnelUnordered(filter, self.team)
- result = funnel.run()
-
- self.assertEqual(result[0]["count"], 1)
- self.assertEqual(result[1]["count"], 1)
diff --git a/posthog/queries/funnels/test/test_funnel_unordered_persons.py b/posthog/queries/funnels/test/test_funnel_unordered_persons.py
deleted file mode 100644
index fb406eb4077c..000000000000
--- a/posthog/queries/funnels/test/test_funnel_unordered_persons.py
+++ /dev/null
@@ -1,191 +0,0 @@
-from datetime import datetime, timedelta
-
-import pytest
-from freezegun import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_event,
- _create_person,
- snapshot_clickhouse_queries,
-)
-
-from django.utils import timezone
-
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.models.filters import Filter
-from posthog.queries.funnels.funnel_unordered_persons import ClickhouseFunnelUnorderedActors
-from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
-from posthog.test.test_journeys import journeys_for
-
-FORMAT_TIME = "%Y-%m-%d 00:00:00"
-
-
-class TestFunnelUnorderedStepsPersons(ClickhouseTestMixin, APIBaseTest):
- def _create_sample_data_multiple_dropoffs(self):
- events_by_person = {}
- for i in range(5):
- events_by_person[f"user_{i}"] = [
- {"event": "step one", "timestamp": datetime(2021, 5, 1)},
- {"event": "step three", "timestamp": datetime(2021, 5, 3)},
- {"event": "step two", "timestamp": datetime(2021, 5, 5)},
- ]
-
- for i in range(5, 15):
- events_by_person[f"user_{i}"] = [
- {"event": "step two", "timestamp": datetime(2021, 5, 1)},
- {"event": "step one", "timestamp": datetime(2021, 5, 3)},
- ]
-
- for i in range(15, 35):
- events_by_person[f"user_{i}"] = [{"event": "step one", "timestamp": datetime(2021, 5, 1)}]
-
- journeys_for(events_by_person, self.team)
-
- def test_invalid_steps(self):
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": "blah",
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- with self.assertRaises(ValueError):
- ClickhouseFunnelUnorderedActors(filter, self.team).run()
-
- filter = filter.shallow_clone({"funnel_step": -1})
- with pytest.raises(ValueError):
- _, _, _ = ClickhouseFunnelUnorderedActors(filter, self.team).run()
-
- def test_first_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, serialized_results, _ = ClickhouseFunnelUnorderedActors(filter, self.team).get_actors()
- self.assertEqual(35, len(serialized_results))
-
- def test_last_step(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 3,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, serialized_results, _ = ClickhouseFunnelUnorderedActors(filter, self.team).get_actors()
- self.assertEqual(5, len(serialized_results))
-
- def test_second_step_dropoff(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": -2,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, serialized_results, _ = ClickhouseFunnelUnorderedActors(filter, self.team).get_actors()
- self.assertEqual(20, len(serialized_results))
-
- def test_last_step_dropoff(self):
- self._create_sample_data_multiple_dropoffs()
- data = {
- "insight": INSIGHT_FUNNELS,
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": -3,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- filter = Filter(data=data)
- _, serialized_results, _ = ClickhouseFunnelUnorderedActors(filter, self.team).get_actors()
- self.assertEqual(10, len(serialized_results))
-
- @snapshot_clickhouse_queries
- @freeze_time("2021-01-02 00:00:00.000Z")
- def test_unordered_funnel_does_not_return_recordings(self):
- p1 = _create_person(distinct_ids=[f"user_1"], team=self.team)
- _create_event(
- event="step two",
- distinct_id="user_1",
- team=self.team,
- timestamp=timezone.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
- properties={"$session_id": "s1", "$window_id": "w1"},
- event_uuid="21111111-1111-1111-1111-111111111111",
- )
- _create_event(
- event="step one",
- distinct_id="user_1",
- team=self.team,
- timestamp=(timezone.now() + timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S.%f"),
- properties={"$session_id": "s1", "$window_id": "w1"},
- event_uuid="11111111-1111-1111-1111-111111111111",
- )
-
- timestamp = timezone.now() + timedelta(days=1)
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s1",
- distinct_id="user_1",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- )
-
- filter = Filter(
- data={
- "insight": INSIGHT_FUNNELS,
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "funnel_step": 1,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- "include_recordings": "true", # <- The important line
- }
- )
- _, results, _ = ClickhouseFunnelUnorderedActors(filter, self.team).get_actors()
- self.assertEqual(results[0]["id"], p1.uuid)
- self.assertEqual(results[0]["matched_recordings"], [])
diff --git a/posthog/queries/funnels/test/test_utils.py b/posthog/queries/funnels/test/test_utils.py
deleted file mode 100644
index ad3ebe433ccc..000000000000
--- a/posthog/queries/funnels/test/test_utils.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from posthog.test.base import BaseTest
-
-from posthog.constants import FunnelOrderType
-from posthog.models.filters import Filter
-from posthog.queries.funnels import ClickhouseFunnel, ClickhouseFunnelStrict, ClickhouseFunnelUnordered
-from posthog.queries.funnels.utils import get_funnel_order_class
-
-
-class TestGetFunnelOrderClass(BaseTest):
- def test_filter_missing_order(self):
- filter = Filter({"foo": "bar"})
- self.assertEqual(get_funnel_order_class(filter), ClickhouseFunnel)
-
- def test_unordered(self):
- filter = Filter({"funnel_order_type": FunnelOrderType.UNORDERED})
- self.assertEqual(get_funnel_order_class(filter), ClickhouseFunnelUnordered)
-
- def test_strict(self):
- filter = Filter({"funnel_order_type": FunnelOrderType.STRICT})
- self.assertEqual(get_funnel_order_class(filter), ClickhouseFunnelStrict)
-
- def test_ordered(self):
- filter = Filter({"funnel_order_type": FunnelOrderType.ORDERED})
- self.assertEqual(get_funnel_order_class(filter), ClickhouseFunnel)
diff --git a/posthog/queries/funnels/utils.py b/posthog/queries/funnels/utils.py
deleted file mode 100644
index 77ced8991304..000000000000
--- a/posthog/queries/funnels/utils.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from posthog.constants import FunnelOrderType
-from posthog.models.filters import Filter
-from posthog.queries.funnels import ClickhouseFunnelBase
-
-
-def get_funnel_order_class(filter: Filter) -> type[ClickhouseFunnelBase]:
- from posthog.queries.funnels import ClickhouseFunnel, ClickhouseFunnelStrict, ClickhouseFunnelUnordered
-
- if filter.funnel_order_type == FunnelOrderType.UNORDERED:
- return ClickhouseFunnelUnordered
- elif filter.funnel_order_type == FunnelOrderType.STRICT:
- return ClickhouseFunnelStrict
- return ClickhouseFunnel
-
-
-def get_funnel_order_actor_class(filter: Filter):
- from posthog.queries.funnels import (
- ClickhouseFunnelActors,
- ClickhouseFunnelStrictActors,
- ClickhouseFunnelUnorderedActors,
- )
-
- if filter.funnel_order_type == FunnelOrderType.UNORDERED:
- return ClickhouseFunnelUnorderedActors
- elif filter.funnel_order_type == FunnelOrderType.STRICT:
- return ClickhouseFunnelStrictActors
- return ClickhouseFunnelActors
diff --git a/posthog/queries/properties_timeline/properties_timeline.py b/posthog/queries/properties_timeline/properties_timeline.py
index b240f41b459a..afff3ec3b3b1 100644
--- a/posthog/queries/properties_timeline/properties_timeline.py
+++ b/posthog/queries/properties_timeline/properties_timeline.py
@@ -2,15 +2,24 @@ import json
import datetime
from typing import Any, TypedDict, Union, cast
+from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.property import action_to_expr
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.constants import TREND_FILTER_TYPE_ACTIONS
+from posthog.models.entity import Entity
from posthog.models.filters.properties_timeline_filter import PropertiesTimelineFilter
from posthog.models.group.group import Group
from posthog.models.person.person import Person
-from posthog.models.property.util import extract_tables_and_properties, get_single_or_multi_property_string_expr
+from posthog.models.property.util import extract_tables_and_properties
from posthog.models.team.team import Team
-from posthog.queries.insight import insight_sync_execute
+from posthog.queries.query_date_range import QueryDateRange
from posthog.queries.trends.util import offset_time_series_date_by_interval
-from .properties_timeline_event_query import PropertiesTimelineEventQuery
+from products.actions.backend.models.action import Action
class PropertiesTimelinePoint(TypedDict):
@@ -26,7 +35,11 @@ class PropertiesTimelineResult(TypedDict):
effective_date_to: str
-PROPERTIES_TIMELINE_SQL = """
+# relevant_event_count of each point is the number of events between consecutive changes of the
+# crucial property values. We detect changes with lagInFrame over the ordered event stream, keep only
+# the change points, then use leadInFrame (defaulting to total_events + 1 for the last segment) to
+# measure how many events each segment spans — equivalent to the legacy UNION-ALL sentinel-row trick.
+PROPERTIES_TIMELINE_HOGQL = """
SELECT
timestamp,
properties,
@@ -36,19 +49,27 @@ FROM (
timestamp,
properties,
start_event_number,
- leadInFrame(start_event_number) OVER (ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS end_event_number
+ leadInFrame(start_event_number, 1, total_events + 1) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING
+ ) AS end_event_number
FROM (
SELECT
timestamp,
- {actor_properties_column} AS properties,
- {crucial_property_columns} AS relevant_property_values,
- lagInFrame(relevant_property_values) OVER (ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS previous_relevant_property_values,
- row_number() OVER (ORDER BY timestamp ASC) AS start_event_number
- FROM ({event_query})
+ {actor_properties} AS properties,
+ {crucial_properties} AS relevant_property_values,
+ lagInFrame({crucial_properties}) OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
+ ) AS previous_relevant_property_values,
+ row_number() OVER (
+ ORDER BY timestamp ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
+ ) AS start_event_number,
+ count() OVER () AS total_events
+ FROM events
+ WHERE {where}
)
- WHERE start_event_number = 1 OR relevant_property_values != previous_relevant_property_values OR timestamp IS NULL
+ WHERE start_event_number = 1 OR relevant_property_values != previous_relevant_property_values
)
-WHERE timestamp IS NOT NULL /* Remove sentinel row */
+ORDER BY timestamp ASC
"""
@@ -79,11 +100,31 @@ class PropertiesTimeline:
return crucial_property_keys
+ def _actor_properties_chain(self, filter: PropertiesTimelineFilter) -> list[Union[str, int]]:
+ # Read the actor's properties as frozen on the event (persons-on-events columns), so the
+ # timeline reflects the values at the time of each event rather than current values.
+ if filter.aggregation_group_type_index is None:
+ return ["poe", "properties"]
+ return [f"goe_{filter.aggregation_group_type_index}", "properties"]
+
+ def _entity_expr(self, entity: Entity, team: Team) -> ast.Expr:
+ # Only the entity's event/action identity filters the timeline events — the entity's ad-hoc
+ # property filters are not applied here (they only feed crucial-property-key extraction), matching
+ # the legacy behavior.
+ if entity.type == TREND_FILTER_TYPE_ACTIONS:
+ action = Action.objects.get(pk=cast(Union[int, str], entity.id), team=team)
+ return action_to_expr(action)
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["event"]),
+ right=ast.Constant(value=entity.id),
+ )
+
def run(
self, filter: PropertiesTimelineFilter, team: Team, actor: Union[Person, Group]
) -> PropertiesTimelineResult:
if filter._date_from is not None and filter._date_to is not None and filter._date_from == filter._date_to:
- # Search for `offset_time_series_date_by_interval` in the `TrendsActors` class for context on this handling
+ # A single-point range is widened by one interval so the window actually spans some events.
filter = filter.shallow_clone(
{
"date_to": offset_time_series_date_by_interval(
@@ -94,56 +135,76 @@ class PropertiesTimeline:
}
)
- event_query = PropertiesTimelineEventQuery(
- filter=filter,
- team=team,
- )
- event_query_sql, event_query_params = event_query.get_query()
-
- crucial_property_keys = self.extract_crucial_property_keys(filter, team_id=team.pk)
- crucial_property_columns, crucial_property_params = get_single_or_multi_property_string_expr(
- sorted(crucial_property_keys),
- query_alias=None,
- table="events",
- column="person_properties",
- allow_denormalized_props=True,
- materialised_table_column="person_properties",
- )
-
- actor_properties_column = (
- "person_properties"
- if filter.aggregation_group_type_index is None
- else f"group_{filter.aggregation_group_type_index}_properties"
- )
-
- formatted_sql = PROPERTIES_TIMELINE_SQL.format(
- event_query=event_query_sql,
- crucial_property_columns=crucial_property_columns,
- actor_properties_column=actor_properties_column,
+ query_date_range = QueryDateRange(filter, team)
+ effective_date_from = query_date_range.date_from_param.replace(tzinfo=team.timezone_info)
+ effective_date_to = query_date_range.date_to_param.replace(tzinfo=team.timezone_info)
+
+ crucial_property_keys = sorted(self.extract_crucial_property_keys(filter, team_id=team.pk))
+ actor_properties_chain = self._actor_properties_chain(filter)
+ # Serialize the crucial property values to a single string for change detection. A tuple would
+ # break `lagInFrame`, whose out-of-frame default is an empty tuple that ClickHouse refuses to
+ # compare against a sized tuple.
+ crucial_properties: ast.Expr
+ if crucial_property_keys:
+ crucial_properties = ast.Call(
+ name="toString",
+ args=[
+ ast.Tuple(exprs=[ast.Field(chain=[*actor_properties_chain, key]) for key in crucial_property_keys])
+ ],
+ )
+ else:
+ crucial_properties = ast.Constant(value="")
+
+ where_exprs: list[ast.Expr] = [
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["poe", "id"]),
+ right=ast.Constant(value=actor.uuid if isinstance(actor, Person) else actor.group_key),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value=effective_date_from),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.LtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=ast.Constant(value=effective_date_to),
+ ),
+ ]
+ entity_exprs = [self._entity_expr(entity, team) for entity in filter.entities]
+ if entity_exprs:
+ where_exprs.append(ast.Or(exprs=entity_exprs) if len(entity_exprs) > 1 else entity_exprs[0])
+
+ query = parse_select(
+ PROPERTIES_TIMELINE_HOGQL,
+ placeholders={
+ "actor_properties": ast.Field(chain=actor_properties_chain),
+ "crucial_properties": crucial_properties,
+ "where": ast.And(exprs=where_exprs),
+ },
)
- params = {
- **event_query_params,
- **crucial_property_params,
- "actor_id": actor.uuid if isinstance(actor, Person) else actor.group_key,
- }
- raw_query_result = insight_sync_execute(
- formatted_sql,
- {**params, **filter.hogql_context.values},
+ response = execute_hogql_query(
+ query,
+ team=team,
query_type="properties_timeline",
- team_id=team.pk,
+ modifiers=HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
+ ),
)
return PropertiesTimelineResult(
points=[
PropertiesTimelinePoint(
+ # Returned as a datetime so DRF renders it with a "Z" suffix, matching the legacy shape.
timestamp=timestamp,
- properties=json.loads(properties),
+ properties=properties if isinstance(properties, dict) else json.loads(properties),
relevant_event_count=relevant_event_count,
)
- for timestamp, properties, relevant_event_count in raw_query_result
+ for timestamp, properties, relevant_event_count in response.results
],
- crucial_property_keys=sorted(crucial_property_keys),
- effective_date_from=event_query.effective_date_from.isoformat(),
- effective_date_to=event_query.effective_date_to.isoformat(),
+ crucial_property_keys=crucial_property_keys,
+ effective_date_from=effective_date_from.isoformat(),
+ effective_date_to=effective_date_to.isoformat(),
)
diff --git a/posthog/queries/property_values.py b/posthog/queries/property_values.py
index 7ef692c71e67..4b4ee9dca501 100644
--- a/posthog/queries/property_values.py
+++ b/posthog/queries/property_values.py
@@ -1,84 +1,15 @@
from typing import Optional
-from django.utils import timezone
-
from opentelemetry import trace
-from posthog.models.event.sql import SELECT_PROP_VALUES_SQL_WITH_FILTER
from posthog.models.person.sql import SELECT_PERSON_PROP_VALUES_SQL, SELECT_PERSON_PROP_VALUES_SQL_WITH_FILTER
from posthog.models.property.util import get_property_string_expr
from posthog.models.team import Team
from posthog.queries.insight import insight_sync_execute
-from posthog.utils import relative_date_parse
tracer = trace.get_tracer(__name__)
-def get_property_values_for_key(
- key: str,
- team: Team,
- event_names: Optional[list[str]] = None,
- value: Optional[str] = None,
-):
- with tracer.start_as_current_span("get_property_values_for_key") as span:
- span.set_attribute("team_id", team.pk)
- span.set_attribute("property_key", key)
- span.set_attribute("has_value_filter", value is not None)
- span.set_attribute("event_names_count", len(event_names) if event_names else 0)
-
- property_field, mat_column_exists = get_property_string_expr("events", key, "%(key)s", "properties")
- span.set_attribute("materialized_column", mat_column_exists)
-
- parsed_date_from = "AND timestamp >= '{}'".format(
- relative_date_parse("-7d", team.timezone_info).strftime("%Y-%m-%d 00:00:00")
- )
- parsed_date_to = "AND timestamp <= '{}'".format(timezone.now().strftime("%Y-%m-%d 23:59:59"))
- property_exists_filter = ""
- event_filter = ""
- value_filter = ""
- order_by_clause = ""
- extra_params = {}
-
- if mat_column_exists:
- property_exists_filter = "AND notEmpty({})".format(property_field)
- else:
- property_exists_filter = "AND JSONHas(properties, %(key)s)"
- extra_params["key"] = key
-
- if event_names is not None and len(event_names) > 0:
- event_conditions_list = []
- for index, event_name in enumerate(event_names):
- event_conditions_list.append(f"event = %(event_{index})s")
- extra_params[f"event_{index}"] = event_name
-
- event_conditions = " OR ".join(event_conditions_list)
- event_filter = "AND ({})".format(event_conditions)
-
- if value:
- value_filter = "AND {} ILIKE %(value)s".format(property_field)
- escaped = value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
- extra_params["value"] = "%{}%".format(escaped)
-
- order_by_clause = f"order by length({property_field})"
-
- result = insight_sync_execute(
- SELECT_PROP_VALUES_SQL_WITH_FILTER.format(
- parsed_date_from=parsed_date_from,
- parsed_date_to=parsed_date_to,
- property_field=property_field,
- event_filter=event_filter,
- value_filter=value_filter,
- property_exists_filter=property_exists_filter,
- order_by_clause=order_by_clause,
- ),
- {"team_id": team.pk, "key": key, **extra_params},
- query_type="get_property_values_with_value",
- team_id=team.pk,
- )
- span.set_attribute("result_count", len(result))
- return result
-
-
# property_values_distributed routes to the aggregated table on the aux cluster.
SELECT_EVENT_PROPERTY_VALUES_FROM_AGGREGATED_TABLE_SQL = """
SELECT DISTINCT property_value
diff --git a/posthog/queries/query_date_range.py b/posthog/queries/query_date_range.py
index ec00184a6004..599d474c9214 100644
--- a/posthog/queries/query_date_range.py
+++ b/posthog/queries/query_date_range.py
@@ -11,7 +11,7 @@ from posthog.models.filters import AnyFilter
from posthog.models.filters.base_filter import BaseFilter
from posthog.models.filters.mixins.interval import IntervalMixin
from posthog.models.team import Team
-from posthog.queries.util import TIME_IN_SECONDS, get_earliest_timestamp, get_start_of_interval_sql
+from posthog.queries.util import TIME_IN_SECONDS, get_start_of_interval_sql
from posthog.utils import DEFAULT_DATE_FROM_DAYS, relative_date_parse, relative_date_parse_with_delta_mapping
@@ -70,7 +70,10 @@ class QueryDateRange:
if self._earliest_timestamp_fallback:
return self._earliest_timestamp_fallback
- return get_earliest_timestamp(self._team.pk)
+ # Imported here to avoid a circular import at module load (timestamp_utils pulls in HogQL).
+ from posthog.hogql_queries.utils.timestamp_utils import get_earliest_timestamp_unfiltered # noqa: PLC0415
+
+ return get_earliest_timestamp_unfiltered(self._team)
@property
def date_from_param(self) -> datetime:
diff --git a/posthog/queries/test/__snapshots__/test_lifecycle.ambr b/posthog/queries/test/__snapshots__/test_lifecycle.ambr
deleted file mode 100644
index edb903c22775..000000000000
--- a/posthog/queries/test/__snapshots__/test_lifecycle.ambr
+++ /dev/null
@@ -1,220 +0,0 @@
-# serializer version: 1
-# name: TestLifecycle.test_sampling
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2020-01-19 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e SAMPLE 0.1
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC'))) + INTERVAL 1 day
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestLifecycle.test_timezones
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2020-01-19 23:59:59', 'UTC'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC')), dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'UTC'), 'UTC')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'UTC'), 'UTC')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'UTC') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC'))) + INTERVAL 1 day
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'UTC'))
- AND start_of_period >= dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'UTC'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
-# name: TestLifecycle.test_timezones.1
- '''
- WITH 'day' AS selected_period,
- periods AS
- (SELECT dateSub(day, number, dateTrunc(selected_period, toDateTime('2020-01-19 23:59:59', 'US/Pacific'))) AS start_of_period
- FROM numbers(dateDiff('day', dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'US/Pacific')), dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'US/Pacific') + INTERVAL 1 day))))
- SELECT groupArray(start_of_period) AS date,
- groupArray(counts) AS total,
- status
- FROM
- (SELECT if(status = 'dormant', toInt64(SUM(counts)) * toInt16(-1), toInt64(SUM(counts))) as counts,
- start_of_period,
- status
- FROM
- (SELECT periods.start_of_period as start_of_period,
- toUInt16(0) AS counts,
- status
- FROM periods
- CROSS JOIN
- (SELECT status
- FROM
- (SELECT ['new', 'returning', 'resurrecting', 'dormant'] as status) ARRAY
- JOIN status) as sec
- ORDER BY status,
- start_of_period
- UNION ALL SELECT start_of_period,
- count(DISTINCT person_id) counts,
- status
- FROM
- (SELECT if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- arraySort(groupUniqArray(dateTrunc('day', toTimeZone(toDateTime(events.timestamp, 'US/Pacific'), 'US/Pacific')))) AS all_activity,
- arrayPopBack(arrayPushFront(all_activity, dateTrunc('day', toTimeZone(toDateTime(min(person.created_at), 'US/Pacific'), 'US/Pacific')))) as previous_activity,
- arrayPopFront(arrayPushBack(all_activity, dateTrunc('day', toDateTime('1970-01-01')))) as following_activity,
- arrayMap((previous, current, index) -> if(previous = current, 'new', if(current - INTERVAL 1 day = previous
- AND index != 1, 'returning', 'resurrecting')), previous_activity, all_activity, arrayEnumerate(all_activity)) as initial_status,
- arrayMap((current, next) -> if(current + INTERVAL 1 day = next, '', 'dormant'), all_activity, following_activity) as dormant_status,
- arrayMap(x -> x + INTERVAL 1 day, arrayFilter((current, is_dormant) -> is_dormant = 'dormant', all_activity, dormant_status)) as dormant_periods,
- arrayMap(x -> 'dormant', dormant_periods) as dormant_label,
- arrayConcat(arrayZip(all_activity, initial_status), arrayZip(dormant_periods, dormant_label)) as temp_concat,
- arrayJoin(temp_concat) as period_status_pairs,
- period_status_pairs.1 as start_of_period,
- period_status_pairs.2 as status,
- toDateTime(min(person.created_at), 'US/Pacific') AS created_at
- FROM events AS e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(created_at, version) as created_at
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND timestamp >= toDateTime(dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'US/Pacific'))) - INTERVAL 1 day
- AND timestamp < toDateTime(dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'US/Pacific'))) + INTERVAL 1 day
- GROUP BY if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id))
- GROUP BY start_of_period,
- status)
- WHERE start_of_period <= dateTrunc('day', toDateTime('2020-01-19 23:59:59', 'US/Pacific'))
- AND start_of_period >= dateTrunc('day', toDateTime('2020-01-12 00:00:00', 'US/Pacific'))
- GROUP BY start_of_period,
- status
- ORDER BY start_of_period ASC)
- GROUP BY status
- '''
-# ---
diff --git a/posthog/queries/test/__snapshots__/test_trends.ambr b/posthog/queries/test/__snapshots__/test_trends.ambr
deleted file mode 100644
index 5440b9bad349..000000000000
--- a/posthog/queries/test/__snapshots__/test_trends.ambr
+++ /dev/null
@@ -1,6084 +0,0 @@
-# serializer version: 1
-# name: TestTrends.test_action_filtering_with_cohort
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 2
- '''
-# ---
-# name: TestTrends.test_action_filtering_with_cohort.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-07 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-07 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['x'], replaceRegexpAll(JSONExtractRaw(properties, '$bool_prop'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['x'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$bool_prop'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND ((event = 'sign up'
- AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN
- (SELECT DISTINCT person_id
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 2))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_action_filtering_with_cohort.2
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 2
- '''
-# ---
-# name: TestTrends.test_action_filtering_with_cohort.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-07 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-07 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event IN ['sign up']
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['x'], replaceRegexpAll(JSONExtractRaw(properties, '$bool_prop'), '^"|"$', ''))) )
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['x'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$bool_prop'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND ((event = 'sign up'
- AND (if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) IN
- (SELECT DISTINCT person_id
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 2 ))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_action_filtering_with_cohort_poe_v2
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 2
- '''
-# ---
-# name: TestTrends.test_action_filtering_with_cohort_poe_v2.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-07 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-07 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND ((event = 'sign up'
- AND (if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) IN
- (SELECT DISTINCT person_id
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 2))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- AND (has(['x'], replaceRegexpAll(JSONExtractRaw(e.person_properties, '$bool_prop'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_action_filtering_with_cohort_poe_v2.2
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 2
- '''
-# ---
-# name: TestTrends.test_action_filtering_with_cohort_poe_v2.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-07 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-07 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND ((event = 'sign up'
- AND (if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) IN
- (SELECT DISTINCT person_id
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 2 ))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- AND (has(['x'], replaceRegexpAll(JSONExtractRaw(e.person_properties, '$bool_prop'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_breakdown_by_group_props_person_on_events
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group0_properties, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_by_group_props_person_on_events.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(12)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['finance', 'technology'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['finance', 'technology']), (['finance', 'technology']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND notEmpty(e.person_id)
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_breakdown_by_group_props_person_on_events.2
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- e.person_id as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC')
- AND (has(['technology'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_by_group_props_with_person_filter_person_on_events
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(group0_properties, 'industry'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (has(['value'], replaceRegexpAll(JSONExtractRaw(e.person_properties, 'key'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_by_group_props_with_person_filter_person_on_events.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(12)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['finance'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['finance']), (['finance']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND (has(['value'], replaceRegexpAll(JSONExtractRaw(e.person_properties, 'key'), '^"|"$', '')))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND notEmpty(e.person_id)
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_breakdown_filtering_with_properties_in_new_format
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- AND (((has(['Firefox'], replaceRegexpAll(JSONExtractRaw(e.properties, '$browser'), '^"|"$', '')))
- OR (has(['Windows'], replaceRegexpAll(JSONExtractRaw(e.properties, '$os'), '^"|"$', ''))))
- AND (has(['Mac'], replaceRegexpAll(JSONExtractRaw(e.properties, '$os'), '^"|"$', ''))))
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_filtering_with_properties_in_new_format.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-05 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(15)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-22 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['second url'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['second url']), (['second url']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND (((has(['Firefox'], replaceRegexpAll(JSONExtractRaw(e.properties, '$browser'), '^"|"$', '')))
- OR (has(['Windows'], replaceRegexpAll(JSONExtractRaw(e.properties, '$os'), '^"|"$', ''))))
- AND (has(['Mac'], replaceRegexpAll(JSONExtractRaw(e.properties, '$os'), '^"|"$', ''))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-22 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_breakdown_filtering_with_properties_in_new_format.2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- AND (((has(['Firefox'], replaceRegexpAll(JSONExtractRaw(e.properties, '$browser'), '^"|"$', '')))
- AND (has(['Windows'], replaceRegexpAll(JSONExtractRaw(e.properties, '$os'), '^"|"$', ''))))
- AND (has(['Mac'], replaceRegexpAll(JSONExtractRaw(e.properties, '$os'), '^"|"$', ''))))
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_filtering_with_properties_in_new_format.3
- '''
- SELECT [now()] AS date,
- [0] AS total,
- '' AS breakdown_value
- LIMIT 0
- '''
-# ---
-# name: TestTrends.test_breakdown_weekly_active_users_aggregated
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', '') AS value,
- count(DISTINCT pdi.person_id) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-11 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-11 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_weekly_active_users_aggregated.1
- '''
-
- SELECT count(DISTINCT pdi.person_id) AS total,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['val', 'bor']), (['val', 'bor']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events AS e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-11 23:59:59', 'UTC')
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-04 23:59:59', 'UTC') - INTERVAL 6 DAY
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-11 23:59:59', 'UTC')
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_breakdown_weekly_active_users_aggregated_materialized
- '''
-
- SELECT "mat_key" AS value,
- count(DISTINCT pdi.person_id) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-11 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-11 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_weekly_active_users_aggregated_materialized.1
- '''
-
- SELECT count(DISTINCT pdi.person_id) AS total,
- transform(ifNull(nullIf("mat_key", ''), '$$_posthog_breakdown_null_$$'), (['val', 'bor']), (['val', 'bor']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events AS e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-11 23:59:59', 'UTC')
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-04 23:59:59', 'UTC') - INTERVAL 6 DAY
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-11 23:59:59', 'UTC')
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_breakdown_weekly_active_users_daily_based_on_action
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', '') AS value,
- count(DISTINCT pdi.person_id) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON pdi.person_id = person.id
- WHERE team_id = 99999
- AND ((event = '$pageview'
- AND (has(['p1', 'p2', 'p3'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))
- AND pdi.person_id IN (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', ''), tuple('p1', 'p2'))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE in(persons.properties___name,
- tuple('p1', 'p2'))
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_weekly_active_users_daily_based_on_action.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(12)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['val'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT counts AS total,
- timestamp AS day_start,
- breakdown_value
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT person_id) counts,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS timestamp
- FROM events e
- WHERE team_id = 99999
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-25 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY timestamp) d
- CROSS JOIN
- (SELECT toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS timestamp,
- pdi.person_id AS person_id,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['val']), (['val']), '$$_posthog_breakdown_other_$$') AS breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE e.team_id = 99999
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-25 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND ((event = '$pageview'
- AND (has(['p1', 'p2', 'p3'], replaceRegexpAll(JSONExtractRaw(person_props, 'name'), '^"|"$', ''))
- AND pdi.person_id IN (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '')), person.version), 1) AS properties___name,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, 'name'), ''), 'null'), '^"|"$', ''), tuple('p1', 'p2'))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE in(persons.properties___name,
- tuple('p1', 'p2'))
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')))))
- GROUP BY timestamp, person_id,
- breakdown_value) e
- WHERE e.timestamp <= d.timestamp
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp,
- breakdown_value
- ORDER BY d.timestamp)
- WHERE 11111 = 11111
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_breakdown_with_filter_groups_person_on_events
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_with_filter_groups_person_on_events.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(12)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['uh', 'oh'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['uh', 'oh']), (['uh', 'oh']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_breakdown_with_filter_groups_person_on_events_v2
- '''
-
- SELECT DISTINCT person_id
- FROM events
- WHERE team_id = 99999
- AND distinct_id = 'test_breakdown_d2'
- '''
-# ---
-# name: TestTrends.test_breakdown_with_filter_groups_person_on_events_v2.1
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_breakdown_with_filter_groups_person_on_events_v2.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(12)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['uh', 'oh'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id)) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, 'key'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['uh', 'oh']), (['uh', 'oh']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND (has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND notEmpty(e.person_id)
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_dau_with_breakdown_filtering_with_sampling
- '''
- /* celery:posthog.tasks.tasks.sync_insight_caching_state */
- SELECT team_id,
- date_diff('second', max(timestamp), now()) AS age
- FROM events
- WHERE timestamp > date_sub(DAY, 3, now())
- AND timestamp < now()
- GROUP BY team_id
- ORDER BY age;
- '''
-# ---
-# name: TestTrends.test_dau_with_breakdown_filtering_with_sampling.1
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e SAMPLE 1.0
- WHERE team_id = 99999
- AND ((event = 'sign up'))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_dau_with_breakdown_filtering_with_sampling.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['other_value', '$$_posthog_breakdown_null_$$', 'value'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT pdi.person_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['other_value', '$$_posthog_breakdown_null_$$', 'value']), (['other_value', '$$_posthog_breakdown_null_$$', 'value']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e SAMPLE 1.0
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND ((event = 'sign up'))
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_dau_with_breakdown_filtering_with_sampling.3
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e SAMPLE 1.0
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_dau_with_breakdown_filtering_with_sampling.4
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['other_value', '$$_posthog_breakdown_null_$$', 'value'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT pdi.person_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['other_value', '$$_posthog_breakdown_null_$$', 'value']), (['other_value', '$$_posthog_breakdown_null_$$', 'value']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e SAMPLE 1.0
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_filter_events_by_precalculated_cohort
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestTrends.test_filter_events_by_precalculated_cohort.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-02 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), toDateTime('2020-01-02 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Jane'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Jane'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_filter_events_by_precalculated_cohort.2
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestTrends.test_filter_events_by_precalculated_cohort.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-02 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), toDateTime('2020-01-02 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['Jane'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', ''))) )
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['Jane'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_filter_events_by_precalculated_cohort_poe_v2
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestTrends.test_filter_events_by_precalculated_cohort_poe_v2.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-02 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), toDateTime('2020-01-02 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC')
- AND (has(['Jane'], replaceRegexpAll(JSONExtractRaw(e.person_properties, 'name'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_filter_events_by_precalculated_cohort_poe_v2.2
- '''
-
- SELECT count(DISTINCT person_id)
- FROM cohortpeople
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND version = 0
- '''
-# ---
-# name: TestTrends.test_filter_events_by_precalculated_cohort_poe_v2.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-02 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), toDateTime('2020-01-02 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'event_name'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-26 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC')
- AND (has(['Jane'], replaceRegexpAll(JSONExtractRaw(e.person_properties, 'name'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_filtering_by_multiple_groups_person_on_events
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-12 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_2
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 2
- GROUP BY group_key) groups_2 ON "$group_2" == groups_2.group_key
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND ((has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (has(['six'], replaceRegexpAll(JSONExtractRaw(group_properties_2, 'name'), '^"|"$', ''))))
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_filtering_by_multiple_groups_person_on_events.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- e.person_id as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_2
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 2
- GROUP BY group_key) groups_2 ON "$group_2" == groups_2.group_key
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-02 23:59:59', 'UTC')
- AND ((has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (has(['six'], replaceRegexpAll(JSONExtractRaw(group_properties_2, 'name'), '^"|"$', ''))))
- AND notEmpty(e.person_id))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_filtering_with_group_props_person_on_events
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-12 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT JOIN
- (SELECT group_key,
- argMax(group_properties, _timestamp) AS group_properties_0
- FROM groups
- WHERE team_id = 99999
- AND group_type_index = 0
- GROUP BY group_key) groups_0 ON "$group_0" == groups_0.group_key
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND ((has(['finance'], replaceRegexpAll(JSONExtractRaw(group_properties_0, 'industry'), '^"|"$', '')))
- AND (has(['value'], replaceRegexpAll(JSONExtractRaw(e.person_properties, 'key'), '^"|"$', ''))))
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_mau_with_breakdown_filtering_and_prop_filter
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(person_props, '$some_prop'), '^"|"$', '') AS value,
- count(DISTINCT pdi.person_id) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['filter_val'], replaceRegexpAll(JSONExtractRaw(properties, 'filter_prop'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['filter_val'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'filter_prop'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON pdi.person_id = person.id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_mau_with_breakdown_filtering_and_prop_filter.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['some_val2', 'some_val'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT counts AS total,
- timestamp AS day_start,
- breakdown_value
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT person_id) counts,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS timestamp
- FROM events e
- WHERE team_id = 99999
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY timestamp) d
- CROSS JOIN
- (SELECT toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS timestamp,
- pdi.person_id AS person_id,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(person_props, '$some_prop'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['some_val2', 'some_val']), (['some_val2', 'some_val']), '$$_posthog_breakdown_other_$$') AS breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['filter_val'], replaceRegexpAll(JSONExtractRaw(properties, 'filter_prop'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['filter_val'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'filter_prop'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY timestamp, person_id,
- breakdown_value) e
- WHERE e.timestamp <= d.timestamp
- AND e.timestamp > d.timestamp - INTERVAL 29 DAY
- GROUP BY d.timestamp,
- breakdown_value
- ORDER BY d.timestamp)
- WHERE 11111 = 11111
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_mau_with_breakdown_filtering_and_prop_filter_poe_v2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(person_properties, '$some_prop'), '^"|"$', '') AS value,
- count(DISTINCT if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id)) as count
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND (has(['filter_val'], replaceRegexpAll(JSONExtractRaw(e.person_properties, 'filter_prop'), '^"|"$', '')))
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_mau_with_breakdown_filtering_and_prop_filter_poe_v2.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['some_val2', 'some_val'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT counts AS total,
- timestamp AS day_start,
- breakdown_value
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT person_id) counts,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS timestamp
- FROM events e
- WHERE team_id = 99999
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY timestamp) d
- CROSS JOIN
- (SELECT toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS timestamp,
- if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) AS person_id,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(person_properties, '$some_prop'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['some_val2', 'some_val']), (['some_val2', 'some_val']), '$$_posthog_breakdown_other_$$') AS breakdown_value
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND (has(['filter_val'], replaceRegexpAll(JSONExtractRaw(e.person_properties, 'filter_prop'), '^"|"$', '')))
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND notEmpty(e.person_id)
- GROUP BY timestamp, person_id,
- breakdown_value) e
- WHERE e.timestamp <= d.timestamp
- AND e.timestamp > d.timestamp - INTERVAL 29 DAY
- GROUP BY d.timestamp,
- breakdown_value
- ORDER BY d.timestamp)
- WHERE 11111 = 11111
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_non_deterministic_timezones
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2022-11-30 23:59:59', 'US/Pacific'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2022-10-31 00:00:00', 'US/Pacific'), 0), toDateTime('2022-11-30 23:59:59', 'US/Pacific')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2022-10-31 00:00:00', 'US/Pacific'), 0)
- UNION ALL SELECT count(*) AS total,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'US/Pacific'), 0) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'US/Pacific') >= toDateTime(toStartOfWeek(toDateTime('2022-10-31 00:00:00', 'US/Pacific'), 0), 'US/Pacific')
- AND toTimeZone(timestamp, 'US/Pacific') <= toDateTime('2022-11-30 23:59:59', 'US/Pacific')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_person_filtering_in_cohort_in_action
- '''
- /* celery:posthog.tasks.tasks.sync_insight_caching_state */
- SELECT team_id,
- date_diff('second', max(timestamp), now()) AS age
- FROM events
- WHERE timestamp > date_sub(DAY, 3, now())
- AND timestamp < now()
- GROUP BY team_id
- ORDER BY age;
- '''
-# ---
-# name: TestTrends.test_person_filtering_in_cohort_in_action.1
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND ((event = 'sign up'
- AND (pdi.person_id IN (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$some_prop'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$some_prop`,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, '$some_prop'), ''), 'null'), '^"|"$', ''), 'some_val'), 0)))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(equals(persons.`properties___$some_prop`, 'some_val'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_person_filtering_in_cohort_in_action.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$', 'value', 'other_value'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'value', 'other_value']), (['$$_posthog_breakdown_null_$$', 'value', 'other_value']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND ((event = 'sign up'
- AND (pdi.person_id IN (
- (SELECT persons.id AS id
- FROM
- (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$some_prop'), ''), 'null'), '^"|"$', '')), person.version), 1) AS `properties___$some_prop`,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(where_optimization.properties, '$some_prop'), ''), 'null'), '^"|"$', ''), 'some_val'), 0)))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- WHERE ifNull(equals(persons.`properties___$some_prop`, 'some_val'), 0)
- ORDER BY persons.id ASC
- LIMIT 1000000000 SETTINGS optimize_aggregation_in_order=1,
- join_algorithm='auto')))))
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_person_filtering_in_cohort_in_action_poe_v2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND ((event = 'sign up'
- AND (if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['some_val'], replaceRegexpAll(JSONExtractRaw(properties, '$some_prop'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['some_val'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$some_prop'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_person_filtering_in_cohort_in_action_poe_v2.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$', 'value', 'other_value'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'value', 'other_value']), (['$$_posthog_breakdown_null_$$', 'value', 'other_value']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE e.team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND ((event = 'sign up'
- AND (if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((has(['some_val'], replaceRegexpAll(JSONExtractRaw(properties, '$some_prop'), '^"|"$', '')))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((has(['some_val'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$some_prop'), '^"|"$', '')))) SETTINGS optimize_aggregation_in_order = 1))))
- AND notEmpty(e.person_id)
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_person_property_filtering
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['person1'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['person1'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_person_property_filtering_clashing_with_event_property
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['person1'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['person1'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_person_property_filtering_clashing_with_event_property.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND (has(['1'], replaceRegexpAll(JSONExtractRaw(e.properties, 'name'), '^"|"$', '')))
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_person_property_filtering_clashing_with_event_property_materialized
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['person1'], "pmat_name")))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['person1'], argMax(person."pmat_name", version))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_person_property_filtering_clashing_with_event_property_materialized.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND (has(['1'], "mat_name"))
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_person_property_filtering_materialized
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['person1'], "pmat_name")))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['person1'], argMax(person."pmat_name", version))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2
- '''
-
- SELECT DISTINCT person_id
- FROM events
- WHERE team_id = 99999
- AND distinct_id = 'distinctid2'
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC')), toDateTime('2020-01-03 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-03 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-03 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC')), toDateTime('2020-01-03 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT if(notEmpty(overrides.person_id), overrides.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-03 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-03 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2_latest_override
- '''
-
- SELECT DISTINCT person_id
- FROM events
- WHERE team_id = 99999
- AND distinct_id = 'distinctid2'
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2_latest_override.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC')), toDateTime('2020-01-03 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT if(notEmpty(overrides.person_id), overrides.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-03 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-03 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2_latest_override.2
- '''
-
- SELECT DISTINCT person_id
- FROM events
- WHERE team_id = 99999
- AND distinct_id = 'distinctid3'
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2_latest_override.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC')), toDateTime('2020-01-03 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT if(notEmpty(overrides.person_id), overrides.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-03 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-03 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2_latest_override.4
- '''
-
- SELECT DISTINCT person_id
- FROM events
- WHERE team_id = 99999
- AND distinct_id = 'distinctid2'
- '''
-# ---
-# name: TestTrends.test_same_day_with_person_on_events_v2_latest_override.5
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC')), toDateTime('2020-01-03 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-03 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT if(notEmpty(overrides.person_id), overrides.person_id, e.person_id)) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-03 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-03 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC')), toDateTime('2020-01-05 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-22 00:00:00', 'UTC')), toDateTime('2020-01-05 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-22 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT pdi.person_id) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-22 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-22 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC')), toDateTime('2020-01-05 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2020-01-05 23:59:59', 'UTC')) - toIntervalDay(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-22 00:00:00', 'UTC')), toDateTime('2020-01-05 23:59:59', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC')), toDateTime('2020-01-05 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily.4
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-29 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_timezones_daily.5
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-05 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['Mac'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT pdi.person_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['Mac']), (['Mac']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_timezones_daily_minus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'America/Phoenix')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix')), toDateTime('2020-01-05 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily_minus_utc.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'America/Phoenix')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-22 00:00:00', 'America/Phoenix')), toDateTime('2020-01-05 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-22 00:00:00', 'America/Phoenix'))
- UNION ALL SELECT count(DISTINCT pdi.person_id) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfDay(toDateTime('2019-12-22 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfDay(toDateTime('2019-12-22 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily_minus_utc.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'America/Phoenix')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix')), toDateTime('2020-01-05 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2020-01-05 23:59:59', 'America/Phoenix')) - toIntervalDay(number), 'America/Phoenix') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-22 00:00:00', 'America/Phoenix')), toDateTime('2020-01-05 23:59:59', 'America/Phoenix')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily_minus_utc.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'America/Phoenix')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix')), toDateTime('2020-01-05 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily_minus_utc.4
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime('2019-12-29 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_timezones_daily_minus_utc.5
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-05 23:59:59', 'America/Phoenix')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['Mac'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT pdi.person_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['Mac']), (['Mac']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 23:59:59', 'America/Phoenix')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_timezones_daily_plus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily_plus_utc.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo'))
- UNION ALL SELECT count(DISTINCT pdi.person_id) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfDay(toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfDay(toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily_plus_utc.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')) - toIntervalDay(number), 'Asia/Tokyo') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily_plus_utc.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_daily_plus_utc.4
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_timezones_daily_plus_utc.5
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['Mac'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT pdi.person_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['Mac']), (['Mac']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfDay(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 23:59:59', 'Asia/Tokyo')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 10:59:59', 'UTC')) - toIntervalHour(number) AS day_start
- FROM numbers(dateDiff('hour', toStartOfHour(toDateTime('2020-01-05 00:00:00', 'UTC')), toDateTime('2020-01-05 10:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT pdi.person_id) AS total,
- toStartOfHour(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 10:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 10:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-05 07:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 08:00:00', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-05 07:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 08:00:00', 'UTC'))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 10:59:59', 'UTC')) - toIntervalHour(number) AS day_start
- FROM numbers(dateDiff('hour', toStartOfHour(toDateTime('2020-01-05 00:00:00', 'UTC')), toDateTime('2020-01-05 10:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfHour(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-05 10:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from_minus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 10:59:59', 'America/Phoenix')) - toIntervalHour(number) AS day_start
- FROM numbers(dateDiff('hour', toStartOfHour(toDateTime('2020-01-05 00:00:00', 'America/Phoenix')), toDateTime('2020-01-05 10:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 00:00:00', 'America/Phoenix'))
- UNION ALL SELECT count(DISTINCT pdi.person_id) AS total,
- toStartOfHour(toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 10:59:59', 'America/Phoenix'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 10:59:59', 'America/Phoenix')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from_minus_utc.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime('2020-01-05 07:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 08:00:00', 'America/Phoenix'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime('2020-01-05 07:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 08:00:00', 'America/Phoenix'))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from_minus_utc.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 10:59:59', 'America/Phoenix')) - toIntervalHour(number) AS day_start
- FROM numbers(dateDiff('hour', toStartOfHour(toDateTime('2020-01-05 00:00:00', 'America/Phoenix')), toDateTime('2020-01-05 10:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 00:00:00', 'America/Phoenix'))
- UNION ALL SELECT count(*) AS total,
- toStartOfHour(toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-05 10:59:59', 'America/Phoenix')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from_plus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 10:59:59', 'Asia/Tokyo')) - toIntervalHour(number) AS day_start
- FROM numbers(dateDiff('hour', toStartOfHour(toDateTime('2020-01-05 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-05 10:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 00:00:00', 'Asia/Tokyo'))
- UNION ALL SELECT count(DISTINCT pdi.person_id) AS total,
- toStartOfHour(toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 10:59:59', 'Asia/Tokyo'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 10:59:59', 'Asia/Tokyo')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from_plus_utc.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime('2020-01-05 07:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 08:00:00', 'Asia/Tokyo'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime('2020-01-05 07:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 08:00:00', 'Asia/Tokyo'))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_timezones_hourly_relative_from_plus_utc.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 10:59:59', 'Asia/Tokyo')) - toIntervalHour(number) AS day_start
- FROM numbers(dateDiff('hour', toStartOfHour(toDateTime('2020-01-05 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-05 10:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-05 00:00:00', 'Asia/Tokyo'))
- UNION ALL SELECT count(*) AS total,
- toStartOfHour(toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfHour(toDateTime('2020-01-05 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-05 10:59:59', 'Asia/Tokyo')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_weekly
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-26 23:59:59', 'UTC'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'UTC'), 0), toDateTime('2020-01-26 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'UTC'), 0)
- UNION ALL SELECT count(*) AS total,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC'), 0) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'UTC'), 0), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-26 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_weekly.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-26 23:59:59', 'UTC'), 3) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'UTC'), 3), toDateTime('2020-01-26 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'UTC'), 3)
- UNION ALL SELECT count(*) AS total,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC'), 3) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'UTC'), 3), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-26 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_weekly_minus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-26 23:59:59', 'America/Phoenix'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'America/Phoenix'), 0), toDateTime('2020-01-26 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'America/Phoenix'), 0)
- UNION ALL SELECT count(*) AS total,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix'), 0) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'America/Phoenix'), 0), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-26 23:59:59', 'America/Phoenix')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_weekly_minus_utc.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-26 23:59:59', 'America/Phoenix'), 3) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'America/Phoenix'), 3), toDateTime('2020-01-26 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'America/Phoenix'), 3)
- UNION ALL SELECT count(*) AS total,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix'), 3) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'America/Phoenix'), 3), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-26 23:59:59', 'America/Phoenix')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_weekly_plus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-26 23:59:59', 'Asia/Tokyo'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'Asia/Tokyo'), 0), toDateTime('2020-01-26 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'Asia/Tokyo'), 0)
- UNION ALL SELECT count(*) AS total,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo'), 0) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'Asia/Tokyo'), 0), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-26 23:59:59', 'Asia/Tokyo')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_timezones_weekly_plus_utc.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-26 23:59:59', 'Asia/Tokyo'), 3) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'Asia/Tokyo'), 3), toDateTime('2020-01-26 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'Asia/Tokyo'), 3)
- UNION ALL SELECT count(*) AS total,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo'), 3) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfWeek(toDateTime('2020-01-12 00:00:00', 'Asia/Tokyo'), 3), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-26 23:59:59', 'Asia/Tokyo')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trend_actors_person_on_events_pagination_with_alias_inconsistencies
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT e.person_id) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trend_actors_person_on_events_pagination_with_alias_inconsistencies.1
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- e.person_id as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-04 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-04 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 5
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trend_actors_person_on_events_pagination_with_alias_inconsistencies.2
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- e.person_id as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-04 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-04 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 5
- OFFSET 5
- '''
-# ---
-# name: TestTrends.test_trend_actors_person_on_events_pagination_with_alias_inconsistencies.3
- '''
- /* user_id:0 request:_snapshot_ */
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- e.person_id as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-04 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-04 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 5
- OFFSET 10
- '''
-# ---
-# name: TestTrends.test_trend_breakdown_user_props_with_filter_with_partial_property_pushdowns
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(person_props, 'email'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (((has(['android'], replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', '')))
- OR (has(['safari'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''))))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (((has(['android'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$os'), '^"|"$', '')))
- OR (has(['safari'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', ''))))) SETTINGS optimize_aggregation_in_order = 1) person ON pdi.person_id = person.id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC')
- AND (((NOT (replaceRegexpAll(JSONExtractRaw(person_props, 'email'), '^"|"$', '') ILIKE '%@posthog.com%'))
- OR (has(['val'], replaceRegexpAll(JSONExtractRaw(e.properties, 'key'), '^"|"$', '')))))
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trend_breakdown_user_props_with_filter_with_partial_property_pushdowns.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-07-01 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(183)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(person_props, 'email'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']), (['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (((has(['android'], replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', '')))
- OR (has(['safari'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', ''))))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (((has(['android'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$os'), '^"|"$', '')))
- OR (has(['safari'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', ''))))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND (((NOT (replaceRegexpAll(JSONExtractRaw(person_props, 'email'), '^"|"$', '') ILIKE '%@posthog.com%'))
- OR (has(['val'], replaceRegexpAll(JSONExtractRaw(e.properties, 'key'), '^"|"$', '')))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trend_breakdown_user_props_with_filter_with_partial_property_pushdowns.2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(person_props, 'email'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((((has(['android'], replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', '')))
- AND (has(['chrome'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')))))
- AND (replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%@posthog.com%')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((((has(['android'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$os'), '^"|"$', '')))
- AND (has(['chrome'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', '')))))
- AND (replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%@posthog.com%')) SETTINGS optimize_aggregation_in_order = 1) person ON pdi.person_id = person.id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC')
- AND ((has(['val'], replaceRegexpAll(JSONExtractRaw(e.properties, 'key'), '^"|"$', ''))))
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trend_breakdown_user_props_with_filter_with_partial_property_pushdowns.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-07-01 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(183)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['[email protected]'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(person_props, 'email'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['[email protected]']), (['[email protected]']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND ((((has(['android'], replaceRegexpAll(JSONExtractRaw(properties, '$os'), '^"|"$', '')))
- AND (has(['chrome'], replaceRegexpAll(JSONExtractRaw(properties, '$browser'), '^"|"$', '')))))
- AND (replaceRegexpAll(JSONExtractRaw(properties, 'email'), '^"|"$', '') ILIKE '%@posthog.com%')))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND ((((has(['android'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$os'), '^"|"$', '')))
- AND (has(['chrome'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$browser'), '^"|"$', '')))))
- AND (replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'email'), '^"|"$', '') ILIKE '%@posthog.com%')) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND ((has(['val'], replaceRegexpAll(JSONExtractRaw(e.properties, 'key'), '^"|"$', ''))))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-07-01 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_aggregate_by_distinct_id
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-31 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), toDateTime('2019-12-31 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT e.distinct_id) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_aggregate_by_distinct_id.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-31 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), toDateTime('2019-12-31 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC'))
- UNION ALL SELECT count(DISTINCT e.distinct_id) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['some_val'], replaceRegexpAll(JSONExtractRaw(properties, '$some_prop'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['some_val'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), '$some_prop'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_aggregate_by_distinct_id.2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(person_props, '$some_prop'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON pdi.person_id = person.id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-24 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_aggregate_by_distinct_id.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2019-12-31 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['some_val', '$$_posthog_breakdown_null_$$'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT e.distinct_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(person_props, '$some_prop'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['some_val', '$$_posthog_breakdown_null_$$']), (['some_val', '$$_posthog_breakdown_null_$$']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_aggregate_by_distinct_id.4
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-31 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), toDateTime('2019-12-31 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2019-12-31 23:59:59', 'UTC')) - toIntervalDay(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-11-24 00:00:00', 'UTC')), toDateTime('2019-12-31 23:59:59', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- e.distinct_id AS actor_id
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-24 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 29 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_aggregate_by_distinct_id.5
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-31 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), toDateTime('2019-12-31 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2019-12-31 23:59:59', 'UTC')) - toIntervalDay(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-17 00:00:00', 'UTC')), toDateTime('2019-12-31 23:59:59', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- e.distinct_id AS actor_id
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-17 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_aggregate_by_distinct_id.6
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_prop'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-24 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_aggregate_by_distinct_id.7
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2019-12-31 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT e.distinct_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_prop'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$']), (['$$_posthog_breakdown_null_$$']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-24 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-31 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_any_event_total_count
- '''
- /* celery:posthog.tasks.tasks.sync_insight_caching_state */
- SELECT team_id,
- date_diff('second', max(timestamp), now()) AS age
- FROM events
- WHERE timestamp > date_sub(DAY, 3, now())
- AND timestamp < now()
- GROUP BY team_id
- ORDER BY age;
- '''
-# ---
-# name: TestTrends.test_trends_any_event_total_count.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_any_event_total_count.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_cumulative
- '''
- /* celery:posthog.tasks.tasks.sync_insight_caching_state */
- SELECT team_id,
- date_diff('second', max(timestamp), now()) AS age
- FROM events
- WHERE timestamp > date_sub(DAY, 3, now())
- AND timestamp < now()
- GROUP BY team_id
- ORDER BY age;
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_cumulative.1
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_cumulative.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$', 'value', 'other_value'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT person_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- breakdown_value
- FROM
- (SELECT person_id,
- min(timestamp) as timestamp,
- breakdown_value
- FROM
- (SELECT pdi.person_id as person_id, timestamp, transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'value', 'other_value']), (['$$_posthog_breakdown_null_$$', 'value', 'other_value']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY person_id,
- breakdown_value) AS pdi
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_cumulative_poe_v2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_cumulative_poe_v2.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$', 'value', 'other_value'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT person_id) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- breakdown_value
- FROM
- (SELECT person_id,
- min(timestamp) as timestamp,
- breakdown_value
- FROM
- (SELECT if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id) as person_id, timestamp, transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'value', 'other_value']), (['$$_posthog_breakdown_null_$$', 'value', 'other_value']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- AND notEmpty(e.person_id))
- GROUP BY person_id,
- breakdown_value) AS pdi
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- quantile(0.50)(session_duration) as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown.1
- '''
-
- SELECT quantile(0.50)(session_duration) AS total,
- breakdown_value
- FROM
- (SELECT any(session_duration) as session_duration,
- breakdown_value
- FROM
- (SELECT sessions.$session_id,
- session_duration,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['value2', 'value1', '$$_posthog_breakdown_null_$$']), (['value2', 'value1', '$$_posthog_breakdown_null_$$']), '$$_posthog_breakdown_other_$$') AS breakdown_value
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY sessions.$session_id,
- breakdown_value)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown.2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- quantile(0.50)(session_duration) as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown.3
- '''
-
- SELECT quantile(0.50)(session_duration) AS total,
- breakdown_value
- FROM
- (SELECT any(session_duration) as session_duration,
- breakdown_value
- FROM
- (SELECT sessions.$session_id,
- session_duration,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['value2', 'value1', '$$_posthog_breakdown_null_$$']), (['value2', 'value1', '$$_posthog_breakdown_null_$$']), '$$_posthog_breakdown_other_$$') AS breakdown_value
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY sessions.$session_id,
- breakdown_value)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_compare_day_interval_relative_range
- '''
- /* celery:posthog.tasks.tasks.sync_insight_caching_state */
- SELECT team_id,
- date_diff('second', max(timestamp), now()) AS age
- FROM events
- WHERE timestamp > date_sub(DAY, 3, now())
- AND timestamp < now()
- GROUP BY team_id
- ORDER BY age;
- '''
-# ---
-# name: TestTrends.test_trends_compare_day_interval_relative_range.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_compare_day_interval_relative_range.2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-21 00:00:00', 'UTC')), toDateTime('2019-12-28 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-21 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-21 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2019-12-28 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_compare_day_interval_relative_range.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_count_per_group_average_aggregated
- '''
-
- SELECT avg(intermediate_count) AS total
- FROM
- (SELECT count() AS intermediate_count
- FROM events e
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- AND "$group_0" != ''
- GROUP BY "$group_0") events
- '''
-# ---
-# name: TestTrends.test_trends_count_per_group_average_daily
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-07 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-07 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT avg(intermediate_count) AS total, date
- FROM
- (SELECT count() AS intermediate_count,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- AND "$group_0" != ''
- GROUP BY "$group_0", date)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_count_per_user_average_aggregated
- '''
-
- SELECT avg(intermediate_count) AS total
- FROM
- (SELECT count() AS intermediate_count
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- GROUP BY pdi.person_id) events
- '''
-# ---
-# name: TestTrends.test_trends_count_per_user_average_aggregated_poe_v2
- '''
-
- SELECT avg(intermediate_count) AS total
- FROM
- (SELECT count() AS intermediate_count
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id)) events
- '''
-# ---
-# name: TestTrends.test_trends_count_per_user_average_aggregated_with_event_property_breakdown_with_sampling
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, 'color'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e SAMPLE 1.0
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON pdi.person_id = person.id
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_count_per_user_average_aggregated_with_event_property_breakdown_with_sampling.1
- '''
-
- SELECT avg(intermediate_count) AS total,
- breakdown_value
- FROM
- (SELECT COUNT(*) AS intermediate_count,
- pdi.person_id,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, 'color'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['red', 'blue', '$$_posthog_breakdown_null_$$']), (['red', 'blue', '$$_posthog_breakdown_null_$$']), '$$_posthog_breakdown_other_$$') AS breakdown_value
- FROM events AS e SAMPLE 1.0
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE e.team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- GROUP BY pdi.person_id,
- breakdown_value)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_count_per_user_average_daily
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-07 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-07 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT avg(intermediate_count) AS total, date
- FROM
- (SELECT count() AS intermediate_count,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- GROUP BY pdi.person_id, date)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_count_per_user_average_daily_poe_v2
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-07 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-07 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT avg(intermediate_count) AS total, date
- FROM
- (SELECT count() AS intermediate_count,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0), 0)) AS overrides ON e.distinct_id = overrides.distinct_id
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-07 23:59:59', 'UTC')
- AND notEmpty(e.person_id)
- GROUP BY if(notEmpty(overrides.distinct_id), overrides.person_id, e.person_id), date)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_groups_per_day_cumulative
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-06 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-30 00:00:00', 'UTC')), toDateTime('2020-01-06 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-30 00:00:00', 'UTC'))
- UNION ALL SELECT COUNT(DISTINCT actor_id) AS total,
- toStartOfDay(toTimeZone(toDateTime(first_seen_timestamp, 'UTC'), 'UTC')) AS date
- FROM
- (SELECT "$group_0" AS actor_id,
- min(timestamp) AS first_seen_timestamp
- FROM events e
- WHERE team_id = 99999
- AND event = 'viewed video'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-30 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-06 23:59:59', 'UTC')
- AND (NOT has([''], "$group_0"))
- AND "$group_0" != ''
- GROUP BY actor_id)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_per_day_cumulative
- '''
- /* celery:posthog.tasks.tasks.sync_insight_caching_state */
- SELECT team_id,
- date_diff('second', max(timestamp), now()) AS age
- FROM events
- WHERE timestamp > date_sub(DAY, 3, now())
- AND timestamp < now()
- GROUP BY team_id
- ORDER BY age;
- '''
-# ---
-# name: TestTrends.test_trends_per_day_cumulative.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT count(*) AS total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_person_breakdown_with_session_property_single_aggregate_math_and_breakdown
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(person_props, '$some_prop'), '^"|"$', '') AS value,
- quantile(0.50)(session_duration) as count
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON pdi.person_id = person.id
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_person_breakdown_with_session_property_single_aggregate_math_and_breakdown.1
- '''
-
- SELECT quantile(0.50)(session_duration) AS total,
- breakdown_value
- FROM
- (SELECT any(session_duration) as session_duration,
- breakdown_value
- FROM
- (SELECT sessions.$session_id,
- session_duration,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(person_props, '$some_prop'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['some_val', 'another_val']), (['some_val', 'another_val']), '$$_posthog_breakdown_other_$$') AS breakdown_value
- FROM events e
- INNER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) as pdi ON events.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id,
- argMax(properties, version) as person_props
- FROM person
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY sessions.$session_id,
- breakdown_value)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_with_hogql_math
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-04 23:59:59', 'UTC'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0)
- UNION ALL SELECT plus(avg(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, 'x'), ''), 'null'), '^"|"$', ''), 'Int64')), 1000) AS total,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC'), 0) AS date
- FROM events e
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_with_session_property_single_aggregate_math
- '''
-
- SELECT quantile(0.50)(session_duration) AS total
- FROM
- (SELECT any(session_duration) as session_duration
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") as sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY e."$session_id")
- '''
-# ---
-# name: TestTrends.test_trends_with_session_property_single_aggregate_math.1
- '''
-
- SELECT quantile(0.50)(session_duration) AS total
- FROM
- (SELECT any(session_duration) as session_duration
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") as sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY e."$session_id")
- '''
-# ---
-# name: TestTrends.test_trends_with_session_property_total_volume_math
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-04 23:59:59', 'UTC'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0)
- UNION ALL SELECT quantile(0.50)(session_duration) AS total, date
- FROM
- (SELECT toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC'), 0) as date,
- any(sessions.session_duration) as session_duration
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") as sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY e."$session_id", date)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_with_session_property_total_volume_math.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), toDateTime('2020-01-04 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC'))
- UNION ALL SELECT quantile(0.50)(session_duration) AS total, date
- FROM
- (SELECT toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as date,
- any(sessions.session_duration) as session_duration
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") as sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY e."$session_id", date)
- GROUP BY date)
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_trends_with_session_property_total_volume_math_with_breakdowns
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- quantile(0.50)(session_duration) as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_with_session_property_total_volume_math_with_breakdowns.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfWeek(toDateTime('2020-01-04 23:59:59', 'UTC'), 0) - toIntervalWeek(number) as day_start
- FROM numbers(2)
- UNION ALL SELECT toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['value2', 'value1'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT quantile(0.50)(session_duration) as total,
- day_start,
- breakdown_value
- FROM
- (SELECT any(session_duration) as session_duration,
- day_start,
- breakdown_value
- FROM
- (SELECT sessions.$session_id,
- session_duration,
- toStartOfWeek(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC'), 0) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['value2', 'value1']), (['value2', 'value1']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events AS e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2019-12-28 00:00:00', 'UTC'), 0), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY sessions.$session_id,
- day_start,
- breakdown_value)
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_trends_with_session_property_total_volume_math_with_breakdowns.2
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', '') AS value,
- quantile(0.50)(session_duration) as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestTrends.test_trends_with_session_property_total_volume_math_with_breakdowns.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-04 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(8)
- UNION ALL SELECT toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['value2', 'value1'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT quantile(0.50)(session_duration) as total,
- day_start,
- breakdown_value
- FROM
- (SELECT any(session_duration) as session_duration,
- day_start,
- breakdown_value
- FROM
- (SELECT sessions.$session_id,
- session_duration,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$some_property'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['value2', 'value1']), (['value2', 'value1']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events AS e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2019-12-28 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'sign up'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2019-12-28 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-04 23:59:59', 'UTC'))
- GROUP BY sessions.$session_id,
- day_start,
- breakdown_value)
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_aggregated_range_narrower_than_week
- '''
-
- SELECT count(DISTINCT pdi.person_id) AS total
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-05 23:59:59', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-05 23:59:59', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_aggregated_range_wider_than_week
- '''
-
- SELECT count(DISTINCT pdi.person_id) AS total
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-11 23:59:59', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-18 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-11 23:59:59', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-18 23:59:59', 'UTC')
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_aggregated_range_wider_than_week_with_sampling
- '''
-
- SELECT count(DISTINCT pdi.person_id) AS total
- FROM events e SAMPLE 1.0
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-11 23:59:59', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-18 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-11 23:59:59', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-18 23:59:59', 'UTC')
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_daily
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-19 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-08 00:00:00', 'UTC')), toDateTime('2020-01-19 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-08 00:00:00', 'UTC'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2020-01-19 23:59:59', 'UTC')) - toIntervalDay(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-19 23:59:59', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-19 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-19 23:59:59', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-08 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-19 23:59:59', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_daily_minus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-19 23:59:59', 'America/Phoenix')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-08 00:00:00', 'America/Phoenix')), toDateTime('2020-01-19 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-08 00:00:00', 'America/Phoenix'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2020-01-19 23:59:59', 'America/Phoenix')) - toIntervalDay(number), 'America/Phoenix') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'America/Phoenix')), toDateTime('2020-01-19 23:59:59', 'America/Phoenix')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-19 23:59:59', 'America/Phoenix'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-19 23:59:59', 'America/Phoenix')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfDay(toDateTime('2020-01-08 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-19 23:59:59', 'America/Phoenix'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_daily_plus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-19 23:59:59', 'Asia/Tokyo')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-08 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-19 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-08 00:00:00', 'Asia/Tokyo'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2020-01-19 23:59:59', 'Asia/Tokyo')) - toIntervalDay(number), 'Asia/Tokyo') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'Asia/Tokyo')), toDateTime('2020-01-19 23:59:59', 'Asia/Tokyo')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-19 23:59:59', 'Asia/Tokyo'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-01 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-19 23:59:59', 'Asia/Tokyo')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfDay(toDateTime('2020-01-08 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-19 23:59:59', 'Asia/Tokyo'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_filtering
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-12 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-25 00:00:00', 'UTC')), toDateTime('2020-01-12 23:59:59', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-25 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['person-1', 'person-2'], replaceRegexpAll(JSONExtractRaw(properties, 'name'), '^"|"$', ''))))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['person-1', 'person-2'], replaceRegexpAll(JSONExtractRaw(argMax(person.properties, version), 'name'), '^"|"$', ''))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-25 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_filtering_materialized
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) AS day_start
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), toDateTime('2020-01-12 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('day', toStartOfDay(toDateTime('2019-12-25 00:00:00', 'UTC')), toDateTime('2020-01-12 23:59:59', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-25 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- INNER JOIN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND id IN
- (SELECT id
- FROM person
- WHERE team_id = 99999
- AND (has(['person-1', 'person-2'], "pmat_name")))
- GROUP BY id
- HAVING max(is_deleted) = 0
- AND (has(['person-1', 'person-2'], argMax(person."pmat_name", version))) SETTINGS optimize_aggregation_in_order = 1) person ON person.id = pdi.person_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-25 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_hourly
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-09 17:00:00', 'UTC')) - toIntervalHour(number) AS day_start
- FROM numbers(dateDiff('hour', toStartOfHour(toDateTime('2020-01-09 06:00:00', 'UTC')), toDateTime('2020-01-09 17:00:00', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfHour(toDateTime('2020-01-09 06:00:00', 'UTC'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfHour(toDateTime('2020-01-09 17:00:00', 'UTC')) - toIntervalHour(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('hour', toStartOfHour(toDateTime('2020-01-02 06:00:00', 'UTC')), toDateTime('2020-01-09 17:00:00', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-02 06:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-09 17:00:00', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2020-01-02 06:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-09 17:00:00', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfHour(toDateTime('2020-01-09 06:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-09 17:00:00', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_monthly
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfMonth(toDateTime('2020-02-29 23:59:59', 'UTC')) - toIntervalMonth(number) AS day_start
- FROM numbers(dateDiff('month', toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'UTC')), toDateTime('2020-02-29 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'UTC'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfMonth(toDateTime('2020-02-29 23:59:59', 'UTC')) - toIntervalMonth(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('month', toStartOfMonth(toDateTime('2019-11-24 00:00:00', 'UTC')), toDateTime('2020-02-29 23:59:59', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-24 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-02-29 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-24 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-02-29 23:59:59', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-02-29 23:59:59', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_monthly_minus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfMonth(toDateTime('2020-02-29 23:59:59', 'America/Phoenix')) - toIntervalMonth(number) AS day_start
- FROM numbers(dateDiff('month', toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'America/Phoenix')), toDateTime('2020-02-29 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'America/Phoenix'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfMonth(toDateTime('2020-02-29 23:59:59', 'America/Phoenix')) - toIntervalMonth(number), 'America/Phoenix') AS timestamp
- FROM numbers(dateDiff('month', toStartOfMonth(toDateTime('2019-11-24 00:00:00', 'America/Phoenix')), toDateTime('2020-02-29 23:59:59', 'America/Phoenix')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-24 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-02-29 23:59:59', 'America/Phoenix'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-24 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-02-29 23:59:59', 'America/Phoenix')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'America/Phoenix')), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-02-29 23:59:59', 'America/Phoenix'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_monthly_plus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfMonth(toDateTime('2020-02-29 23:59:59', 'Asia/Tokyo')) - toIntervalMonth(number) AS day_start
- FROM numbers(dateDiff('month', toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'Asia/Tokyo')), toDateTime('2020-02-29 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'Asia/Tokyo'))
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfMonth(toDateTime('2020-02-29 23:59:59', 'Asia/Tokyo')) - toIntervalMonth(number), 'Asia/Tokyo') AS timestamp
- FROM numbers(dateDiff('month', toStartOfMonth(toDateTime('2019-11-24 00:00:00', 'Asia/Tokyo')), toDateTime('2020-02-29 23:59:59', 'Asia/Tokyo')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-24 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-02-29 23:59:59', 'Asia/Tokyo'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-11-24 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-02-29 23:59:59', 'Asia/Tokyo')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfMonth(toDateTime('2019-12-01 00:00:00', 'Asia/Tokyo')), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-02-29 23:59:59', 'Asia/Tokyo'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_weekly
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-18 23:59:59', 'UTC'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'UTC'), 0), toDateTime('2020-01-18 23:59:59', 'UTC')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'UTC'), 0)
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfWeek(toDateTime('2020-01-18 23:59:59', 'UTC'), 0) - toIntervalWeek(number), 'UTC') AS timestamp
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2019-12-22 00:00:00', 'UTC'), 0), toDateTime('2020-01-18 23:59:59', 'UTC')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-18 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-18 23:59:59', 'UTC')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'UTC'), 0), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-18 23:59:59', 'UTC'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_weekly_minus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-18 23:59:59', 'America/Phoenix'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'America/Phoenix'), 0), toDateTime('2020-01-18 23:59:59', 'America/Phoenix')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'America/Phoenix'), 0)
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfWeek(toDateTime('2020-01-18 23:59:59', 'America/Phoenix'), 0) - toIntervalWeek(number), 'America/Phoenix') AS timestamp
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2019-12-22 00:00:00', 'America/Phoenix'), 0), toDateTime('2020-01-18 23:59:59', 'America/Phoenix')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'America/Phoenix') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-18 23:59:59', 'America/Phoenix'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-18 23:59:59', 'America/Phoenix')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'America/Phoenix') >= toDateTime(toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'America/Phoenix'), 0), 'America/Phoenix')
- AND toTimeZone(timestamp, 'America/Phoenix') <= toDateTime('2020-01-18 23:59:59', 'America/Phoenix'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
-# name: TestTrends.test_weekly_active_users_weekly_plus_utc
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total
- FROM
- (SELECT SUM(total) AS count,
- day_start
- FROM
- (SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2020-01-18 23:59:59', 'Asia/Tokyo'), 0) - toIntervalWeek(number) AS day_start
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo'), 0), toDateTime('2020-01-18 23:59:59', 'Asia/Tokyo')))
- UNION ALL SELECT toUInt16(0) AS total,
- toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo'), 0)
- UNION ALL SELECT counts AS total,
- timestamp AS day_start
- FROM
- (SELECT d.timestamp,
- COUNT(DISTINCT actor_id) AS counts
- FROM
- (SELECT toDateTime(toStartOfWeek(toDateTime('2020-01-18 23:59:59', 'Asia/Tokyo'), 0) - toIntervalWeek(number), 'Asia/Tokyo') AS timestamp
- FROM numbers(dateDiff('week', toStartOfWeek(toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo'), 0), toDateTime('2020-01-18 23:59:59', 'Asia/Tokyo')))) d
- CROSS JOIN
- (SELECT toTimeZone(toDateTime(timestamp, 'UTC'), 'Asia/Tokyo') AS timestamp,
- pdi.person_id AS actor_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-18 23:59:59', 'Asia/Tokyo'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = '$pageview'
- AND toDateTime(timestamp, 'UTC') >= toDateTime('2019-12-22 00:00:00', 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-18 23:59:59', 'Asia/Tokyo')
- GROUP BY timestamp, actor_id) e
- WHERE e.timestamp <= d.timestamp + INTERVAL 1 DAY
- AND e.timestamp > d.timestamp - INTERVAL 6 DAY
- GROUP BY d.timestamp
- ORDER BY d.timestamp)
- WHERE 1 = 1
- AND toTimeZone(timestamp, 'Asia/Tokyo') >= toDateTime(toStartOfWeek(toDateTime('2019-12-29 00:00:00', 'Asia/Tokyo'), 0), 'Asia/Tokyo')
- AND toTimeZone(timestamp, 'Asia/Tokyo') <= toDateTime('2020-01-18 23:59:59', 'Asia/Tokyo'))
- GROUP BY day_start
- ORDER BY day_start)
- '''
-# ---
diff --git a/posthog/queries/test/test_lifecycle.py b/posthog/queries/test/test_lifecycle.py
deleted file mode 100644
index 2882741e1a5a..000000000000
--- a/posthog/queries/test/test_lifecycle.py
+++ /dev/null
@@ -1,943 +0,0 @@
-import json
-
-from freezegun import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_event,
- _create_person,
- snapshot_clickhouse_queries,
-)
-
-from posthog.constants import FILTER_TEST_ACCOUNTS, TRENDS_LIFECYCLE
-from posthog.models import Filter
-from posthog.models.filters.lifecycle_filter import LifecycleFilter
-from posthog.models.instance_setting import get_instance_setting
-from posthog.queries.trends.trends import Trends
-
-from products.actions.backend.models.action import Action
-
-
-def create_action(**kwargs):
- team = kwargs.pop("team")
- name = kwargs.pop("name")
- event_name = kwargs.pop("event_name")
- action = Action.objects.create(team=team, name=name, steps_json=[{"event": event_name}])
- return action
-
-
-class TestLifecycleBase(ClickhouseTestMixin, APIBaseTest):
- def assertLifecycleResults(self, results, expected):
- sorted_results = [
- {"status": r["status"], "data": r["data"]} for r in sorted(results, key=lambda r: r["status"])
- ]
- sorted_expected = sorted(expected, key=lambda r: r["status"])
-
- self.assertListEqual(sorted_results, sorted_expected)
-
-
-class TestLifecycle(TestLifecycleBase):
- def _create_events(self, data, event="$pageview"):
- person_result = []
- for id, timestamps in data:
- with freeze_time(timestamps[0]):
- person_result.append(
- _create_person(
- team_id=self.team.pk,
- distinct_ids=[id],
- properties={
- "name": id,
- **({"email": "[email protected]"} if id == "p1" else {}),
- },
- )
- )
- for timestamp in timestamps:
- _create_event(team=self.team, event=event, distinct_id=id, timestamp=timestamp)
- return person_result
-
- def test_lifecycle_trend(self):
- self._create_events(
- data=[
- (
- "p1",
- [
- "2020-01-11T12:00:00Z",
- "2020-01-12T12:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ]
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -2, -1, 0, -2, 0, -1, 0]},
- {"status": "new", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- def test_lifecycle_trend_any_event(self):
- self._create_events(
- event="$pageview",
- data=[
- (
- "p1",
- [
- "2020-01-11T12:00:00Z",
- "2020-01-12T12:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ],
- )
- self._create_events(
- event="$other",
- data=[
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ],
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": None, "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -2, -1, 0, -2, 0, -1, 0]},
- {"status": "new", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- def test_lifecycle_trend_with_zero_person_ids(self):
- # only a person-on-event test
- if not get_instance_setting("PERSON_ON_EVENTS_ENABLED"):
- return True
-
- self._create_events(
- data=[
- (
- "p1",
- [
- "2020-01-11T12:00:00Z",
- "2020-01-12T12:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ]
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p5",
- timestamp="2020-01-13T12:00:00Z",
- person_id="00000000-0000-0000-0000-000000000000",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p5",
- timestamp="2020-01-14T12:00:00Z",
- person_id="00000000-0000-0000-0000-000000000000",
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -2, -1, 0, -2, 0, -1, 0]},
- {"status": "new", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- def test_lifecycle_trend_prop_filtering(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"$number": 1},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-12T12:00:00Z",
- properties={"$number": 1},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-13T12:00:00Z",
- properties={"$number": 1},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-15T12:00:00Z",
- properties={"$number": 1},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-17T12:00:00Z",
- properties={"$number": 1},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-19T12:00:00Z",
- properties={"$number": 1},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-12T12:00:00Z",
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"name": "p3"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p3",
- timestamp="2020-01-12T12:00:00Z",
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p4"], properties={"name": "p4"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p4",
- timestamp="2020-01-15T12:00:00Z",
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- "properties": [{"key": "$number", "value": 1}],
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, 0, -1, 0, -1, 0, -1, 0]},
- {"status": "new", "data": [0, 0, 0, 0, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [0, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- #  entities filtering
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [
- {
- "properties": [{"key": "$number", "value": 1}],
- "id": "$pageview",
- "type": "events",
- "order": 0,
- }
- ],
- "shown_as": TRENDS_LIFECYCLE,
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, 0, -1, 0, -1, 0, -1, 0]},
- {"status": "new", "data": [0, 0, 0, 0, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [0, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- def test_lifecycle_trend_person_prop_filtering(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"$number": 1},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-12T12:00:00Z",
- properties={"$number": 1},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-13T12:00:00Z",
- properties={"$number": 1},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-15T12:00:00Z",
- properties={"$number": 1},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-17T12:00:00Z",
- properties={"$number": 1},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-19T12:00:00Z",
- properties={"$number": 1},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-12T12:00:00Z",
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"name": "p3"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p3",
- timestamp="2020-01-12T12:00:00Z",
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p4"], properties={"name": "p4"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p4",
- timestamp="2020-01-15T12:00:00Z",
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "properties": [{"key": "name", "value": "p1", "type": "person"}],
- }
- ],
- "shown_as": TRENDS_LIFECYCLE,
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, 0, -1, 0, -1, 0, -1, 0]},
- {"status": "new", "data": [0, 0, 0, 0, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [0, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- def test_lifecycle_trends_distinct_id_repeat(self):
- with freeze_time("2020-01-12T12:00:00Z"):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["p1", "another_p1"],
- properties={"name": "p1"},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-12T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="another_p1",
- timestamp="2020-01-14T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-15T12:00:00Z",
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-17T12:00:00Z",
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-19T12:00:00Z",
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -1, 0, 0, -1, 0, -1, 0]},
- {"status": "new", "data": [1, 0, 0, 0, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [0, 0, 1, 0, 0, 1, 0, 1]},
- {"status": "returning", "data": [0, 0, 0, 1, 0, 0, 0, 0]},
- ],
- )
-
- def test_lifecycle_trend_people(self):
- people = self._create_events(
- data=[
- (
- "p1",
- [
- "2020-01-11T12:00:00Z",
- "2020-01-12T12:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ]
- )
-
- p1 = people[0]
-
- result = self.client.get(
- "/api/person/lifecycle",
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": json.dumps([{"id": "$pageview", "type": "events", "order": 0}]),
- "shown_as": TRENDS_LIFECYCLE,
- "lifecycle_type": "returning",
- "target_date": "2020-01-13T00:00:00Z",
- },
- ).json()
-
- self.assertEqual(len(result["results"][0]["people"]), 1)
- self.assertEqual(result["results"][0]["people"][0]["uuid"], str(p1.uuid))
-
- dormant_result = self.client.get(
- "/api/person/lifecycle",
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": json.dumps([{"id": "$pageview", "type": "events", "order": 0}]),
- "shown_as": TRENDS_LIFECYCLE,
- "lifecycle_type": "dormant",
- "target_date": "2020-01-13T00:00:00Z",
- },
- ).json()
-
- self.assertEqual(len(dormant_result["results"][0]["people"]), 2)
-
- dormant_result = self.client.get(
- "/api/person/lifecycle",
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": json.dumps([{"id": "$pageview", "type": "events", "order": 0}]),
- "shown_as": TRENDS_LIFECYCLE,
- "lifecycle_type": "dormant",
- "target_date": "2020-01-14T00:00:00Z",
- },
- ).json()
-
- self.assertEqual(len(dormant_result["results"][0]["people"]), 1)
-
- def test_lifecycle_trend_people_paginated(self):
- with freeze_time("2020-01-15T12:00:00Z"):
- for i in range(150):
- person_id = "person{}".format(i)
- _create_person(team_id=self.team.pk, distinct_ids=[person_id])
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id=person_id,
- timestamp="2020-01-15T12:00:00Z",
- )
- # even if set to hour 6 it should default to beginning of day and include all pageviews above
- result = self.client.get(
- "/api/person/lifecycle",
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": json.dumps([{"id": "$pageview", "type": "events", "order": 0}]),
- "shown_as": TRENDS_LIFECYCLE,
- "lifecycle_type": "new",
- "target_date": "2020-01-15T00:00:00Z",
- },
- ).json()
- self.assertEqual(len(result["results"][0]["people"]), 100)
-
- second_result = self.client.get(result["next"]).json()
- self.assertEqual(len(second_result["results"][0]["people"]), 50)
-
- def test_lifecycle_trend_action(self):
- self._create_events(
- data=[
- (
- "p1",
- [
- "2020-01-11T12:00:00Z",
- "2020-01-12T12:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ]
- )
-
- pageview_action = create_action(team=self.team, name="$pageview", event_name="$pageview")
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "actions": [{"id": pageview_action.pk, "type": "actions", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -2, -1, 0, -2, 0, -1, 0]},
- {"status": "new", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- def test_lifecycle_trend_all_time(self):
- self._create_events(
- data=[
- (
- "p1",
- [
- "2020-01-11T12:00:00Z",
- "2020-01-12T12:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ]
- )
-
- with freeze_time("2020-01-17T13:01:01Z"):
- result = Trends().run(
- Filter(
- data={
- "date_from": "all",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -1, 0, 0, -2, -1, 0, -2, 0]},
- {"status": "new", "data": [1, 0, 1, 1, 0, 0, 1, 0, 0]},
- {"status": "returning", "data": [0, 0, 0, 1, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [0, 0, 0, 1, 0, 0, 1, 0, 1]},
- ],
- )
-
- def test_lifecycle_trend_weeks(self):
- # lifecycle weeks rounds the date to the nearest following week 2/5 -> 2/10
- self._create_events(
- data=[
- (
- "p1",
- [
- "2020-02-01T12:00:00Z",
- "2020-02-05T12:00:00Z",
- "2020-02-10T12:00:00Z",
- "2020-02-15T12:00:00Z",
- "2020-02-27T12:00:00Z",
- "2020-03-02T12:00:00Z",
- ],
- ),
- ("p2", ["2020-02-11T12:00:00Z", "2020-02-18T12:00:00Z"]),
- ("p3", ["2020-02-12T12:00:00Z"]),
- ("p4", ["2020-02-27T12:00:00Z"]),
- ]
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-02-05T00:00:00Z",
- "date_to": "2020-03-09T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- "interval": "week",
- }
- ),
- self.team,
- )
-
- self.assertEqual(
- result[0]["days"],
- [
- "2020-02-03",
- "2020-02-10",
- "2020-02-17",
- "2020-02-24",
- "2020-03-02",
- "2020-03-09",
- ],
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, 0, -2, -1, -1, -1]},
- {"status": "new", "data": [0, 2, 0, 1, 0, 0]},
- {"status": "resurrecting", "data": [0, 0, 0, 1, 0, 0]},
- {"status": "returning", "data": [1, 1, 1, 0, 1, 0]},
- ],
- )
-
- def test_lifecycle_trend_months(self):
- self._create_events(
- data=[
- (
- "p1",
- [
- "2020-01-11T12:00:00Z",
- "2020-02-12T12:00:00Z",
- "2020-03-13T12:00:00Z",
- "2020-05-15T12:00:00Z",
- "2020-07-17T12:00:00Z",
- "2020-09-19T12:00:00Z",
- ],
- ),
- ("p2", ["2019-12-09T12:00:00Z", "2020-02-12T12:00:00Z"]),
- ("p3", ["2020-02-12T12:00:00Z"]),
- ("p4", ["2020-05-15T12:00:00Z"]),
- ]
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-02-01T00:00:00Z",
- "date_to": "2020-09-01T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- "interval": "month",
- }
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -2, -1, 0, -2, 0, -1, 0]},
- {"status": "new", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- def test_filter_test_accounts(self):
- self._create_events(
- data=[
- (
- "p1", # p1 gets [email protected] as email and gets filtered out
- [
- "2020-01-11T12:00:00Z",
- "2020-01-12T12:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ]
- )
-
- result = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- FILTER_TEST_ACCOUNTS: True,
- },
- team=self.team,
- ),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -2, 0, 0, -1, 0, 0, 0]},
- {"status": "new", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 0, 0, 0, 0, 0, 0, 0]},
- {"status": "returning", "data": [0, 0, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- Trends().get_people(
- LifecycleFilter(
- data={
- "target_date": "2020-01-13T00:00:00Z",
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- FILTER_TEST_ACCOUNTS: True,
- "lifecycle_type": "dormant",
- },
- team=self.team,
- ),
- self.team,
- )
-
- @snapshot_clickhouse_queries
- def test_timezones(self):
- self._create_events(
- data=[
- (
- "p1",
- [
- "2020-01-11T23:00:00Z",
- "2020-01-12T01:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ]
- )
-
- filter_data = {
- "date_from": "2020-01-12",
- "date_to": "2020-01-19",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- }
- result = Trends().run(
- Filter(data=filter_data),
- self.team,
- )
-
- self.assertLifecycleResults(
- result,
- [
- {"status": "dormant", "data": [0, -2, -1, 0, -2, 0, -1, 0]},
- {"status": "new", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 0, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- self.team.timezone = "US/Pacific"
- self.team.save()
-
- result_pacific = Trends().run(
- Filter(data=filter_data),
- self.team,
- )
- self.assertLifecycleResults(
- result_pacific,
- [
- {
- "status": "dormant",
- "data": [-1.0, -2.0, -1.0, 0.0, -2.0, 0.0, -1.0, 0.0],
- },
- {"status": "new", "data": [1, 0, 0, 1, 0, 0, 0, 0]},
- {"status": "resurrecting", "data": [1, 1, 0, 1, 0, 1, 0, 1]},
- {"status": "returning", "data": [0, 0, 0, 0, 0, 0, 0, 0]},
- ],
- )
-
- # Ensure running the query with sampling works + generate a snapshot that shows sampling in the query
- @snapshot_clickhouse_queries
- def test_sampling(self):
- self._create_events(
- data=[
- (
- "p1",
- [
- "2020-01-11T12:00:00Z",
- "2020-01-12T12:00:00Z",
- "2020-01-13T12:00:00Z",
- "2020-01-15T12:00:00Z",
- "2020-01-17T12:00:00Z",
- "2020-01-19T12:00:00Z",
- ],
- ),
- ("p2", ["2020-01-09T12:00:00Z", "2020-01-12T12:00:00Z"]),
- ("p3", ["2020-01-12T12:00:00Z"]),
- ("p4", ["2020-01-15T12:00:00Z"]),
- ]
- )
-
- Trends().run(
- Filter(
- data={
- "date_from": "2020-01-12T00:00:00Z",
- "date_to": "2020-01-19T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "shown_as": TRENDS_LIFECYCLE,
- "sampling_factor": 0.1,
- }
- ),
- self.team,
- )
diff --git a/posthog/queries/test/test_trends.py b/posthog/queries/test/test_trends.py
deleted file mode 100644
index 3cb4622b9597..000000000000
--- a/posthog/queries/test/test_trends.py
+++ /dev/null
@@ -1,8871 +0,0 @@
-import json
-import uuid
-import dataclasses
-from datetime import datetime
-from typing import Optional, Union
-from urllib.parse import parse_qsl, urlparse
-from zoneinfo import ZoneInfo
-
-from freezegun import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_action,
- _create_event,
- _create_person,
- also_test_with_different_timezones,
- also_test_with_materialized_columns,
- also_test_with_person_on_events_v2,
- create_person_id_override_by_distinct_id,
- flush_persons_and_events,
- snapshot_clickhouse_queries,
-)
-from unittest.mock import ANY, patch
-
-from django.conf import settings
-from django.core.cache import cache
-from django.test import override_settings
-from django.utils import timezone
-
-from rest_framework.exceptions import ValidationError
-
-from posthog.constants import (
- ENTITY_ID,
- ENTITY_TYPE,
- TREND_FILTER_TYPE_EVENTS,
- TRENDS_BAR_VALUE,
- TRENDS_LINEAR,
- TRENDS_TABLE,
-)
-from posthog.models import Entity, Filter, Organization, Person
-from posthog.models.group.util import create_group
-from posthog.models.instance_setting import get_instance_setting, override_instance_config, set_instance_setting
-from posthog.models.person.util import create_person_distinct_id
-from posthog.models.utils import uuid7
-from posthog.queries.trends.breakdown import BREAKDOWN_OTHER_STRING_LABEL
-from posthog.queries.trends.trends import Trends
-from posthog.test.persons import create_person
-from posthog.test.test_journeys import journeys_for
-from posthog.test.test_utils import create_group_type_mapping_without_created_at
-from posthog.utils import generate_cache_key
-
-from products.actions.backend.models.action import Action
-from products.cohorts.backend.models.cohort import Cohort
-
-
-def breakdown_label(entity: Entity, value: Union[str, int]) -> dict[str, Optional[Union[str, int]]]:
- ret_dict: dict[str, Optional[Union[str, int]]] = {}
- if not value or not isinstance(value, str) or "cohort_" not in value:
- label = (
- value
- if (value or isinstance(value, bool)) and value != "None (i.e. no value)" and value != "nan"
- else "Other (i.e. all remaining values)"
- )
- ret_dict["label"] = f"{entity.name} - {label}"
- ret_dict["breakdown_value"] = label
- else:
- if value == "cohort_all":
- ret_dict["label"] = f"{entity.name} - all users"
- ret_dict["breakdown_value"] = "all"
- else:
- cohort = Cohort.objects.get(pk=value.replace("cohort_", ""))
- ret_dict["label"] = f"{entity.name} - {cohort.name}"
- ret_dict["breakdown_value"] = cohort.pk
- return ret_dict
-
-
-def _create_cohort(**kwargs):
- team = kwargs.pop("team")
- name = kwargs.pop("name")
- groups = kwargs.pop("groups")
- cohort = Cohort.objects.create(team=team, name=name, groups=groups, last_calculation=timezone.now())
- return cohort
-
-
-class TestTrends(ClickhouseTestMixin, APIBaseTest):
- maxDiff = None
-
- def _get_trend_people(self, filter: Filter, entity: Entity):
- data = filter.to_dict()
- # The test client doesn't serialize nested objects into JSON, so we need to do it ourselves
- if data.get("events", None):
- data["events"] = json.dumps(data["events"])
- if data.get("properties", None):
- data["properties"] = json.dumps(data["properties"])
- with self.settings(DEBUG=True):
- response = self.client.get(
- f"/api/projects/{self.team.id}/persons/trends/",
- data={**data, ENTITY_TYPE: entity.type, ENTITY_ID: entity.id},
- content_type="application/json",
- ).json()
- return response["results"][0]["people"]
-
- def _create_events(self, use_time=False) -> tuple[Action, Person]:
- person = _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _, _, secondTeam = Organization.objects.bootstrap(None, team_fields={"api_token": "token456"})
-
- freeze_without_time = ["2019-12-24", "2020-01-01", "2020-01-02"]
- freeze_with_time = [
- "2019-12-24 03:45:34",
- "2020-01-01 00:06:34",
- "2020-01-02 16:34:34",
- ]
-
- freeze_args = freeze_without_time
- if use_time:
- freeze_args = freeze_with_time
-
- with freeze_time(freeze_args[0]):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$bool_prop": True},
- )
-
- with freeze_time(freeze_args[1]):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$bool_prop": False},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="anonymous_id",
- properties={"$bool_prop": False},
- )
- _create_event(team=self.team, event="sign up", distinct_id="blabla")
- with freeze_time(freeze_args[2]):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$some_property": "other_value",
- "$some_numerical_prop": 80,
- },
- )
- _create_event(team=self.team, event="no events", distinct_id="blabla")
-
- # second team should have no effect
- _create_event(
- team=secondTeam,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "other_value"},
- )
-
- _create_action(team=self.team, name="no events")
- sign_up_action = _create_action(team=self.team, name="sign up")
-
- flush_persons_and_events()
-
- return sign_up_action, person
-
- def _create_breakdown_events(self, count=25):
- freeze_without_time = ["2020-01-02"]
-
- with freeze_time(freeze_without_time[0]):
- for i in range(count):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": i},
- )
- _create_action(team=self.team, name="sign up")
-
- def _create_event_count_per_actor_events(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"fruit": "mango"},
- )
- _create_person(team_id=self.team.pk, distinct_ids=["tintin"], properties={"fruit": "mango"})
- _create_person(team_id=self.team.pk, distinct_ids=["murmur"], properties={}) # No fruit here
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["reeree"],
- properties={"fruit": "tomato"},
- )
-
- with freeze_time("2020-01-01 00:06:02"):
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="anonymous_id",
- properties={"color": "red", "$group_0": "bouba"},
- )
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="blabla",
- properties={"$group_0": "bouba"},
- ) # No color here
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="reeree",
- properties={"color": "blue", "$group_0": "bouba"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="tintin",
- properties={"$group_0": "kiki"},
- )
-
- with freeze_time("2020-01-03 19:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="murmur",
- properties={"$group_0": "kiki"},
- )
-
- with freeze_time("2020-01-04 23:17:00"):
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="tintin",
- properties={"color": "red", "$group_0": "kiki"},
- )
-
- with freeze_time("2020-01-05 19:06:34"):
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="blabla",
- properties={"color": "blue", "$group_0": "bouba"},
- )
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="tintin",
- properties={"color": "red"},
- ) # No group here
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="tintin",
- properties={"color": "red", "$group_0": "bouba"},
- )
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="tintin",
- properties={"color": "blue", "$group_0": "kiki"},
- )
-
- def test_trends_per_day(self):
- self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
- # with self.assertNumQueries(16):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "events": [{"id": "sign up"}, {"id": "no events"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["label"], "sign up")
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 3.0)
- self.assertEqual(response[0]["labels"][5], "2-Jan-2020")
- self.assertEqual(response[0]["data"][5], 1.0)
-
- @snapshot_clickhouse_queries
- def test_trend_actors_person_on_events_pagination_with_alias_inconsistencies(self):
- test_person_ids = [ # 10 test person IDs (in UUIDT format), hard-coded for deterministic runs
- "016f70a4-1c68-0000-db29-61f63a926520",
- "016f70a4-1c68-0001-51a1-ad418c05e09f",
- "016f70a4-1c68-0002-9ea5-10186329258f",
- "016f70a4-1c68-0003-7680-697adb073c10",
- "016f70a4-1c68-0004-d0f8-7bd581c97eff",
- "016f70a4-1c68-0005-f593-e89d76db7a1f",
- "016f70a4-1c68-0006-bb84-d42937ef5989",
- "016f70a4-1c68-0007-923f-82720e97a6ba",
- "016f70a4-1c68-0008-8970-cbb33f01de1e",
- "016f70a4-1c68-0009-75a2-3755450b0b17",
- ]
-
- with freeze_time("2020-01-04T13:00:01Z"):
- all_distinct_ids = []
- for i, person_id in enumerate(test_person_ids):
- distinct_id = f"blabla_{i}"
- # UUIDT offers k-sortability, making this test effectively deterministic, as opposed to UUIDv4
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id=distinct_id,
- properties={"$some_property": "value", "$bool_prop": True},
- person_id=person_id, # Different person_ids, but in the end aliased to be the same person
- )
- all_distinct_ids.append(distinct_id)
-
- person = _create_person(
- team_id=self.team.pk,
- distinct_ids=all_distinct_ids,
- properties={"$some_prop": "some_val"},
- uuid=test_person_ids[-1],
- )
- flush_persons_and_events()
-
- data = {
- "date_from": "-7d",
- "events": [{"id": "sign up", "math": "dau"}],
- "limit": 5,
- }
-
- with override_instance_config("PERSON_ON_EVENTS_ENABLED", True):
- from posthog.models.team import util
-
- util.can_enable_actor_on_events = True # ty: ignore[invalid-assignment]
-
- response = Trends().run(Filter(team=self.team, data=data), self.team)
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.0])
-
- url = response[0]["persons_urls"][7]["url"]
- people_response = self.client.get(f"/{url}").json()
-
- # pagination works, no matter how few ids in people_response
- self.assertIsNotNone(people_response["next"])
- self.assertEqual(people_response["missing_persons"], 5)
-
- next_url = people_response["next"]
- second_people_response = self.client.get(f"{next_url}").json()
-
- self.assertIsNotNone(second_people_response["next"])
- self.assertEqual(second_people_response["missing_persons"], 4)
-
- first_load_ids = sorted(str(person["id"]) for person in people_response["results"][0]["people"])
- second_load_ids = sorted(str(person["id"]) for person in second_people_response["results"][0]["people"])
-
- self.assertEqual(len(first_load_ids + second_load_ids), 1)
- self.assertEqual(first_load_ids + second_load_ids, [str(person.uuid)])
-
- third_people_response = self.client.get(f"/{second_people_response['next']}").json()
- self.assertIsNone(third_people_response["next"])
- self.assertFalse(third_people_response["missing_persons"])
-
- third_load_ids = sorted(str(person["id"]) for person in third_people_response["results"][0]["people"])
- self.assertEqual(third_load_ids, [])
-
- # just make sure this doesn't error
- def test_no_props(self):
- with freeze_time("2020-01-04T13:01:01Z"):
- Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- },
- {"id": "no events"},
- ],
- },
- ),
- self.team,
- )
-
- def test_trends_per_day_48hours(self):
- self._create_events()
- with freeze_time("2020-01-03T13:00:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-48h",
- "interval": "day",
- "events": [{"id": "sign up"}, {"id": "no events"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["data"][1], 1.0)
- self.assertEqual(response[0]["labels"][1], "2-Jan-2020")
-
- @snapshot_clickhouse_queries
- def test_trends_per_day_cumulative(self):
- self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "display": "ActionsLineGraphCumulative",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["label"], "sign up")
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 3.0)
- self.assertEqual(response[0]["labels"][5], "2-Jan-2020")
- self.assertEqual(response[0]["data"][5], 4.0)
-
- @snapshot_clickhouse_queries
- def test_trends_groups_per_day_cumulative(self):
- self._create_event_count_per_actor_events()
- with freeze_time("2020-01-06T13:00:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "display": "ActionsLineGraphCumulative",
- "events": [
- {
- "id": "viewed video",
- "math": "unique_group",
- "math_group_type_index": 0,
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["label"], "viewed video")
- self.assertEqual(response[0]["labels"][-1], "6-Jan-2020")
- self.assertEqual(response[0]["data"], [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0])
-
- @also_test_with_person_on_events_v2
- @snapshot_clickhouse_queries
- def test_trends_breakdown_cumulative(self):
- self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "display": "ActionsLineGraphCumulative",
- "events": [{"id": "sign up", "math": "dau"}],
- "breakdown": "$some_property",
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["label"], "None (i.e. no value)")
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0])
-
- self.assertEqual(response[1]["label"], "other_value")
- self.assertEqual(response[1]["data"], [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0])
-
- self.assertEqual(response[2]["label"], "value")
- self.assertEqual(response[2]["data"], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0])
-
- def test_trends_single_aggregate_dau(self):
- self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "week",
- "events": [{"id": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "day",
- "events": [{"id": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(daily_response[0]["aggregated_value"], 1)
- self.assertEqual(
- daily_response[0]["aggregated_value"],
- weekly_response[0]["aggregated_value"],
- )
-
- @also_test_with_materialized_columns(["$math_prop"])
- def test_trends_single_aggregate_math(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- with freeze_time("2020-01-01 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$math_prop": 1},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$math_prop": 1},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$math_prop": 1},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$math_prop": 2},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$math_prop": 3},
- )
-
- with freeze_time("2020-01-02 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$math_prop": 4},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$math_prop": 4},
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "week",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$math_prop",
- }
- ],
- },
- ),
- self.team,
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "day",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$math_prop",
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(daily_response[0]["aggregated_value"], 2.0)
- self.assertEqual(
- daily_response[0]["aggregated_value"],
- weekly_response[0]["aggregated_value"],
- )
-
- @snapshot_clickhouse_queries
- def test_trends_with_session_property_single_aggregate_math(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla2"],
- properties={"$some_prop": "some_val"},
- )
-
- _create_event(
- team=self.team,
- event="sign up before",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:34",
- )
- _create_event(
- team=self.team,
- event="sign up later",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:35",
- )
- # First session lasted 5 seconds
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2},
- timestamp="2020-01-01 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2},
- timestamp="2020-01-01 00:06:45",
- )
- # Second session lasted 10 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 3},
- timestamp="2020-01-01 00:06:45",
- )
- # Third session lasted 0 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4},
- timestamp="2020-01-02 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4},
- timestamp="2020-01-02 00:06:45",
- )
- # Fourth session lasted 15 seconds
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "week",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "day",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(daily_response[0]["aggregated_value"], 7.5)
- self.assertEqual(
- daily_response[0]["aggregated_value"],
- weekly_response[0]["aggregated_value"],
- )
-
- def test_unique_session_with_session_breakdown(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla2"],
- properties={"$some_prop": "some_val"},
- )
-
- _create_event(
- team=self.team,
- event="sign up before",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:34",
- )
- _create_event(
- team=self.team,
- event="sign up later",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:35",
- )
- # First session lasted 5 seconds
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2},
- timestamp="2020-01-01 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2},
- timestamp="2020-01-01 00:06:45",
- )
- # Second session lasted 10 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 3},
- timestamp="2020-01-01 00:06:45",
- )
- # Third session lasted 0 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4},
- timestamp="2020-01-02 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4},
- timestamp="2020-01-02 00:06:45",
- )
- # Fourth session lasted 15 seconds
-
- with freeze_time("2020-01-04T13:00:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": "ActionsLineGraph",
- "interval": "day",
- "events": [{"id": "sign up", "math": "unique_session"}],
- "breakdown": "$session_duration",
- "breakdown_type": "session",
- "insight": "TRENDS",
- "breakdown_histogram_bin_count": 3,
- "properties": [{"key": "$some_prop", "value": "some_val", "type": "person"}],
- "date_from": "-3d",
- },
- ),
- self.team,
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- ("[0.0,4.95]", 1.0, [1.0, 0.0, 0.0, 0.0]),
- ("[4.95,10.05]", 2.0, [2.0, 0.0, 0.0, 0.0]),
- ("[10.05,15.01]", 1.0, [0.0, 1.0, 0.0, 0.0]),
- ],
- )
-
- @also_test_with_person_on_events_v2
- @also_test_with_materialized_columns(person_properties=["name"], verify_no_jsonextract=False)
- def test_trends_breakdown_single_aggregate_cohorts(self):
- _create_person(team_id=self.team.pk, distinct_ids=["Jane"], properties={"name": "Jane"})
- _create_person(team_id=self.team.pk, distinct_ids=["John"], properties={"name": "John"})
- _create_person(team_id=self.team.pk, distinct_ids=["Jill"], properties={"name": "Jill"})
- cohort1 = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "Jane", "type": "person"}]}],
- )
- cohort2 = _create_cohort(
- team=self.team,
- name="cohort2",
- groups=[{"properties": [{"key": "name", "value": "John", "type": "person"}]}],
- )
- cohort3 = _create_cohort(
- team=self.team,
- name="cohort3",
- groups=[{"properties": [{"key": "name", "value": "Jill", "type": "person"}]}],
- )
- with freeze_time("2020-01-01 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="John",
- properties={"$some_property": "value", "$browser": "Chrome"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="John",
- properties={"$some_property": "value", "$browser": "Chrome"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="Jill",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="Jill",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="Jill",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
-
- with freeze_time("2020-01-02 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="Jane",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="Jane",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- with freeze_time("2020-01-04T13:00:01Z"):
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "breakdown": json.dumps([cohort1.pk, cohort2.pk, cohort3.pk, "all"]),
- "breakdown_type": "cohort",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
-
- for result in event_response:
- if result["label"] == "cohort1":
- self.assertEqual(result["aggregated_value"], 2)
- elif result["label"] == "cohort2":
- self.assertEqual(result["aggregated_value"], 2)
- elif result["label"] == "cohort3":
- self.assertEqual(result["aggregated_value"], 3)
- else:
- self.assertEqual(result["label"], "all users")
- self.assertEqual(result["aggregated_value"], 7)
-
- def test_trends_breakdown_single_aggregate(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- with freeze_time("2020-01-01 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Chrome"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Chrome"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
-
- with freeze_time("2020-01-02 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "breakdown": "$browser",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
-
- for result in daily_response:
- if result["breakdown_value"] == "Chrome":
- self.assertEqual(result["aggregated_value"], 2)
- else:
- self.assertEqual(result["aggregated_value"], 5)
-
- def test_trends_breakdown_single_aggregate_with_zero_person_ids(self):
- # only a person-on-event test
- if not get_instance_setting("PERSON_ON_EVENTS_ENABLED"):
- return True
-
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- with freeze_time("2020-01-01 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Chrome"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Chrome"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$some_property": "value", "$browser": "Chrome"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$some_property": "value", "$browser": "Safari"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla3",
- properties={"$some_property": "value", "$browser": "xyz"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
-
- with freeze_time("2020-01-02 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$browser": "Safari"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla4",
- properties={"$some_property": "value", "$browser": "Chrome"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$some_property": "value", "$browser": "urgh"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "breakdown": "$browser",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
-
- for result in daily_response:
- if result["breakdown_value"] == "Chrome":
- self.assertEqual(result["aggregated_value"], 2)
- else:
- self.assertEqual(result["aggregated_value"], 5)
-
- def test_trends_breakdown_single_aggregate_math(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- with freeze_time("2020-01-01 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$math_prop": 1},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$math_prop": 1},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$math_prop": 1},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$math_prop": 2},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$math_prop": 3},
- )
-
- with freeze_time("2020-01-02 00:06:34"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$math_prop": 4},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value", "$math_prop": 4},
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "day",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$math_prop",
- }
- ],
- },
- ),
- self.team,
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "week",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$math_prop",
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(daily_response[0]["aggregated_value"], 2.0)
- self.assertEqual(
- daily_response[0]["aggregated_value"],
- weekly_response[0]["aggregated_value"],
- )
-
- @snapshot_clickhouse_queries
- def test_trends_breakdown_with_session_property_single_aggregate_math_and_breakdown(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla2"],
- properties={"$some_prop": "some_val"},
- )
-
- _create_event(
- team=self.team,
- event="sign up before",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:34",
- )
- _create_event(
- team=self.team,
- event="sign up later",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value doesnt matter"},
- timestamp="2020-01-01 00:06:35",
- )
- # First session lasted 5 seconds
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2, "$some_property": "value2"},
- timestamp="2020-01-01 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:45",
- )
- # Second session lasted 10 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 3},
- timestamp="2020-01-01 00:06:45",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 3},
- timestamp="2020-01-01 00:06:46",
- )
- # Third session lasted 1 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4, "$some_property": "value2"},
- timestamp="2020-01-02 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4, "$some_property": "value2"},
- timestamp="2020-01-02 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4, "$some_property": "value1"},
- timestamp="2020-01-02 00:06:45",
- )
- # Fourth session lasted 15 seconds
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "week",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- # value1 has: 5 seconds, 10 seconds, 15 seconds
- # value2 has: 10 seconds, 15 seconds (aggregated by session, so 15 is not double counted)
- # empty has: 1 seconds
- self.assertEqual(
- [resp["breakdown_value"] for resp in daily_response],
- ["value2", "value1", "$$_posthog_breakdown_null_$$"],
- )
- self.assertEqual([resp["aggregated_value"] for resp in daily_response], [12.5, 10, 1])
-
- with freeze_time("2020-01-04T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "day",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(
- [resp["breakdown_value"] for resp in daily_response],
- [resp["breakdown_value"] for resp in weekly_response],
- )
- self.assertEqual(
- [resp["aggregated_value"] for resp in daily_response],
- [resp["aggregated_value"] for resp in weekly_response],
- )
-
- @snapshot_clickhouse_queries
- def test_trends_person_breakdown_with_session_property_single_aggregate_math_and_breakdown(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla2"],
- properties={"$some_prop": "another_val"},
- )
-
- _create_event(
- team=self.team,
- event="sign up before",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:34",
- )
- _create_event(
- team=self.team,
- event="sign up later",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value doesnt matter"},
- timestamp="2020-01-01 00:06:35",
- )
- # First session lasted 5 seconds
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2, "$some_property": "value2"},
- timestamp="2020-01-01 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:45",
- )
- # Second session lasted 10 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 3},
- timestamp="2020-01-01 00:06:45",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 3},
- timestamp="2020-01-01 00:06:46",
- )
- # Third session lasted 1 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4, "$some_property": "value2"},
- timestamp="2020-01-02 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4, "$some_property": "value2"},
- timestamp="2020-01-02 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4, "$some_property": "value1"},
- timestamp="2020-01-02 00:06:45",
- )
- # Fourth session lasted 15 seconds
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "week",
- "breakdown": "$some_prop",
- "breakdown_type": "person",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- # another_val has: 10 seconds
- # some_val has: 1, 5 seconds, 15 seconds
- self.assertEqual(
- [resp["breakdown_value"] for resp in daily_response],
- ["another_val", "some_val"],
- )
- self.assertEqual([resp["aggregated_value"] for resp in daily_response], [10.0, 5.0])
-
- @snapshot_clickhouse_queries
- def test_trends_any_event_total_count(self):
- self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
- response1 = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "interval": "day",
- "events": [{"id": None, "math": "total"}],
- },
- ),
- self.team,
- )
- response2 = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "interval": "day",
- "events": [{"id": "sign up", "math": "total"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response1[0]["count"], 5)
- self.assertEqual(response2[0]["count"], 4)
-
- @also_test_with_materialized_columns(["$math_prop", "$some_property"])
- def test_trends_breakdown_with_math_func(self):
- with freeze_time("2020-01-01 00:06:34"):
- for i in range(20):
- _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id=f"person{i}",
- properties={"$some_property": f"value_{i}", "$math_prop": 1},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id=f"person{i}",
- properties={"$some_property": f"value_{i}", "$math_prop": 1},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=[f"person21"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id=f"person21",
- properties={"$some_property": "value_21", "$math_prop": 25},
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "interval": "day",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "math": "p90",
- "math_property": "$math_prop",
- }
- ],
- },
- ),
- self.team,
- )
-
- breakdown_vals = [val["breakdown_value"] for val in daily_response]
- self.assertTrue("value_21" in breakdown_vals)
-
- @snapshot_clickhouse_queries
- def test_trends_compare_day_interval_relative_range(self):
- self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "compare": "true",
- "date_from": "-7d",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["label"], "sign up")
- self.assertEqual(response[0]["labels"][4], "day 4")
- self.assertEqual(response[0]["data"][4], 3.0)
- self.assertEqual(response[0]["labels"][5], "day 5")
- self.assertEqual(response[0]["data"][5], 1.0)
- self.assertEqual(
- response[0]["days"],
- [
- "2019-12-28", # -7d, current period
- "2019-12-29", # -6d, current period
- "2019-12-30", # -5d, current period
- "2019-12-31", # -4d, current period
- "2020-01-01", # -3d, current period
- "2020-01-02", # -2d, current period
- "2020-01-03", # -1d, current period
- "2020-01-04", # -0d, current period (this one's ongoing!)
- ],
- )
-
- self.assertEqual(
- response[1]["days"],
- [
- "2019-12-21", # -7d, previous period
- "2019-12-22", # -6d, previous period
- "2019-12-23", # -5d, previous period
- "2019-12-24", # -4d, previous period
- "2019-12-25", # -3d, previous period
- "2019-12-26", # -2d, previous period
- "2019-12-27", # -1d, previous period
- "2019-12-28", # -0d, previous period
- ],
- )
- self.assertEqual(response[1]["label"], "sign up")
- self.assertEqual(response[1]["labels"][3], "day 3")
- self.assertEqual(response[1]["data"][3], 1.0)
- self.assertEqual(response[1]["labels"][4], "day 4")
- self.assertEqual(response[1]["data"][4], 0.0)
-
- with freeze_time("2020-01-04T13:00:01Z"):
- no_compare_response = Trends().run(
- Filter(
- team=self.team,
- data={"compare": "false", "events": [{"id": "sign up"}]},
- ),
- self.team,
- )
-
- self.assertEqual(no_compare_response[0]["label"], "sign up")
- self.assertEqual(no_compare_response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(no_compare_response[0]["data"][4], 3.0)
- self.assertEqual(no_compare_response[0]["labels"][5], "2-Jan-2020")
- self.assertEqual(no_compare_response[0]["data"][5], 1.0)
-
- def test_trends_compare_day_interval_fixed_range_single(self):
- self._create_events(use_time=True)
- with freeze_time("2020-01-02T20:17:00Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "compare": "true",
- # A fixed single-day range requires different handling than a relative range like -7d
- "date_from": "2020-01-02",
- "interval": "day",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(
- response[0]["days"],
- [
- "2020-01-02", # Current day
- ],
- )
- self.assertEqual(
- response[0]["data"],
- [1],
- )
- self.assertEqual(
- response[1]["days"],
- [
- "2020-01-01", # Previous day
- ],
- )
- self.assertEqual(
- response[1]["data"],
- [
- 3,
- ],
- )
-
- def test_trends_compare_hour_interval_relative_range(self):
- self._create_events(use_time=True)
- with freeze_time("2020-01-02T20:17:00Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "compare": "true",
- "date_from": "dStart",
- "interval": "hour",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(
- response[0]["days"],
- [
- "2020-01-02 00:00:00",
- "2020-01-02 01:00:00",
- "2020-01-02 02:00:00",
- "2020-01-02 03:00:00",
- "2020-01-02 04:00:00",
- "2020-01-02 05:00:00",
- "2020-01-02 06:00:00",
- "2020-01-02 07:00:00",
- "2020-01-02 08:00:00",
- "2020-01-02 09:00:00",
- "2020-01-02 10:00:00",
- "2020-01-02 11:00:00",
- "2020-01-02 12:00:00",
- "2020-01-02 13:00:00",
- "2020-01-02 14:00:00",
- "2020-01-02 15:00:00",
- "2020-01-02 16:00:00",
- "2020-01-02 17:00:00",
- "2020-01-02 18:00:00",
- "2020-01-02 19:00:00",
- "2020-01-02 20:00:00",
- ],
- )
- self.assertEqual(
- response[0]["data"],
- [
- 0, # 00:00
- 0, # 01:00
- 0, # 02:00
- 0, # 03:00
- 0, # 04:00
- 0, # 05:00
- 0, # 06:00
- 0, # 07:00
- 0, # 08:00
- 0, # 09:00
- 0, # 10:00
- 0, # 11:00
- 0, # 12:00
- 0, # 13:00
- 0, # 14:00
- 0, # 15:00
- 1, # 16:00
- 0, # 17:00
- 0, # 18:00
- 0, # 19:00
- 0, # 20:00
- ],
- )
- self.assertEqual(
- response[1]["days"],
- [
- "2020-01-01 00:00:00",
- "2020-01-01 01:00:00",
- "2020-01-01 02:00:00",
- "2020-01-01 03:00:00",
- "2020-01-01 04:00:00",
- "2020-01-01 05:00:00",
- "2020-01-01 06:00:00",
- "2020-01-01 07:00:00",
- "2020-01-01 08:00:00",
- "2020-01-01 09:00:00",
- "2020-01-01 10:00:00",
- "2020-01-01 11:00:00",
- "2020-01-01 12:00:00",
- "2020-01-01 13:00:00",
- "2020-01-01 14:00:00",
- "2020-01-01 15:00:00",
- "2020-01-01 16:00:00",
- "2020-01-01 17:00:00",
- "2020-01-01 18:00:00",
- "2020-01-01 19:00:00",
- "2020-01-01 20:00:00",
- ],
- )
- self.assertEqual(
- response[1]["data"],
- [
- 3, # 00:00
- 0, # 01:00
- 0, # 02:00
- 0, # 03:00
- 0, # 04:00
- 0, # 05:00
- 0, # 06:00
- 0, # 07:00
- 0, # 08:00
- 0, # 09:00
- 0, # 10:00
- 0, # 11:00
- 0, # 12:00
- 0, # 13:00
- 0, # 14:00
- 0, # 15:00
- 0, # 16:00
- 0, # 17:00
- 0, # 18:00
- 0, # 19:00
- 0, # 20:00
- ],
- )
-
- def _test_events_with_dates(self, dates: list[str], result, query_time=None, **filter_params):
- _create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})
- for time in dates:
- with freeze_time(time):
- _create_event(
- event="event_name",
- team=self.team,
- distinct_id="person_1",
- properties={"$browser": "Safari"},
- )
-
- if query_time:
- with freeze_time(query_time):
- response = Trends().run(
- Filter(
- team=self.team,
- data={**filter_params, "events": [{"id": "event_name"}]},
- ),
- self.team,
- )
- else:
- response = Trends().run(
- Filter(
- team=self.team,
- data={**filter_params, "events": [{"id": "event_name"}]},
- ),
- self.team,
- )
-
- self.assertEqual(result[0]["count"], response[0]["count"])
- self.assertEqual(result[0]["labels"], response[0]["labels"])
- self.assertEqual(result[0]["data"], response[0]["data"])
- self.assertEqual(result[0]["days"], response[0]["days"])
-
- return response
-
- def test_hour_interval(self):
- response = self._test_events_with_dates(
- dates=["2020-11-01 13:00:00", "2020-11-01 13:20:00", "2020-11-01 17:00:00"],
- interval="hour",
- date_from="2020-11-01 12:00:00",
- query_time="2020-11-01 23:00:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 3.0,
- "data": [0.0, 2.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0, 0, 0, 0, 0],
- "labels": [
- "1-Nov-2020 12:00",
- "1-Nov-2020 13:00",
- "1-Nov-2020 14:00",
- "1-Nov-2020 15:00",
- "1-Nov-2020 16:00",
- "1-Nov-2020 17:00",
- "1-Nov-2020 18:00",
- "1-Nov-2020 19:00",
- "1-Nov-2020 20:00",
- "1-Nov-2020 21:00",
- "1-Nov-2020 22:00",
- "1-Nov-2020 23:00",
- ],
- "days": [
- "2020-11-01 12:00:00",
- "2020-11-01 13:00:00",
- "2020-11-01 14:00:00",
- "2020-11-01 15:00:00",
- "2020-11-01 16:00:00",
- "2020-11-01 17:00:00",
- "2020-11-01 18:00:00",
- "2020-11-01 19:00:00",
- "2020-11-01 20:00:00",
- "2020-11-01 21:00:00",
- "2020-11-01 22:00:00",
- "2020-11-01 23:00:00",
- ],
- }
- ],
- )
- self.assertEqual(
- {
- "date_from": datetime(2020, 11, 1, 12, tzinfo=ZoneInfo("UTC")),
- "date_to": datetime(2020, 11, 1, 13, tzinfo=ZoneInfo("UTC")),
- "entity_id": "event_name",
- "entity_math": None,
- "entity_order": None,
- "entity_type": "events",
- },
- response[0]["persons_urls"][0]["filter"],
- )
-
- def test_day_interval(self):
- response = self._test_events_with_dates(
- dates=["2020-11-01", "2020-11-02", "2020-11-03", "2020-11-04"],
- interval="day",
- date_from="2020-11-01",
- date_to="2020-11-07",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 4.0,
- "data": [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],
- "labels": [
- "1-Nov-2020",
- "2-Nov-2020",
- "3-Nov-2020",
- "4-Nov-2020",
- "5-Nov-2020",
- "6-Nov-2020",
- "7-Nov-2020",
- ],
- "days": [
- "2020-11-01",
- "2020-11-02",
- "2020-11-03",
- "2020-11-04",
- "2020-11-05",
- "2020-11-06",
- "2020-11-07",
- ],
- }
- ],
- )
- self.assertEqual(
- {
- "date_from": datetime(2020, 11, 1, tzinfo=ZoneInfo("UTC")),
- "date_to": datetime(2020, 11, 1, 23, 59, 59, 999999, tzinfo=ZoneInfo("UTC")),
- "entity_id": "event_name",
- "entity_math": None,
- "entity_order": None,
- "entity_type": "events",
- },
- response[0]["persons_urls"][0]["filter"],
- )
-
- def test_week_interval(self):
- self._test_events_with_dates(
- dates=["2020-11-01", "2020-11-10", "2020-11-11", "2020-11-18"],
- interval="week",
- date_from="2020-10-29", # having date after sunday + no events caused an issue in CH
- date_to="2020-11-24",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 4.0,
- "data": [0.0, 1.0, 2.0, 1.0, 0.0],
- "labels": [
- "25-Oct-2020",
- "1-Nov-2020",
- "8-Nov-2020",
- "15-Nov-2020",
- "22-Nov-2020",
- ],
- "days": [
- "2020-10-25",
- "2020-11-01",
- "2020-11-08",
- "2020-11-15",
- "2020-11-22",
- ],
- }
- ],
- )
-
- def test_month_interval(self):
- self._test_events_with_dates(
- dates=["2020-07-10", "2020-07-30", "2020-10-18"],
- interval="month",
- date_from="2020-6-01",
- date_to="2020-11-24",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 3.0,
- "data": [0.0, 2.0, 0.0, 0.0, 1.0, 0.0],
- "labels": [
- "1-Jun-2020",
- "1-Jul-2020",
- "1-Aug-2020",
- "1-Sep-2020",
- "1-Oct-2020",
- "1-Nov-2020",
- ],
- "days": [
- "2020-06-01",
- "2020-07-01",
- "2020-08-01",
- "2020-09-01",
- "2020-10-01",
- "2020-11-01",
- ],
- }
- ],
- )
-
- def test_interval_rounding(self):
- self._test_events_with_dates(
- dates=["2020-11-01", "2020-11-10", "2020-11-11", "2020-11-18"],
- interval="week",
- date_from="2020-11-04",
- date_to="2020-11-24",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 4.0,
- "data": [1.0, 2.0, 1.0, 0.0],
- "labels": [
- "1-Nov-2020",
- "8-Nov-2020",
- "15-Nov-2020",
- "22-Nov-2020",
- ],
- "days": ["2020-11-01", "2020-11-08", "2020-11-15", "2020-11-22"],
- }
- ],
- )
-
- def test_interval_rounding_monthly(self):
- self._test_events_with_dates(
- dates=["2020-06-2", "2020-07-30"],
- interval="month",
- date_from="2020-6-7", # should round down to 6-1
- date_to="2020-7-30",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 2.0,
- "data": [1.0, 1.0],
- "labels": ["1-Jun-2020", "1-Jul-2020"],
- "days": ["2020-06-01", "2020-07-01"],
- }
- ],
- )
-
- def test_today_timerange(self):
- self._test_events_with_dates(
- dates=["2020-11-01 10:20:00", "2020-11-01 10:22:00", "2020-11-01 10:25:00"],
- date_from="dStart",
- query_time="2020-11-01 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 3,
- "data": [3],
- "labels": ["1-Nov-2020"],
- "days": ["2020-11-01"],
- }
- ],
- )
-
- def test_yesterday_timerange(self):
- self._test_events_with_dates(
- dates=["2020-11-01 05:20:00", "2020-11-01 10:22:00", "2020-11-01 10:25:00"],
- date_from="-1d",
- date_to="-1d",
- query_time="2020-11-02 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 3.0,
- "data": [3.0],
- "labels": ["1-Nov-2020"],
- "days": ["2020-11-01"],
- }
- ],
- )
-
- def test_last24hours_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-11-01 05:20:00",
- "2020-11-01 10:22:00",
- "2020-11-01 10:25:00",
- "2020-11-02 08:25:00",
- ],
- date_from="-24h",
- query_time="2020-11-02 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 3,
- "data": [2, 1],
- "labels": ["1-Nov-2020", "2-Nov-2020"],
- "days": ["2020-11-01", "2020-11-02"],
- }
- ],
- )
-
- def test_last48hours_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-11-01 05:20:00",
- "2020-11-01 10:22:00",
- "2020-11-01 10:25:00",
- "2020-11-02 08:25:00",
- ],
- date_from="-48h",
- query_time="2020-11-02 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 4.0,
- "data": [0.0, 3.0, 1.0],
- "labels": ["31-Oct-2020", "1-Nov-2020", "2-Nov-2020"],
- "days": ["2020-10-31", "2020-11-01", "2020-11-02"],
- }
- ],
- )
-
- def test_last7days_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-11-01 05:20:00",
- "2020-11-02 10:22:00",
- "2020-11-04 10:25:00",
- "2020-11-05 08:25:00",
- ],
- date_from="-7d",
- query_time="2020-11-07 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 4.0,
- "data": [0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0],
- "labels": [
- "31-Oct-2020",
- "1-Nov-2020",
- "2-Nov-2020",
- "3-Nov-2020",
- "4-Nov-2020",
- "5-Nov-2020",
- "6-Nov-2020",
- "7-Nov-2020",
- ],
- "days": [
- "2020-10-31",
- "2020-11-01",
- "2020-11-02",
- "2020-11-03",
- "2020-11-04",
- "2020-11-05",
- "2020-11-06",
- "2020-11-07",
- ],
- }
- ],
- )
-
- def test_last14days_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-11-01 05:20:00",
- "2020-11-02 10:22:00",
- "2020-11-04 10:25:00",
- "2020-11-05 08:25:00",
- "2020-11-05 08:25:00",
- "2020-11-10 08:25:00",
- ],
- date_from="-14d",
- query_time="2020-11-14 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 6.0,
- "data": [
- 0.0,
- 1.0,
- 1.0,
- 0.0,
- 1.0,
- 2.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- 1.0,
- 0.0,
- 0.0,
- 0.0,
- 0.0,
- ],
- "labels": [
- "31-Oct-2020",
- "1-Nov-2020",
- "2-Nov-2020",
- "3-Nov-2020",
- "4-Nov-2020",
- "5-Nov-2020",
- "6-Nov-2020",
- "7-Nov-2020",
- "8-Nov-2020",
- "9-Nov-2020",
- "10-Nov-2020",
- "11-Nov-2020",
- "12-Nov-2020",
- "13-Nov-2020",
- "14-Nov-2020",
- ],
- "days": [
- "2020-10-31",
- "2020-11-01",
- "2020-11-02",
- "2020-11-03",
- "2020-11-04",
- "2020-11-05",
- "2020-11-06",
- "2020-11-07",
- "2020-11-08",
- "2020-11-09",
- "2020-11-10",
- "2020-11-11",
- "2020-11-12",
- "2020-11-13",
- "2020-11-14",
- ],
- }
- ],
- )
-
- def test_last30days_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-11-01 05:20:00",
- "2020-11-11 10:22:00",
- "2020-11-24 10:25:00",
- "2020-11-05 08:25:00",
- "2020-11-05 08:25:00",
- "2020-11-10 08:25:00",
- ],
- date_from="-30d",
- interval="week",
- query_time="2020-11-30 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 6.0,
- "data": [0.0, 3.0, 2.0, 0.0, 1.0, 0.0],
- "labels": [
- "25-Oct-2020",
- "1-Nov-2020",
- "8-Nov-2020",
- "15-Nov-2020",
- "22-Nov-2020",
- "29-Nov-2020",
- ],
- "days": [
- "2020-10-25",
- "2020-11-01",
- "2020-11-08",
- "2020-11-15",
- "2020-11-22",
- "2020-11-29",
- ],
- }
- ],
- )
-
- def test_last90days_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-09-01 05:20:00",
- "2020-10-05 05:20:00",
- "2020-10-20 05:20:00",
- "2020-11-01 05:20:00",
- "2020-11-11 10:22:00",
- "2020-11-24 10:25:00",
- "2020-11-05 08:25:00",
- "2020-11-05 08:25:00",
- "2020-11-10 08:25:00",
- ],
- date_from="-90d",
- interval="month",
- query_time="2020-11-30 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 9,
- "data": [1, 2, 6],
- "labels": ["1-Sep-2020", "1-Oct-2020", "1-Nov-2020"],
- "days": ["2020-09-01", "2020-10-01", "2020-11-01"],
- }
- ],
- )
-
- def test_this_month_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-11-01 05:20:00",
- "2020-11-11 10:22:00",
- "2020-11-24 10:25:00",
- "2020-11-05 08:25:00",
- "2020-11-05 08:25:00",
- "2020-11-10 08:25:00",
- ],
- date_from="mStart",
- interval="month",
- query_time="2020-11-30 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 6,
- "data": [6],
- "labels": ["1-Nov-2020"],
- "days": ["2020-11-01"],
- }
- ],
- )
-
- def test_previous_month_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-11-01 05:20:00",
- "2020-11-11 10:22:00",
- "2020-11-24 10:25:00",
- "2020-11-05 08:25:00",
- "2020-11-05 08:25:00",
- "2020-11-10 08:25:00",
- ],
- date_from="-1mStart",
- date_to="-1mEnd",
- interval="month",
- query_time="2020-12-30 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 6,
- "data": [6],
- "labels": ["1-Nov-2020"],
- "days": ["2020-11-01"],
- }
- ],
- )
-
- def test_year_to_date_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-01-01 05:20:00",
- "2020-01-11 10:22:00",
- "2020-02-24 10:25:00",
- "2020-02-05 08:25:00",
- "2020-03-05 08:25:00",
- "2020-05-10 08:25:00",
- ],
- date_from="yStart",
- interval="month",
- query_time="2020-04-30 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 5.0,
- "data": [2.0, 2.0, 1.0, 0.0],
- "labels": ["1-Jan-2020", "1-Feb-2020", "1-Mar-2020", "1-Apr-2020"],
- "days": ["2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01"],
- }
- ],
- )
-
- def test_all_time_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-01-01 05:20:00",
- "2020-01-11 10:22:00",
- "2020-02-24 10:25:00",
- "2020-02-05 08:25:00",
- "2020-03-05 08:25:00",
- ],
- date_from="all",
- interval="month",
- query_time="2020-04-30 10:20:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 5.0,
- "data": [2.0, 2.0, 1.0, 0.0],
- "labels": ["1-Jan-2020", "1-Feb-2020", "1-Mar-2020", "1-Apr-2020"],
- "days": ["2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01"],
- }
- ],
- )
-
- def test_custom_range_timerange(self):
- self._test_events_with_dates(
- dates=[
- "2020-01-05 05:20:00",
- "2020-01-05 10:22:00",
- "2020-01-04 10:25:00",
- "2020-01-11 08:25:00",
- "2020-01-09 08:25:00",
- ],
- date_from="2020-01-05",
- query_time="2020-01-10",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 3.0,
- "data": [2.0, 0.0, 0.0, 0.0, 1.0, 0.0],
- "labels": [
- "5-Jan-2020",
- "6-Jan-2020",
- "7-Jan-2020",
- "8-Jan-2020",
- "9-Jan-2020",
- "10-Jan-2020",
- ],
- "days": [
- "2020-01-05",
- "2020-01-06",
- "2020-01-07",
- "2020-01-08",
- "2020-01-09",
- "2020-01-10",
- ],
- }
- ],
- )
-
- @also_test_with_materialized_columns(["$some_property"])
- def test_property_filtering(self):
- self._create_events()
- with freeze_time("2020-01-04"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "properties": [{"key": "$some_property", "value": "value"}],
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 1.0)
- self.assertEqual(response[0]["labels"][5], "2-Jan-2020")
- self.assertEqual(response[0]["data"][5], 0)
-
- @snapshot_clickhouse_queries
- def test_trends_with_hogql_math(self):
- s1 = str(uuid7("2020-01-01", 1))
- s5 = str(uuid7("2020-01-01", 5))
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val", "number": 8},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": s1, "x": 1},
- timestamp="2020-01-01 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": s5, "x": 5},
- timestamp="2020-01-02 00:06:45",
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "week",
- "events": [
- {
- "id": "sign up",
- "math": "hogql",
- "math_hogql": "avg(toInt(properties.x)) + 1000",
- }
- ],
- },
- ),
- self.team,
- )
- self.assertCountEqual(response[0]["labels"], ["22-Dec-2019", "29-Dec-2019"])
- self.assertCountEqual(response[0]["data"], [0, 1003])
-
- @snapshot_clickhouse_queries
- def test_trends_with_session_property_total_volume_math(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla2"],
- properties={"$some_prop": "some_val"},
- )
-
- _create_event(
- team=self.team,
- event="sign up before",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:34",
- )
- _create_event(
- team=self.team,
- event="sign up later",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:35",
- )
- # First session lasted 5 seconds
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2},
- timestamp="2020-01-01 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2},
- timestamp="2020-01-01 00:06:45",
- )
- # Second session lasted 10 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 3},
- timestamp="2020-01-01 00:06:45",
- )
- # Third session lasted 0 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4},
- timestamp="2020-01-02 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4},
- timestamp="2020-01-02 00:06:45",
- )
- # Fourth session lasted 15 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 5},
- timestamp="2020-01-02 00:06:40",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 5},
- timestamp="2020-01-02 00:06:45",
- )
- # Fifth session lasted 5 seconds
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "week",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "day",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertCountEqual(daily_response[0]["labels"], ["22-Dec-2019", "29-Dec-2019"])
- self.assertCountEqual(daily_response[0]["data"], [0, 5])
-
- self.assertCountEqual(
- weekly_response[0]["labels"],
- [
- "28-Dec-2019",
- "29-Dec-2019",
- "30-Dec-2019",
- "31-Dec-2019",
- "1-Jan-2020",
- "2-Jan-2020",
- "3-Jan-2020",
- "4-Jan-2020",
- ],
- )
- self.assertCountEqual(weekly_response[0]["data"], [0, 0, 0, 0, 5, 10, 0, 0])
-
- @snapshot_clickhouse_queries
- def test_trends_with_session_property_total_volume_math_with_breakdowns(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla2"],
- properties={"$some_prop": "some_val"},
- )
-
- _create_event(
- team=self.team,
- event="sign up before",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value2"},
- timestamp="2020-01-01 00:06:34",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1, "$some_property": "value2"},
- timestamp="2020-01-01 00:06:35",
- )
- # First session lasted 5 seconds
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2, "$some_property": "value2"},
- timestamp="2020-01-01 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:45",
- )
- # Second session lasted 10 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 3, "$some_property": "value1"},
- timestamp="2020-01-01 00:06:45",
- )
- # Third session lasted 0 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4, "$some_property": "value2"},
- timestamp="2020-01-02 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 4, "$some_property": "value2"},
- timestamp="2020-01-02 00:06:45",
- )
- # Fourth session lasted 15 seconds
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 5, "$some_property": "value1"},
- timestamp="2020-01-02 00:06:40",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 5, "$some_property": "value1"},
- timestamp="2020-01-02 00:06:45",
- )
- # Fifth session lasted 5 seconds
-
- with freeze_time("2020-01-04T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "breakdown": "$some_property",
- "interval": "week",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- with freeze_time("2020-01-04T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "breakdown": "$some_property",
- "interval": "day",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- # value1 has 0,5,10 seconds (in second interval)
- # value2 has 5,10,15 seconds (in second interval)
- self.assertEqual([resp["breakdown_value"] for resp in daily_response], ["value2", "value1"])
- self.assertCountEqual(daily_response[0]["labels"], ["22-Dec-2019", "29-Dec-2019"])
- self.assertCountEqual(daily_response[0]["data"], [0, 10])
- self.assertCountEqual(daily_response[1]["data"], [0, 5])
-
- self.assertEqual([resp["breakdown_value"] for resp in weekly_response], ["value2", "value1"])
- self.assertCountEqual(
- weekly_response[0]["labels"],
- [
- "28-Dec-2019",
- "29-Dec-2019",
- "30-Dec-2019",
- "31-Dec-2019",
- "1-Jan-2020",
- "2-Jan-2020",
- "3-Jan-2020",
- "4-Jan-2020",
- ],
- )
- self.assertCountEqual(weekly_response[0]["data"], [0, 0, 0, 0, 7.5, 15, 0, 0])
- self.assertCountEqual(weekly_response[1]["data"], [0, 0, 0, 0, 5, 5, 0, 0])
-
- def test_trends_with_session_property_total_volume_math_with_sessions_spanning_multiple_intervals(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla2"],
- properties={"$some_prop": "some_val"},
- )
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-01 00:06:30",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-02 00:06:34",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$session_id": 1},
- timestamp="2020-01-03 00:06:30",
- )
- # First Session lasted 48 hours = a lot of seconds
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2},
- timestamp="2020-01-01 00:06:35",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={"$session_id": 2},
- timestamp="2020-01-05 00:06:35",
- )
- # Second session lasted 96 hours = a lot of seconds
-
- with freeze_time("2020-01-06T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "day",
- "events": [
- {
- "id": "sign up",
- "math": "median",
- "math_property": "$session_duration",
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertCountEqual(
- weekly_response[0]["labels"],
- [
- "30-Dec-2019",
- "31-Dec-2019",
- "1-Jan-2020",
- "2-Jan-2020",
- "3-Jan-2020",
- "4-Jan-2020",
- "5-Jan-2020",
- "6-Jan-2020",
- ],
- )
-
- ONE_DAY_IN_SECONDS = 24 * 60 * 60
- # math property is counted only in the intervals in which the session was active
- # and the event in question happened (i.e. sign up event)
- self.assertCountEqual(
- weekly_response[0]["data"],
- [
- 0,
- 0,
- 3 * ONE_DAY_IN_SECONDS,
- 2 * ONE_DAY_IN_SECONDS,
- 2 * ONE_DAY_IN_SECONDS,
- 0,
- 4 * ONE_DAY_IN_SECONDS,
- 0,
- ],
- )
-
- @also_test_with_person_on_events_v2
- @also_test_with_materialized_columns(person_properties=["name"])
- def test_filter_events_by_cohort(self):
- _create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})
- _create_person(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})
-
- _create_event(
- event="event_name",
- team=self.team,
- distinct_id="person_1",
- properties={"$browser": "Safari"},
- )
- _create_event(
- event="event_name",
- team=self.team,
- distinct_id="person_2",
- properties={"$browser": "Chrome"},
- )
- _create_event(
- event="event_name",
- team=self.team,
- distinct_id="person_2",
- properties={"$browser": "Safari"},
- )
-
- cohort = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "Jane", "type": "person"}]}],
- )
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "properties": [{"key": "id", "value": cohort.pk, "type": "cohort"}],
- "events": [{"id": "event_name"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["count"], 2)
- self.assertEqual(response[0]["data"][-1], 2)
-
- @also_test_with_person_on_events_v2
- @snapshot_clickhouse_queries
- def test_filter_events_by_precalculated_cohort(self):
- with freeze_time("2020-01-02"):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person_1"],
- properties={"name": "John"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person_2"],
- properties={"name": "Jane"},
- )
-
- _create_event(
- event="event_name",
- team=self.team,
- distinct_id="person_1",
- properties={"$browser": "Safari"},
- )
- _create_event(
- event="event_name",
- team=self.team,
- distinct_id="person_2",
- properties={"$browser": "Chrome"},
- )
- _create_event(
- event="event_name",
- team=self.team,
- distinct_id="person_2",
- properties={"$browser": "Safari"},
- )
-
- cohort = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "Jane", "type": "person"}]}],
- )
- cohort.calculate_people_ch(pending_version=0)
-
- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "properties": [{"key": "id", "value": cohort.pk, "type": "cohort"}],
- "events": [{"id": "event_name"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["count"], 2)
- self.assertEqual(response[0]["data"][-1], 2)
-
- def test_response_empty_if_no_events(self):
- self._create_events()
- flush_persons_and_events()
- response = Trends().run(Filter(team=self.team, data={"date_from": "2012-12-12"}), self.team)
- self.assertEqual(response, [])
-
- def test_interval_filtering_hour(self):
- self._create_events(use_time=True)
-
- with freeze_time("2020-01-02"):
- response = Trends().run(
- Filter(
- data={
- "date_from": "2019-12-24",
- "interval": "hour",
- "events": [{"id": "sign up"}],
- }
- ),
- self.team,
- )
- self.assertEqual(response[0]["labels"][3], "24-Dec-2019 03:00")
- self.assertEqual(response[0]["data"][3], 1.0)
- # 217 - 24 - 1
- self.assertEqual(response[0]["data"][192], 3.0)
-
- def test_interval_filtering_week(self):
- self._create_events(use_time=True)
-
- with freeze_time("2020-01-02"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- # 2019-11-24 is a Sunday, i.e. beginning of our week
- "date_from": "2019-11-24",
- "interval": "week",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
- self.assertEqual(
- response[0]["labels"][:5],
- ["24-Nov-2019", "1-Dec-2019", "8-Dec-2019", "15-Dec-2019", "22-Dec-2019"],
- )
- self.assertEqual(response[0]["data"][:5], [0.0, 0.0, 0.0, 0.0, 1.0])
-
- def test_interval_filtering_month(self):
- self._create_events(use_time=True)
-
- with freeze_time("2020-01-02"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2019-9-24",
- "interval": "month",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["labels"][0], "1-Sep-2019")
- self.assertEqual(response[0]["data"][0], 0)
- self.assertEqual(response[0]["labels"][3], "1-Dec-2019")
- self.assertEqual(response[0]["data"][3], 1.0)
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 4.0)
-
- def test_interval_filtering_today_hourly(self):
- self._create_events(use_time=True)
-
- with freeze_time("2020-01-02 23:30"):
- _create_event(team=self.team, event="sign up", distinct_id="blabla")
-
- with freeze_time("2020-01-02T23:31:00Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "dStart",
- "interval": "hour",
- "events": [{"id": "sign up"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["labels"][23], "2-Jan-2020 23:00")
- self.assertEqual(response[0]["data"][23], 1.0)
-
- def test_breakdown_label(self):
- entity = Entity({"id": "$pageview", "name": "$pageview", "type": TREND_FILTER_TYPE_EVENTS})
- num_label = breakdown_label(entity, 1)
- self.assertEqual(num_label, {"label": "$pageview - 1", "breakdown_value": 1})
-
- string_label = breakdown_label(entity, "Chrome")
- self.assertEqual(string_label, {"label": "$pageview - Chrome", "breakdown_value": "Chrome"})
-
- nan_label = breakdown_label(entity, "nan")
- self.assertEqual(
- nan_label,
- {
- "label": "$pageview - Other (i.e. all remaining values)",
- "breakdown_value": "Other (i.e. all remaining values)",
- },
- )
-
- none_label = breakdown_label(entity, "None (i.e. no value)")
- self.assertEqual(
- none_label,
- {
- "label": "$pageview - Other (i.e. all remaining values)",
- "breakdown_value": "Other (i.e. all remaining values)",
- },
- )
-
- cohort_all_label = breakdown_label(entity, "cohort_all")
- self.assertEqual(
- cohort_all_label,
- {"label": "$pageview - all users", "breakdown_value": "all"},
- )
-
- cohort = _create_cohort(team=self.team, name="cohort1", groups=[{"properties": {"name": "Jane"}}])
- cohort_label = breakdown_label(entity, f"cohort_{cohort.pk}")
- self.assertEqual(
- cohort_label,
- {"label": f"$pageview - {cohort.name}", "breakdown_value": cohort.pk},
- )
-
- @also_test_with_materialized_columns(["key"])
- def test_breakdown_with_filter(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person1"],
- properties={"email": "[email protected]"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person2"],
- properties={"email": "[email protected]"},
- )
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "val"},
- )
- _create_event(
- event="sign up",
- distinct_id="person2",
- team=self.team,
- properties={"key": "oh"},
- )
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "key",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- "properties": [{"key": "key", "value": "oh", "operator": "not_icontains"}],
- },
- ),
- self.team,
- )
- self.assertEqual(len(response), 1)
- self.assertEqual(response[0]["breakdown_value"], "val")
-
- def test_action_filtering(self):
- sign_up_action, person = self._create_events()
- action_response = Trends().run(
- Filter(team=self.team, data={"actions": [{"id": sign_up_action.id}]}),
- self.team,
- )
- event_response = Trends().run(Filter(team=self.team, data={"events": [{"id": "sign up"}]}), self.team)
- self.assertEqual(len(action_response), 1)
-
- self.assertEntityResponseEqual(action_response, event_response)
-
- @also_test_with_person_on_events_v2
- @snapshot_clickhouse_queries
- def test_action_filtering_with_cohort(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_property": "value", "$bool_prop": "x"},
- )
- cohort = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "$some_property", "value": "value", "type": "person"}]}],
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value"},
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "value2"},
- timestamp="2020-01-03T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="xyz",
- properties={"$some_property": "value"},
- timestamp="2020-01-04T12:00:00Z",
- )
-
- sign_up_action = _create_action(
- team=self.team,
- name="sign up",
- properties=[{"key": "id", "type": "cohort", "value": cohort.id}],
- )
-
- cohort.calculate_people_ch(pending_version=2)
-
- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "actions": [{"id": sign_up_action.id}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- "properties": [{"key": "$bool_prop", "value": "x", "type": "person"}],
- },
- ),
- self.team,
- )
- self.assertEqual(len(action_response), 1)
- self.assertEqual(action_response[0]["data"], [0, 1, 1, 0, 0, 0, 0])
-
- def test_trends_for_non_existing_action(self):
- with freeze_time("2020-01-04"):
- response = Trends().run(Filter(data={"actions": [{"id": 50000000}]}), self.team)
- self.assertEqual(len(response), 0)
-
- with freeze_time("2020-01-04"):
- response = Trends().run(Filter(data={"events": [{"id": "DNE"}]}), self.team)
- self.assertEqual(response[0]["data"], [0, 0, 0, 0, 0, 0, 0, 0])
-
- @also_test_with_materialized_columns(person_properties=["email", "bar"])
- def test_trends_regression_filtering_by_action_with_person_properties(self):
- _create_person(
- team_id=self.team.pk,
- properties={"email": "[email protected]", "bar": "aa"},
- distinct_ids=["d1"],
- )
- _create_person(
- team_id=self.team.pk,
- properties={"email": "[email protected]", "bar": "bb"},
- distinct_ids=["d2"],
- )
- _create_person(
- team_id=self.team.pk,
- properties={"email": "[email protected]", "bar": "ab"},
- distinct_ids=["d3"],
- )
- _create_person(team_id=self.team.pk, properties={"bar": "aa"}, distinct_ids=["d4"])
-
- with freeze_time("2020-01-02 16:34:34"):
- _create_event(team=self.team, event="$pageview", distinct_id="d1")
- _create_event(team=self.team, event="$pageview", distinct_id="d2")
- _create_event(team=self.team, event="$pageview", distinct_id="d3")
- _create_event(team=self.team, event="$pageview", distinct_id="d4")
-
- event_filtering_action = Action.objects.create(
- team=self.team,
- name="$pageview from non-internal",
- steps_json=[
- {
- "event": "$pageview",
- "properties": [{"key": "bar", "type": "person", "value": "a", "operator": "icontains"}],
- }
- ],
- )
-
- with freeze_time("2020-01-04T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={"actions": [{"id": event_filtering_action.id}]},
- ),
- self.team,
- )
- self.assertEqual(len(response), 1)
- self.assertEqual(response[0]["count"], 3)
-
- with freeze_time("2020-01-04T13:01:01Z"):
- response_with_email_filter = Trends().run(
- Filter(
- team=self.team,
- data={
- "actions": [{"id": event_filtering_action.id}],
- "properties": [
- {
- "key": "email",
- "type": "person",
- "value": "is_set",
- "operator": "is_set",
- }
- ],
- },
- ),
- self.team,
- )
- self.assertEqual(len(response_with_email_filter), 1)
- self.assertEqual(response_with_email_filter[0]["count"], 2)
-
- def test_dau_filtering(self):
- sign_up_action, person = self._create_events()
-
- with freeze_time("2020-01-02"):
- _create_person(team_id=self.team.pk, distinct_ids=["someone_else"])
- _create_event(team=self.team, event="sign up", distinct_id="someone_else")
-
- with freeze_time("2020-01-04"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={"actions": [{"id": sign_up_action.id, "math": "dau"}]},
- ),
- self.team,
- )
- response = Trends().run(Filter(data={"events": [{"id": "sign up", "math": "dau"}]}), self.team)
-
- self.assertEqual(response[0]["data"][4], 1)
- self.assertEqual(response[0]["data"][5], 2)
- self.assertEntityResponseEqual(action_response, response)
-
- def _create_maths_events(self, values):
- sign_up_action, person = self._create_events()
- _create_person(team_id=self.team.pk, distinct_ids=["someone_else"])
- for value in values:
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="someone_else",
- properties={"some_number": value},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="someone_else",
- properties={"some_number": None},
- )
- return sign_up_action
-
- def _test_math_property_aggregation(self, math_property, values, expected_value):
- sign_up_action = self._create_maths_events(values)
-
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "actions": [
- {
- "id": sign_up_action.id,
- "math": math_property,
- "math_property": "some_number",
- }
- ]
- },
- ),
- self.team,
- )
- event_response = Trends().run(
- Filter(
- data={
- "events": [
- {
- "id": "sign up",
- "math": math_property,
- "math_property": "some_number",
- }
- ]
- }
- ),
- self.team,
- )
- # :TRICKY: Work around clickhouse functions not being 100%
- self.assertAlmostEqual(action_response[0]["data"][-1], expected_value, delta=0.5)
- self.assertEntityResponseEqual(action_response, event_response)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_sum_filtering(self):
- self._test_math_property_aggregation("sum", values=[2, 3, 5.5, 7.5], expected_value=18)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_avg_filtering(self):
- self._test_math_property_aggregation("avg", values=[2, 3, 5.5, 7.5], expected_value=4.5)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_min_filtering(self):
- self._test_math_property_aggregation("min", values=[2, 3, 5.5, 7.5], expected_value=2)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_max_filtering(self):
- self._test_math_property_aggregation("max", values=[2, 3, 5.5, 7.5], expected_value=7.5)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_median_filtering(self):
- self._test_math_property_aggregation("median", values=range(101, 201), expected_value=150)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_p75_filtering(self):
- self._test_math_property_aggregation("p75", values=range(101, 201), expected_value=175)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_p90_filtering(self):
- self._test_math_property_aggregation("p90", values=range(101, 201), expected_value=190)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_p95_filtering(self):
- self._test_math_property_aggregation("p95", values=range(101, 201), expected_value=195)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_p99_filtering(self):
- self._test_math_property_aggregation("p99", values=range(101, 201), expected_value=199)
-
- @also_test_with_materialized_columns(["some_number"])
- def test_avg_filtering_non_number_resiliency(self):
- sign_up_action, person = self._create_events()
- _create_person(team_id=self.team.pk, distinct_ids=["someone_else"])
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="someone_else",
- properties={"some_number": 2},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="someone_else",
- properties={"some_number": "x"},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="someone_else",
- properties={"some_number": None},
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="someone_else",
- properties={"some_number": 8},
- )
- action_response = Trends().run(
- Filter(
- data={
- "actions": [
- {
- "id": sign_up_action.id,
- "math": "avg",
- "math_property": "some_number",
- }
- ]
- }
- ),
- self.team,
- )
- event_response = Trends().run(
- Filter(data={"events": [{"id": "sign up", "math": "avg", "math_property": "some_number"}]}),
- self.team,
- )
- self.assertEqual(action_response[0]["data"][-1], 5)
- self.assertEntityResponseEqual(action_response, event_response)
-
- @also_test_with_materialized_columns(["$some_property"])
- def test_per_entity_filtering(self):
- self._create_events()
- with freeze_time("2020-01-04T13:00:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "events": [
- {
- "id": "sign up",
- "properties": [{"key": "$some_property", "value": "value"}],
- },
- {
- "id": "sign up",
- "properties": [{"key": "$some_property", "value": "other_value"}],
- },
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 1)
- self.assertEqual(response[0]["count"], 1)
- self.assertEqual(response[1]["labels"][5], "2-Jan-2020")
- self.assertEqual(response[1]["data"][5], 1)
- self.assertEqual(response[1]["count"], 1)
-
- def _create_multiple_people(self):
- person1 = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person1"],
- properties={"name": "person1"},
- )
- person2 = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person2"],
- properties={"name": "person2"},
- )
- person3 = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person3"],
- properties={"name": "person3"},
- )
- person4 = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person4"],
- properties={"name": "person4"},
- )
-
- journey = {
- "person1": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"order": "1", "name": "1"},
- }
- ],
- "person2": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"order": "1", "name": "2"},
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"order": "2", "name": "2"},
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"order": "2", "name": "2"},
- },
- ],
- "person3": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 1, 12),
- "properties": {"order": "1", "name": "3"},
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"order": "2", "name": "3"},
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 3, 12),
- "properties": {"order": "2", "name": "3"},
- },
- ],
- "person4": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 5, 12),
- "properties": {"order": "1", "name": "4"},
- }
- ],
- }
-
- journeys_for(events_by_person=journey, team=self.team)
-
- return (person1, person2, person3, person4)
-
- @also_test_with_materialized_columns(person_properties=["name"])
- @snapshot_clickhouse_queries
- def test_person_property_filtering(self):
- self._create_multiple_people()
- with freeze_time("2020-01-04"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "properties": [{"key": "name", "value": "person1", "type": "person"}],
- "events": [{"id": "watched movie"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 1.0)
- self.assertEqual(response[0]["labels"][5], "2-Jan-2020")
- self.assertEqual(response[0]["data"][5], 0)
-
- @also_test_with_materialized_columns(["name"], person_properties=["name"])
- @snapshot_clickhouse_queries
- def test_person_property_filtering_clashing_with_event_property(self):
- # This test needs to choose the right materialised column for it to pass.
- # For resiliency, we reverse the filter as well.
- self._create_multiple_people()
- with freeze_time("2020-01-04"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "properties": [{"key": "name", "value": "person1", "type": "person"}],
- "events": [{"id": "watched movie"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 1.0)
- self.assertEqual(response[0]["labels"][5], "2-Jan-2020")
- self.assertEqual(response[0]["data"][5], 0)
-
- with freeze_time("2020-01-04"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "properties": [{"key": "name", "value": "1", "type": "event"}],
- "events": [{"id": "watched movie"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 1.0)
- self.assertEqual(response[0]["labels"][5], "2-Jan-2020")
- self.assertEqual(response[0]["data"][5], 0)
-
- @also_test_with_materialized_columns(person_properties=["name"])
- def test_entity_person_property_filtering(self):
- self._create_multiple_people()
- with freeze_time("2020-01-04"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "events": [
- {
- "id": "watched movie",
- "properties": [
- {
- "key": "name",
- "value": "person1",
- "type": "person",
- }
- ],
- }
- ]
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 1.0)
- self.assertEqual(response[0]["labels"][5], "2-Jan-2020")
- self.assertEqual(response[0]["data"][5], 0)
-
- def test_breakdown_by_empty_cohort(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-04T12:00:00Z",
- )
-
- with freeze_time("2020-01-04T13:01:01Z"):
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": json.dumps(["all"]),
- "breakdown_type": "cohort",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(event_response[0]["label"], "all users")
- self.assertEqual(sum(event_response[0]["data"]), 1)
-
- @also_test_with_person_on_events_v2
- @also_test_with_materialized_columns(person_properties=["name"], verify_no_jsonextract=False)
- def test_breakdown_by_cohort(self):
- person1, person2, person3, person4 = self._create_multiple_people()
- cohort = _create_cohort(
- name="cohort1",
- team=self.team,
- groups=[{"properties": [{"key": "name", "value": "person1", "type": "person"}]}],
- )
- cohort2 = _create_cohort(
- name="cohort2",
- team=self.team,
- groups=[{"properties": [{"key": "name", "value": "person2", "type": "person"}]}],
- )
- cohort3 = _create_cohort(
- name="cohort3",
- team=self.team,
- groups=[
- {"properties": [{"key": "name", "value": "person1", "type": "person"}]},
- {"properties": [{"key": "name", "value": "person2", "type": "person"}]},
- ],
- )
- action = _create_action(name="watched movie", team=self.team)
-
- with freeze_time("2020-01-04T13:01:01Z"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": json.dumps([cohort.pk, cohort2.pk, cohort3.pk, "all"]),
- "breakdown_type": "cohort",
- "actions": [{"id": action.pk, "type": "actions", "order": 0}],
- },
- ),
- self.team,
- )
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": json.dumps([cohort.pk, cohort2.pk, cohort3.pk, "all"]),
- "breakdown_type": "cohort",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- }
- ],
- },
- ),
- self.team,
- )
-
- counts = {}
- break_val = {}
- for res in event_response:
- counts[res["label"]] = sum(res["data"])
- break_val[res["label"]] = res["breakdown_value"]
-
- self.assertEqual(counts["cohort1"], 1)
- self.assertEqual(counts["cohort2"], 3)
- self.assertEqual(counts["cohort3"], 4)
- self.assertEqual(counts["all users"], 7)
-
- self.assertEqual(break_val["cohort1"], cohort.pk)
- self.assertEqual(break_val["cohort2"], cohort2.pk)
- self.assertEqual(break_val["cohort3"], cohort3.pk)
- self.assertEqual(break_val["all users"], "all")
-
- self.assertEntityResponseEqual(event_response, action_response)
-
- @also_test_with_materialized_columns(verify_no_jsonextract=False)
- def test_interval_filtering_breakdown(self):
- self._create_events(use_time=True)
- cohort = _create_cohort(
- name="cohort1",
- team=self.team,
- groups=[{"properties": [{"key": "$some_prop", "value": "some_val", "type": "person"}]}],
- )
-
- # test hour
- with freeze_time("2020-01-02"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2019-12-24",
- "interval": "hour",
- "events": [{"id": "sign up"}],
- "breakdown": json.dumps([cohort.pk]),
- "breakdown_type": "cohort",
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["labels"][3], "24-Dec-2019 03:00")
- self.assertEqual(response[0]["data"][3], 1.0)
- # 217 - 24 - 1
- self.assertEqual(response[0]["data"][192], 3.0)
-
- # test week
- with freeze_time("2020-01-02"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- # 2019-11-24 is a Sunday
- "date_from": "2019-11-24",
- "interval": "week",
- "events": [{"id": "sign up"}],
- "breakdown": json.dumps([cohort.pk]),
- "breakdown_type": "cohort",
- },
- ),
- self.team,
- )
-
- self.assertEqual(
- response[0]["labels"][:5],
- ["24-Nov-2019", "1-Dec-2019", "8-Dec-2019", "15-Dec-2019", "22-Dec-2019"],
- )
- self.assertEqual(response[0]["data"][:5], [0.0, 0.0, 0.0, 0.0, 1.0])
-
- # test month
- with freeze_time("2020-01-02"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2019-9-24",
- "interval": "month",
- "events": [{"id": "sign up"}],
- "breakdown": json.dumps([cohort.pk]),
- "breakdown_type": "cohort",
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["labels"][3], "1-Dec-2019")
- self.assertEqual(response[0]["data"][3], 1.0)
- self.assertEqual(response[0]["labels"][4], "1-Jan-2020")
- self.assertEqual(response[0]["data"][4], 4.0)
-
- with freeze_time("2020-01-02 23:30"):
- _create_event(team=self.team, event="sign up", distinct_id="blabla")
-
- # test today + hourly
- with freeze_time("2020-01-02T23:31:00Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "dStart",
- "interval": "hour",
- "events": [{"id": "sign up"}],
- "breakdown": json.dumps([cohort.pk]),
- "breakdown_type": "cohort",
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["labels"][23], "2-Jan-2020 23:00")
- self.assertEqual(response[0]["data"][23], 1.0)
-
- def test_breakdown_by_person_property(self):
- person1, person2, person3, person4 = self._create_multiple_people()
- action = _create_action(name="watched movie", team=self.team)
-
- with freeze_time("2020-01-04T13:01:01Z"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "name",
- "breakdown_type": "person",
- "actions": [{"id": action.pk, "type": "actions", "order": 0}],
- },
- ),
- self.team,
- )
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "name",
- "breakdown_type": "person",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertListEqual(
- sorted(res["breakdown_value"] for res in event_response),
- ["person1", "person2", "person3"],
- )
-
- for response in event_response:
- if response["breakdown_value"] == "person1":
- self.assertEqual(response["count"], 1)
- self.assertEqual(response["label"], "person1")
- if response["breakdown_value"] == "person2":
- self.assertEqual(response["count"], 3)
- if response["breakdown_value"] == "person3":
- self.assertEqual(response["count"], 3)
-
- self.assertEntityResponseEqual(event_response, action_response)
-
- @also_test_with_materialized_columns(["name"], person_properties=["name"])
- def test_breakdown_by_person_property_for_person_on_events(self):
- person1, person2, person3, person4 = self._create_multiple_people()
-
- with freeze_time("2020-01-04T13:01:01Z"):
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "name",
- "breakdown_type": "person",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertListEqual(
- sorted(res["breakdown_value"] for res in event_response),
- ["person1", "person2", "person3"],
- )
-
- for response in event_response:
- if response["breakdown_value"] == "person1":
- self.assertEqual(response["count"], 1)
- self.assertEqual(response["label"], "person1")
- if response["breakdown_value"] == "person2":
- self.assertEqual(response["count"], 3)
- if response["breakdown_value"] == "person3":
- self.assertEqual(response["count"], 3)
-
- def test_breakdown_by_person_property_for_person_on_events_with_zero_person_ids(self):
- # only a person-on-event test
- if not get_instance_setting("PERSON_ON_EVENTS_ENABLED"):
- return True
-
- self._create_multiple_people()
-
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person5",
- person_id="00000000-0000-0000-0000-000000000000",
- person_properties={"name": "person5"},
- timestamp=datetime(2020, 1, 1, 12),
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person6",
- person_id="00000000-0000-0000-0000-000000000000",
- person_properties={"name": "person6"},
- timestamp=datetime(2020, 1, 1, 12),
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person7",
- person_id="00000000-0000-0000-0000-000000000000",
- person_properties={"name": "person2"},
- timestamp=datetime(2020, 1, 1, 12),
- )
-
- with freeze_time("2020-01-04T13:01:01Z"):
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "name",
- "breakdown_type": "person",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertListEqual(
- sorted(res["breakdown_value"] for res in event_response),
- ["person1", "person2", "person3"],
- )
-
- for response in event_response:
- if response["breakdown_value"] == "person1":
- self.assertEqual(response["count"], 1)
- self.assertEqual(response["label"], "watched movie - person1")
- if response["breakdown_value"] == "person2":
- self.assertEqual(response["count"], 3)
- if response["breakdown_value"] == "person3":
- self.assertEqual(response["count"], 3)
-
- def test_breakdown_by_property_pie(self):
- with freeze_time("2020-01-01T12:00:00Z"): # Fake created_at for easier assertions
- person1 = _create_person(team_id=self.team.pk, distinct_ids=["person1"], immediate=True)
- person2 = _create_person(team_id=self.team.pk, distinct_ids=["person2"], immediate=True)
- person3 = _create_person(team_id=self.team.pk, distinct_ids=["person3"], immediate=True)
-
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person1",
- timestamp="2020-01-01T12:00:00Z",
- properties={"fake_prop": "value_1"},
- )
-
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person2",
- timestamp="2020-01-01T12:00:00Z",
- properties={"fake_prop": "value_1"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person2",
- timestamp="2020-01-01T12:00:00Z",
- properties={"fake_prop": "value_1"},
- )
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person2",
- timestamp="2020-01-02T12:00:00Z",
- properties={"fake_prop": "value_2"},
- )
-
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person3",
- timestamp="2020-01-01T12:00:00Z",
- properties={"fake_prop": "value_1"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["person4"], immediate=True)
- _create_event(
- team=self.team,
- event="watched movie",
- distinct_id="person4",
- timestamp="2020-01-05T12:00:00Z",
- properties={"fake_prop": "value_1"},
- )
-
- with freeze_time("2020-01-04T13:01:01Z"):
- data = {
- "date_from": "-14d",
- "breakdown": "fake_prop",
- "breakdown_type": "event",
- "display": "ActionsPie",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- "math": "dau",
- }
- ],
- }
- event_response = Trends().run(Filter(team=self.team, data=data), self.team)
- event_response = sorted(event_response, key=lambda resp: resp["breakdown_value"])
-
- entity = Entity({"id": "watched movie", "type": "events", "math": "dau"})
-
- people_value_1 = self._get_trend_people(
- Filter(team=self.team, data={**data, "breakdown_value": "value_1"}),
- entity,
- )
- assert people_value_1 == [
- # Persons with higher value come first
- {
- "created_at": "2020-01-01T12:00:00Z",
- "last_seen_at": None,
- "distinct_ids": ["person2"],
- "id": str(person2.uuid),
- "is_identified": False,
- "matched_recordings": [],
- "name": "person2",
- "properties": {},
- "type": "person",
- "uuid": str(person2.uuid),
- "value_at_data_point": 2, # 2 events with fake_prop="value_1" in the time range
- },
- {
- "created_at": "2020-01-01T12:00:00Z",
- "last_seen_at": None,
- "distinct_ids": ["person1"],
- "id": str(person1.uuid),
- "is_identified": False,
- "matched_recordings": [],
- "name": "person1",
- "properties": {},
- "type": "person",
- "uuid": str(person1.uuid),
- "value_at_data_point": 1, # 1 event with fake_prop="value_1" in the time range
- },
- {
- "created_at": "2020-01-01T12:00:00Z",
- "last_seen_at": None,
- "distinct_ids": ["person3"],
- "id": str(person3.uuid),
- "is_identified": False,
- "matched_recordings": [],
- "name": "person3",
- "properties": {},
- "type": "person",
- "uuid": str(person3.uuid),
- "value_at_data_point": 1, # 1 event with fake_prop="value_1" in the time range
- },
- ]
-
- people_value_2 = self._get_trend_people(
- Filter(team=self.team, data={**data, "breakdown_value": "value_2"}),
- entity,
- )
- assert people_value_2 == [
- {
- "created_at": "2020-01-01T12:00:00Z",
- "last_seen_at": None,
- "distinct_ids": ["person2"],
- "id": str(person2.uuid),
- "is_identified": False,
- "matched_recordings": [],
- "name": "person2",
- "properties": {},
- "type": "person",
- "uuid": str(person2.uuid),
- "value_at_data_point": 1, # 1 event with fake_prop="value_2" in the time range
- }
- ]
-
- @also_test_with_materialized_columns(person_properties=["name"])
- def test_breakdown_by_person_property_pie(self):
- self._create_multiple_people()
-
- with freeze_time("2020-01-04T13:01:01Z"):
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "name",
- "breakdown_type": "person",
- "display": "ActionsPie",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- "math": "dau",
- }
- ],
- },
- ),
- self.team,
- )
- event_response = sorted(event_response, key=lambda resp: resp["breakdown_value"])
- self.assertLessEqual(
- {"breakdown_value": "person1", "aggregated_value": 1}.items(), event_response[0].items()
- )
- self.assertLessEqual(
- {"breakdown_value": "person2", "aggregated_value": 1}.items(), event_response[1].items()
- )
- self.assertLessEqual(
- {"breakdown_value": "person3", "aggregated_value": 1}.items(), event_response[2].items()
- )
-
- @also_test_with_materialized_columns(person_properties=["name"])
- def test_breakdown_by_person_property_pie_with_event_dau_filter(self):
- self._create_multiple_people()
-
- with freeze_time("2020-01-04T13:01:01Z"):
- event_response = Trends().run(
- Filter(
- data={
- "date_from": "-14d",
- "breakdown": "name",
- "breakdown_type": "person",
- "display": "ActionsPie",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- "math": "dau",
- "properties": [
- {
- "key": "name",
- "operator": "not_icontains",
- "value": "person3",
- "type": "person",
- }
- ],
- }
- ],
- }
- ),
- self.team,
- )
- event_response = sorted(event_response, key=lambda resp: resp["breakdown_value"])
- self.assertEqual(len(event_response), 2)
- self.assertLessEqual(
- {"breakdown_value": "person1", "aggregated_value": 1}.items(), event_response[0].items()
- )
- self.assertLessEqual(
- {"breakdown_value": "person2", "aggregated_value": 1}.items(), event_response[1].items()
- )
-
- def test_breakdown_hour_interval(self):
- response = self._test_events_with_dates(
- dates=["2020-11-01 13:00:00", "2020-11-01 13:20:00", "2020-11-01 17:00:00"],
- interval="hour",
- date_from="2020-11-01 12:00:00",
- breakdown="$browser",
- breakdown_type="event",
- query_time="2020-11-01 23:00:00",
- result=[
- {
- "action": {
- "id": "event_name",
- "type": "events",
- "order": None,
- "name": "event_name",
- "custom_name": None,
- "math": None,
- "math_hogql": None,
- "math_property": None,
- "math_group_type_index": None,
- "properties": [],
- },
- "label": "event_name",
- "count": 3.0,
- "data": [0.0, 2.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0, 0, 0, 0, 0],
- "labels": [
- "1-Nov-2020 12:00",
- "1-Nov-2020 13:00",
- "1-Nov-2020 14:00",
- "1-Nov-2020 15:00",
- "1-Nov-2020 16:00",
- "1-Nov-2020 17:00",
- "1-Nov-2020 18:00",
- "1-Nov-2020 19:00",
- "1-Nov-2020 20:00",
- "1-Nov-2020 21:00",
- "1-Nov-2020 22:00",
- "1-Nov-2020 23:00",
- ],
- "days": [
- "2020-11-01 12:00:00",
- "2020-11-01 13:00:00",
- "2020-11-01 14:00:00",
- "2020-11-01 15:00:00",
- "2020-11-01 16:00:00",
- "2020-11-01 17:00:00",
- "2020-11-01 18:00:00",
- "2020-11-01 19:00:00",
- "2020-11-01 20:00:00",
- "2020-11-01 21:00:00",
- "2020-11-01 22:00:00",
- "2020-11-01 23:00:00",
- ],
- "persons_urls": [],
- }
- ],
- )
- self.assertEqual(
- {
- "breakdown_type": "event",
- "breakdown_value": "Safari",
- "date_from": datetime(2020, 11, 1, 12, tzinfo=ZoneInfo("UTC")),
- "date_to": datetime(2020, 11, 1, 13, tzinfo=ZoneInfo("UTC")),
- "entity_id": "event_name",
- "entity_math": None,
- "entity_type": "events",
- },
- response[0]["persons_urls"][0]["filter"],
- )
-
- @also_test_with_materialized_columns(person_properties=["name"])
- def test_filter_test_accounts_cohorts(self):
- _create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})
- _create_person(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})
-
- _create_event(event="event_name", team=self.team, distinct_id="person_1")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
-
- cohort = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "Jane", "type": "person"}]}],
- )
- self.team.test_account_filters = [{"key": "id", "value": cohort.pk, "type": "cohort"}]
- self.team.save()
-
- response = Trends().run(
- Filter(
- data={"events": [{"id": "event_name"}], "filter_test_accounts": True},
- team=self.team,
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["count"], 2)
- self.assertEqual(response[0]["data"][-1], 2)
-
- def test_filter_by_precalculated_cohort(self):
- _create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})
- _create_person(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})
-
- _create_event(event="event_name", team=self.team, distinct_id="person_1")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
-
- cohort = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "Jane", "type": "person"}]}],
- )
- cohort.calculate_people_ch(pending_version=0)
- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "events": [{"id": "event_name"}],
- "properties": [{"type": "cohort", "key": "id", "value": cohort.pk}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["count"], 2)
- self.assertEqual(response[0]["data"][-1], 2)
-
- @also_test_with_person_on_events_v2
- def test_breakdown_filter_by_precalculated_cohort(self):
- _create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})
- _create_person(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})
-
- _create_event(event="event_name", team=self.team, distinct_id="person_1")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
- _create_event(event="event_name", team=self.team, distinct_id="person_2")
-
- cohort = _create_cohort(
- team=self.team,
- name="cohort1",
- groups=[{"properties": [{"key": "name", "value": "Jane", "type": "person"}]}],
- )
- cohort.calculate_people_ch(pending_version=0)
-
- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "events": [{"id": "event_name"}],
- "properties": [{"type": "cohort", "key": "id", "value": cohort.pk}],
- "breakdown": "name",
- "breakdown_type": "person",
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["count"], 2)
- self.assertEqual(response[0]["data"][-1], 2)
-
- def test_bar_chart_by_value(self):
- self._create_events()
-
- with freeze_time("2020-01-04T13:00:01Z"):
- # with self.assertNumQueries(16):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "events": [{"id": "sign up"}, {"id": "no events"}],
- "display": TRENDS_BAR_VALUE,
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["aggregated_value"], 4)
- self.assertEqual(response[1]["aggregated_value"], 1)
- self.assertEqual(
- response[0]["days"],
- [
- "2019-12-28",
- "2019-12-29",
- "2019-12-30",
- "2019-12-31",
- "2020-01-01",
- "2020-01-02",
- "2020-01-03",
- "2020-01-04",
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_trends_aggregate_by_distinct_id(self):
- # Stopgap until https://github.com/PostHog/meta/pull/39 is implemented
-
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_person(team_id=self.team.pk, distinct_ids=["third"])
-
- with freeze_time("2019-12-24 03:45:34"):
- _create_event(team=self.team, event="sign up", distinct_id="blabla")
- _create_event(
- team=self.team, event="sign up", distinct_id="blabla"
- ) # aggregated by distinctID, so this should be ignored
- _create_event(team=self.team, event="sign up", distinct_id="anonymous_id")
- _create_event(team=self.team, event="sign up", distinct_id="third")
-
- with override_instance_config("AGGREGATE_BY_DISTINCT_IDS_TEAMS", f"{self.team.pk},4"):
- with freeze_time("2019-12-31T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "day",
- "events": [{"id": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(daily_response[0]["data"][0], 3)
-
- with freeze_time("2019-12-31T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "day",
- "events": [{"id": "sign up", "math": "dau"}],
- "properties": [
- {
- "key": "$some_prop",
- "value": "some_val",
- "type": "person",
- }
- ],
- },
- ),
- self.team,
- )
- self.assertEqual(daily_response[0]["data"][0], 2)
-
- # breakdown person props
- with freeze_time("2019-12-31T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "day",
- "events": [{"id": "sign up", "math": "dau"}],
- "breakdown_type": "person",
- "breakdown": "$some_prop",
- },
- ),
- self.team,
- )
- self.assertEqual(daily_response[0]["data"][0], 2)
- self.assertEqual(daily_response[0]["label"], "some_val")
- self.assertEqual(daily_response[1]["data"][0], 1)
- self.assertEqual(daily_response[1]["label"], "None (i.e. no value)")
-
- # MAU
- with freeze_time("2019-12-31T13:00:01Z"):
- monthly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "day",
- "events": [{"id": "sign up", "math": "monthly_active"}],
- },
- ),
- self.team,
- )
- self.assertEqual(monthly_response[0]["data"][0], 3) # this would be 2 without the aggregate hack
-
- with freeze_time("2019-12-31T13:00:01Z"):
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "day",
- "events": [{"id": "sign up", "math": "weekly_active"}],
- },
- ),
- self.team,
- )
- self.assertEqual(weekly_response[0]["data"][0], 3) # this would be 2 without the aggregate hack
-
- # Make sure breakdown doesn't cause us to join on pdi
- with freeze_time("2019-12-31T13:00:01Z"):
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "interval": "day",
- "events": [{"id": "sign up", "math": "dau"}],
- "breakdown": "$some_prop",
- },
- ),
- self.team,
- )
-
- @also_test_with_materialized_columns(["$some_property"])
- def test_breakdown_filtering_limit(self):
- self._create_breakdown_events(200)
-
- with freeze_time("2020-01-04T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- },
- ),
- self.team,
- )
- assert len(response) == 26
- assert response[0]["label"] == "Other (i.e. all remaining values)"
- assert response[0]["breakdown_value"] == BREAKDOWN_OTHER_STRING_LABEL
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "$some_property",
- "breakdown_limit": 50,
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- },
- ),
- self.team,
- )
- assert len(response) == 51
- assert response[0]["label"] == "Other (i.e. all remaining values)"
- assert response[0]["breakdown_value"] == BREAKDOWN_OTHER_STRING_LABEL
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "$some_property",
- "breakdown_limit": 200,
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- },
- ),
- self.team,
- )
- assert len(response) == 200
-
- @also_test_with_materialized_columns(event_properties=["order"], person_properties=["name"])
- def test_breakdown_with_person_property_filter(self):
- self._create_multiple_people()
- action = _create_action(name="watched movie", team=self.team)
-
- with freeze_time("2020-01-04T13:01:01Z"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "order",
- "actions": [{"id": action.pk, "type": "actions", "order": 0}],
- "properties": [{"key": "name", "value": "person2", "type": "person"}],
- },
- ),
- self.team,
- )
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "order",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- "properties": [
- {
- "key": "name",
- "value": "person2",
- "type": "person",
- }
- ],
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertLessEqual({"count": 2, "breakdown_value": "2"}.items(), event_response[0].items())
- self.assertLessEqual({"count": 1, "breakdown_value": "1"}.items(), event_response[1].items())
- self.assertEntityResponseEqual(event_response, action_response)
-
- @also_test_with_materialized_columns(["$some_property"])
- def test_breakdown_filtering(self):
- self._create_events()
- # test breakdown filtering
- with freeze_time("2020-01-04T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- },
- {"id": "no events"},
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["label"], "sign up - None (i.e. no value)")
- self.assertEqual(response[1]["label"], "sign up - value")
- self.assertEqual(response[2]["label"], "sign up - other_value")
- self.assertEqual(response[3]["label"], "no events - None (i.e. no value)")
-
- self.assertEqual(sum(response[0]["data"]), 2)
- self.assertEqual(sum(response[1]["data"]), 2)
- self.assertEqual(sum(response[2]["data"]), 1)
- self.assertEqual(sum(response[3]["data"]), 1)
-
- @also_test_with_materialized_columns(person_properties=["email"])
- def test_breakdown_filtering_persons(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person1"],
- properties={"email": "[email protected]"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person2"],
- properties={"email": "[email protected]"},
- )
- _create_person(team_id=self.team.pk, distinct_ids=["person3"], properties={})
-
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "val"},
- )
- _create_event(
- event="sign up",
- distinct_id="person2",
- team=self.team,
- properties={"key": "val"},
- )
- _create_event(
- event="sign up",
- distinct_id="person3",
- team=self.team,
- properties={"key": "val"},
- )
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "email",
- "breakdown_type": "person",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["label"], "None (i.e. no value)")
- self.assertEqual(response[1]["label"], "[email protected]")
- self.assertEqual(response[2]["label"], "[email protected]")
-
- self.assertEqual(response[0]["count"], 1)
- self.assertEqual(response[1]["count"], 1)
- self.assertEqual(response[2]["count"], 1)
-
- # ensure that column names are properly handled when subqueries and person subquery share properties column
- @also_test_with_materialized_columns(event_properties=["key"], person_properties=["email"])
- def test_breakdown_filtering_persons_with_action_props(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person1"],
- properties={"email": "[email protected]"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person2"],
- properties={"email": "[email protected]"},
- )
- _create_person(team_id=self.team.pk, distinct_ids=["person3"], properties={})
-
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "val"},
- )
- _create_event(
- event="sign up",
- distinct_id="person2",
- team=self.team,
- properties={"key": "val"},
- )
- _create_event(
- event="sign up",
- distinct_id="person3",
- team=self.team,
- properties={"key": "val"},
- )
- action = _create_action(
- name="sign up",
- team=self.team,
- properties=[{"key": "key", "type": "event", "value": ["val"], "operator": "exact"}],
- )
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "email",
- "breakdown_type": "person",
- "actions": [{"id": action.pk, "type": "actions", "order": 0}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["label"], "None (i.e. no value)")
- self.assertEqual(response[1]["label"], "[email protected]")
- self.assertEqual(response[2]["label"], "[email protected]")
-
- self.assertEqual(response[0]["count"], 1)
- self.assertEqual(response[1]["count"], 1)
- self.assertEqual(response[2]["count"], 1)
-
- @also_test_with_materialized_columns(["$current_url", "$os", "$browser"])
- def test_breakdown_filtering_with_properties(self):
- with freeze_time("2020-01-03T13:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Chrome",
- "$os": "Windows",
- },
- )
- with freeze_time("2020-01-04T13:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Chrome",
- "$os": "Windows",
- },
- )
-
- with freeze_time("2020-01-05T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "breakdown": "$current_url",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- "properties": [{"key": "$os", "value": "Mac"}],
- }
- ],
- "properties": [{"key": "$browser", "value": "Firefox"}],
- },
- ),
- self.team,
- )
-
- response = sorted(response, key=lambda x: x["label"])
- self.assertEqual(response[0]["label"], "first url")
- self.assertEqual(response[1]["label"], "second url")
-
- self.assertEqual(sum(response[0]["data"]), 1)
- self.assertEqual(response[0]["breakdown_value"], "first url")
-
- self.assertEqual(sum(response[1]["data"]), 1)
- self.assertEqual(response[1]["breakdown_value"], "second url")
-
- @snapshot_clickhouse_queries
- def test_breakdown_filtering_with_properties_in_new_format(self):
- with freeze_time("2020-01-03T13:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Windows",
- },
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Chrome",
- "$os": "Mac",
- },
- )
- with freeze_time("2020-01-04T13:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla1",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla2",
- properties={
- "$current_url": "second url",
- "$browser": "Chrome",
- "$os": "Windows",
- },
- )
-
- with freeze_time("2020-01-05T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "$current_url",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- "properties": [{"key": "$os", "value": "Mac"}],
- }
- ],
- "properties": {
- "type": "OR",
- "values": [
- {"key": "$browser", "value": "Firefox"},
- {"key": "$os", "value": "Windows"},
- ],
- },
- },
- ),
- self.team,
- )
-
- response = sorted(response, key=lambda x: x["label"])
- self.assertEqual(response[0]["label"], "second url")
-
- self.assertEqual(sum(response[0]["data"]), 1)
- self.assertEqual(response[0]["breakdown_value"], "second url")
-
- # AND filter properties with disjoint set means results should be empty
- with freeze_time("2020-01-05T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "$current_url",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- "properties": [{"key": "$os", "value": "Mac"}],
- }
- ],
- "properties": {
- "type": "AND",
- "values": [
- {"key": "$browser", "value": "Firefox"},
- {"key": "$os", "value": "Windows"},
- ],
- },
- },
- ),
- self.team,
- )
-
- response = sorted(response, key=lambda x: x["label"])
- self.assertEqual(response, [])
-
- @also_test_with_person_on_events_v2
- @snapshot_clickhouse_queries
- def test_mau_with_breakdown_filtering_and_prop_filter(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val", "filter_prop": "filter_val"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla2"],
- properties={"$some_prop": "some_val3", "filter_prop": "filter_val2"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla3"],
- properties={"$some_prop": "some_val2", "filter_prop": "filter_val"},
- )
- with freeze_time("2020-01-02T13:01:01Z"):
- _create_event(team=self.team, event="sign up", distinct_id="blabla")
- _create_event(team=self.team, event="sign up", distinct_id="blabla2")
- _create_event(team=self.team, event="sign up", distinct_id="blabla3")
- with freeze_time("2020-01-03T13:01:01Z"):
- _create_event(team=self.team, event="sign up", distinct_id="blabla")
- _create_event(team=self.team, event="sign up", distinct_id="blabla2")
- _create_event(team=self.team, event="sign up", distinct_id="blabla3")
- with freeze_time("2020-01-04T13:01:01Z"):
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "breakdown": "$some_prop",
- "breakdown_type": "person",
- "events": [{"id": "sign up", "math": "monthly_active"}],
- "properties": [
- {
- "key": "filter_prop",
- "value": "filter_val",
- "type": "person",
- }
- ],
- "display": "ActionsLineGraph",
- },
- ),
- self.team,
- )
-
- self.assertEqual(event_response[0]["label"], "some_val")
- self.assertEqual(event_response[1]["label"], "some_val2")
-
- self.assertEqual(sum(event_response[0]["data"]), 2)
- self.assertEqual(event_response[0]["data"][5], 1)
-
- self.assertEqual(sum(event_response[1]["data"]), 2)
- self.assertEqual(event_response[1]["data"][5], 1)
-
- @also_test_with_materialized_columns(["$some_property"])
- def test_dau_with_breakdown_filtering(self):
- sign_up_action, _ = self._create_events()
- with freeze_time("2020-01-02T13:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "other_value"},
- )
- with freeze_time("2020-01-04T13:01:01Z"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "breakdown": "$some_property",
- "actions": [{"id": sign_up_action.id, "math": "dau"}],
- },
- ),
- self.team,
- )
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "breakdown": "$some_property",
- "events": [{"id": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(event_response[1]["label"], "other_value")
- self.assertEqual(event_response[2]["label"], "value")
-
- self.assertEqual(sum(event_response[1]["data"]), 1)
- self.assertEqual(event_response[1]["data"][5], 1)
-
- self.assertEqual(sum(event_response[2]["data"]), 1)
- self.assertEqual(event_response[2]["data"][4], 1) # property not defined
-
- self.assertEntityResponseEqual(action_response, event_response)
-
- @snapshot_clickhouse_queries
- def test_dau_with_breakdown_filtering_with_sampling(self):
- sign_up_action, _ = self._create_events()
- with freeze_time("2020-01-02T13:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "other_value"},
- )
- with freeze_time("2020-01-04T13:01:01Z"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "sampling_factor": 1,
- "breakdown": "$some_property",
- "actions": [{"id": sign_up_action.id, "math": "dau"}],
- },
- ),
- self.team,
- )
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "sampling_factor": 1,
- "breakdown": "$some_property",
- "events": [{"id": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(event_response[1]["label"], "other_value")
- self.assertEqual(event_response[2]["label"], "value")
-
- self.assertEqual(sum(event_response[1]["data"]), 1)
- self.assertEqual(event_response[1]["data"][5], 1)
-
- self.assertEqual(sum(event_response[2]["data"]), 1)
- self.assertEqual(event_response[2]["data"][4], 1) # property not defined
-
- self.assertEntityResponseEqual(action_response, event_response)
-
- @also_test_with_materialized_columns(["$os", "$some_property"])
- def test_dau_with_breakdown_filtering_with_prop_filter(self):
- sign_up_action, _ = self._create_events()
- with freeze_time("2020-01-02T13:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$some_property": "other_value", "$os": "Windows"},
- )
- with freeze_time("2020-01-04T13:01:01Z"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "breakdown": "$some_property",
- "actions": [{"id": sign_up_action.id, "math": "dau"}],
- "properties": [{"key": "$os", "value": "Windows"}],
- },
- ),
- self.team,
- )
- event_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "breakdown": "$some_property",
- "events": [{"id": "sign up", "math": "dau"}],
- "properties": [{"key": "$os", "value": "Windows"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(event_response[0]["label"], "other_value")
-
- self.assertEqual(sum(event_response[0]["data"]), 1)
- self.assertEqual(event_response[0]["data"][5], 1) # property not defined
-
- self.assertEntityResponseEqual(action_response, event_response)
-
- @also_test_with_materialized_columns(event_properties=["$host"], person_properties=["$some_prop"])
- def test_against_clashing_entity_and_property_filter_naming(self):
- # Regression test for https://github.com/PostHog/posthog/issues/5814
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="blabla",
- properties={"$host": "app.example.com"},
- timestamp="2020-01-03T12:00:00Z",
- )
-
- with freeze_time("2020-01-04T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "events": [
- {
- "id": "$pageview",
- "properties": [
- {
- "key": "$host",
- "operator": "icontains",
- "value": ".com",
- }
- ],
- }
- ],
- "properties": [
- {
- "key": "$host",
- "value": ["app.example.com", "another.com"],
- }
- ],
- "breakdown": "$some_prop",
- "breakdown_type": "person",
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["count"], 1)
-
- # this ensures that the properties don't conflict when formatting params
- @also_test_with_materialized_columns(["$current_url"])
- def test_action_with_prop(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["blabla", "anonymous_id"],
- properties={"$some_prop": "some_val"},
- )
- sign_up_action = Action.objects.create(
- team=self.team,
- name="sign up",
- steps_json=[
- {
- "event": "sign up",
- "properties": [
- {
- "key": "$current_url",
- "type": "event",
- "value": ["https://posthog.com/feedback/1234"],
- "operator": "exact",
- }
- ],
- }
- ],
- )
-
- with freeze_time("2020-01-02T13:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={"$current_url": "https://posthog.com/feedback/1234"},
- )
-
- with freeze_time("2020-01-04T13:01:01Z"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "actions": [{"id": sign_up_action.id, "math": "dau"}],
- "properties": [{"key": "$current_url", "value": "fake"}],
- },
- ),
- self.team,
- )
-
- # if the params were shared it would be 1 because action would take precedence
- self.assertEqual(action_response[0]["count"], 0)
-
- @also_test_with_materialized_columns(["$current_url"], verify_no_jsonextract=False)
- def test_combine_all_cohort_and_icontains(self):
- # This caused some issues with SQL parsing
- sign_up_action, _ = self._create_events()
- cohort = Cohort.objects.create(
- team=self.team,
- name="a",
- groups=[{"properties": [{"key": "key", "value": "value", "type": "person"}]}],
- )
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "actions": [{"id": sign_up_action.id, "math": "dau"}],
- "properties": [{"key": "$current_url", "value": "ii", "operator": "icontains"}],
- "breakdown": [cohort.pk, "all"],
- "breakdown_type": "cohort",
- },
- ),
- self.team,
- )
- self.assertEqual(action_response[0]["count"], 0)
-
- @also_test_with_person_on_events_v2
- @snapshot_clickhouse_queries
- def test_person_filtering_in_cohort_in_action(self):
- # This caused some issues with SQL parsing
- sign_up_action, _ = self._create_events()
- flush_persons_and_events()
- cohort = Cohort.objects.create(
- team=self.team,
- name="a",
- groups=[{"properties": [{"key": "$some_prop", "value": "some_val", "type": "person"}]}],
- )
- step = sign_up_action.steps[0]
- step.properties = [{"key": "id", "value": cohort.pk, "type": "cohort"}]
-
- sign_up_action.steps = [dataclasses.asdict(step)]
- sign_up_action.save()
-
- with freeze_time("2020-01-04T14:01:01Z"):
- action_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "actions": [{"id": sign_up_action.id}],
- "breakdown": "$some_property",
- },
- ),
- self.team,
- )
- self.assertEqual(action_response[0]["count"], 2)
-
- @also_test_with_materialized_columns(event_properties=["key"], person_properties=["email"])
- def test_breakdown_user_props_with_filter(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person1"],
- properties={"email": "[email protected]"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person2"],
- properties={"email": "[email protected]"},
- )
- person = _create_person(
- team_id=self.team.pk,
- distinct_ids=["person3"],
- properties={"email": "[email protected]"},
- )
- create_person_distinct_id(self.team.pk, "person1", str(person.uuid))
-
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "val"},
- )
- _create_event(
- event="sign up",
- distinct_id="person2",
- team=self.team,
- properties={"key": "val"},
- )
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "breakdown": "email",
- "breakdown_type": "person",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- "properties": [
- {
- "key": "email",
- "value": "@posthog.com",
- "operator": "not_icontains",
- "type": "person",
- },
- {"key": "key", "value": "val"},
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(len(response), 1)
- self.assertEqual(response[0]["breakdown_value"], "[email protected]")
-
- @snapshot_clickhouse_queries
- @also_test_with_materialized_columns(event_properties=["key"], person_properties=["email", "$os", "$browser"])
- def test_trend_breakdown_user_props_with_filter_with_partial_property_pushdowns(self):
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person1"],
- properties={
- "email": "[email protected]",
- "$os": "ios",
- "$browser": "chrome",
- },
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person2"],
- properties={"email": "[email protected]", "$os": "ios", "$browser": "safari"},
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person3"],
- properties={
- "email": "[email protected]",
- "$os": "android",
- "$browser": "chrome",
- },
- )
- # a second person with same properties, just so snapshot passes on different CH versions (indeterminate sorting currently)
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person32"],
- properties={
- "email": "[email protected]",
- "$os": "android",
- "$browser": "chrome",
- },
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person4"],
- properties={
- "email": "[email protected]",
- "$os": "android",
- "$browser": "safari",
- },
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person5"],
- properties={
- "email": "[email protected]",
- "$os": "android",
- "$browser": "safari",
- },
- )
- _create_person(
- team_id=self.team.pk,
- distinct_ids=["person6"],
- properties={
- "email": "[email protected]",
- "$os": "android",
- "$browser": "safari",
- },
- )
-
- journeys_for(
- team=self.team,
- create_people=False,
- events_by_person={
- "person1": [
- {
- "event": "sign up",
- "properties": {"key": "val"},
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- "person2": [
- {
- "event": "sign up",
- "properties": {"key": "val"},
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- "person3": [
- {
- "event": "sign up",
- "properties": {"key": "val"},
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- "person32": [
- {
- "event": "sign up",
- "properties": {"key": "val"},
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- "person4": [
- {
- "event": "sign up",
- "properties": {"key": "val"},
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- "person5": [
- {
- "event": "sign up",
- "properties": {"key": "val"},
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- "person6": [
- {
- "event": "sign up",
- "properties": {"key": "val"},
- "timestamp": datetime(2020, 5, 1, 0),
- }
- ],
- },
- )
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01 00:00:00",
- "date_to": "2020-07-01 00:00:00",
- "breakdown": "email",
- "breakdown_type": "person",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- "properties": {
- "type": "AND",
- "values": [
- {
- "type": "OR",
- "values": [
- {
- "key": "email",
- "value": "@posthog.com",
- "operator": "not_icontains",
- "type": "person",
- },
- {"key": "key", "value": "val"},
- ],
- },
- {
- "type": "OR",
- "values": [
- {
- "key": "$os",
- "value": "android",
- "operator": "exact",
- "type": "person",
- },
- {
- "key": "$browser",
- "value": "safari",
- "operator": "exact",
- "type": "person",
- },
- ],
- },
- ],
- },
- },
- ),
- self.team,
- )
- response = sorted(response, key=lambda item: item["breakdown_value"])
- self.assertEqual(len(response), 5)
- # person1 shouldn't be selected because it doesn't match the filter
- self.assertEqual(response[0]["breakdown_value"], "[email protected]")
- self.assertEqual(response[1]["breakdown_value"], "[email protected]")
- self.assertEqual(response[2]["breakdown_value"], "[email protected]")
- self.assertEqual(response[3]["breakdown_value"], "[email protected]")
- self.assertEqual(response[4]["breakdown_value"], "[email protected]")
-
- # now have more strict filters with entity props
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01 00:00:00",
- "date_to": "2020-07-01 00:00:00",
- "breakdown": "email",
- "breakdown_type": "person",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- "properties": {
- "type": "AND",
- "values": [
- {"key": "key", "value": "val"},
- {
- "key": "email",
- "value": "@posthog.com",
- "operator": "icontains",
- "type": "person",
- },
- ],
- },
- }
- ],
- "properties": {
- "type": "AND",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "$os",
- "value": "android",
- "operator": "exact",
- "type": "person",
- },
- {
- "key": "$browser",
- "value": "chrome",
- "operator": "exact",
- "type": "person",
- },
- ],
- }
- ],
- },
- },
- ),
- self.team,
- )
- self.assertEqual(len(response), 1)
- self.assertEqual(response[0]["breakdown_value"], "[email protected]")
-
- def _create_active_users_events(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p0"], properties={"name": "p1"})
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p0",
- timestamp="2020-01-03T11:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p0",
- timestamp="2020-01-03T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "bor"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-10T12:00:00Z",
- properties={"key": "bor"},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "bor"},
- )
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p0",
- timestamp="2020-01-12T12:00:00Z",
- properties={"key": "val"},
- )
-
- @snapshot_clickhouse_queries
- def test_weekly_active_users_aggregated_range_wider_than_week(self):
- self._create_active_users_events()
-
- data = {
- "date_from": "2020-01-01",
- "date_to": "2020-01-18",
- "display": TRENDS_TABLE,
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- # Only p0 was active on 2020-01-18 or in the preceding 6 days
- self.assertEqual(result[0]["aggregated_value"], 1)
-
- @snapshot_clickhouse_queries
- def test_weekly_active_users_aggregated_range_wider_than_week_with_sampling(self):
- self._create_active_users_events()
-
- data = {
- "sampling_factor": 1,
- "date_from": "2020-01-01",
- "date_to": "2020-01-18",
- "display": TRENDS_TABLE,
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- # Only p0 was active on 2020-01-18 or in the preceding 6 days
- self.assertEqual(result[0]["aggregated_value"], 1)
-
- @snapshot_clickhouse_queries
- def test_weekly_active_users_aggregated_range_narrower_than_week(self):
- self._create_active_users_events()
-
- data = {
- "date_from": "2020-01-11",
- "date_to": "2020-01-12",
- "display": TRENDS_TABLE,
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- # All were active on 2020-01-12 or in the preceding 6 days
- self.assertEqual(result[0]["aggregated_value"], 3)
-
- @also_test_with_different_timezones
- @snapshot_clickhouse_queries
- def test_weekly_active_users_monthly(self):
- self._create_active_users_events()
-
- data = {
- "date_from": "2019-12-01",
- "date_to": "2020-02-29", # T'was a leap year
- "interval": "month",
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- self.assertEqual(result[0]["days"], ["2019-12-01", "2020-01-01", "2020-02-01"])
- # No users fall into the period of 7 days during or before the first day of any of those three months
- self.assertEqual(result[0]["data"], [0.0, 0.0, 0.0])
-
- @also_test_with_different_timezones
- @snapshot_clickhouse_queries
- def test_weekly_active_users_daily(self):
- self._create_active_users_events()
-
- data = {
- "date_from": "2020-01-08",
- "date_to": "2020-01-19",
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- self.assertEqual(
- result[0]["days"],
- [
- "2020-01-08",
- "2020-01-09",
- "2020-01-10",
- "2020-01-11",
- "2020-01-12",
- "2020-01-13",
- "2020-01-14",
- "2020-01-15",
- "2020-01-16",
- "2020-01-17",
- "2020-01-18",
- "2020-01-19",
- ],
- )
- self.assertEqual(
- result[0]["data"],
- [
- 1.0, # 2020-01-08 - p0 only
- 3.0, # 2020-01-09 - p0, p1, and p2
- 2.0, # 2020-01-10 - p1, and p2
- 2.0, # 2020-01-11 - p1 and p2
- 3.0, # 2020-01-12 - p0, p1, and p2
- 3.0, # 2020-01-13 - p0, p1, and p2
- 3.0, # 2020-01-14 - p0, p1, and p2
- 3.0, # 2020-01-15 - p0, p1, and p2
- 3.0, # 2020-01-16 - p0, p1, and p2
- 3.0, # 2020-01-17 - p0, p1, and p2
- 1.0, # 2020-01-18 - p0 only
- 0.0, # 2020-01-19 - nobody
- ],
- )
-
- @also_test_with_different_timezones
- def test_weekly_active_users_daily_based_on_action(self):
- action = _create_action(name="$pageview", team=self.team)
- self._create_active_users_events()
-
- data = {
- "date_from": "2020-01-08",
- "date_to": "2020-01-19",
- "actions": [
- {
- "id": action.id,
- "type": "actions",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- self.assertEqual(
- result[0]["days"],
- [
- "2020-01-08",
- "2020-01-09",
- "2020-01-10",
- "2020-01-11",
- "2020-01-12",
- "2020-01-13",
- "2020-01-14",
- "2020-01-15",
- "2020-01-16",
- "2020-01-17",
- "2020-01-18",
- "2020-01-19",
- ],
- )
- # Same as test_weekly_active_users_daily
- self.assertEqual(
- result[0]["data"],
- [1.0, 3.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 1.0, 0.0],
- )
-
- @also_test_with_different_timezones
- @snapshot_clickhouse_queries
- def test_weekly_active_users_weekly(self):
- self._create_active_users_events()
-
- data = {
- "date_from": "2019-12-29",
- "date_to": "2020-01-18",
- "interval": "week",
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- self.assertEqual(result[0]["days"], ["2019-12-29", "2020-01-05", "2020-01-12"])
- self.assertEqual(result[0]["data"], [0.0, 1.0, 3.0])
-
- @snapshot_clickhouse_queries
- def test_weekly_active_users_hourly(self):
- self._create_active_users_events()
-
- data = {
- "date_from": "2020-01-09T06:00:00Z",
- "date_to": "2020-01-09T17:00:00Z",
- "interval": "hour",
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- self.assertEqual(
- result[0]["days"],
- [
- "2020-01-09 06:00:00",
- "2020-01-09 07:00:00",
- "2020-01-09 08:00:00",
- "2020-01-09 09:00:00",
- "2020-01-09 10:00:00",
- "2020-01-09 11:00:00",
- "2020-01-09 12:00:00",
- "2020-01-09 13:00:00",
- "2020-01-09 14:00:00",
- "2020-01-09 15:00:00",
- "2020-01-09 16:00:00",
- "2020-01-09 17:00:00",
- ],
- )
-
- # p0 falls out of the window at noon, p1 and p2 are counted because the next 24 hours are included.
- # FIXME: This is isn't super intuitive, in particular for hour-by-hour queries, but currently
- # necessary, because there's a presentation issue: in monthly/weekly graphs data points are formatted as
- # D-MMM-YYYY, so if a user sees e.g. 1-Jan-2077, they'll likely expect the active users count to be for
- # the first day of the month, and not the last. If they saw just Jan-2077, the more general case would work.
- self.assertEqual(
- result[0]["data"],
- [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0],
- )
-
- def test_weekly_active_users_daily_based_on_action_with_zero_person_ids(self):
- # only a person-on-event test
- if not get_instance_setting("PERSON_ON_EVENTS_ENABLED"):
- return True
-
- action = _create_action(name="$pageview", team=self.team)
- self._create_active_users_events()
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p5",
- timestamp="2020-01-03T12:00:00Z",
- properties={"key": "val"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p6",
- timestamp="2020-01-03T12:00:00Z",
- properties={"key": "val"},
- person_id="00000000-0000-0000-0000-000000000000",
- )
-
- data = {
- "date_from": "2020-01-08",
- "date_to": "2020-01-19",
- "actions": [
- {
- "id": action.id,
- "type": "actions",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- # Zero person IDs shouldn't be counted
- self.assertEqual(
- result[0]["data"],
- [1.0, 3.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 1.0, 0.0],
- )
-
- @also_test_with_materialized_columns(["key"])
- def test_breakdown_weekly_active_users_daily(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-10T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- data = {
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "key",
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- self.assertEqual(
- result[0]["data"],
- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 0.0],
- )
-
- @also_test_with_materialized_columns(person_properties=["name"])
- @snapshot_clickhouse_queries
- def test_weekly_active_users_filtering(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "person-1"})
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "person-2"})
- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"name": "person-3"})
-
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-10T12:00:00Z",
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p3",
- timestamp="2020-01-11T12:00:00Z",
- )
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- "properties": [
- {
- "key": "name",
- "operator": "exact",
- "value": ["person-1", "person-2"],
- "type": "person",
- }
- ],
- },
- )
-
- result = Trends().run(filter, self.team)
- self.assertEqual(
- result[0]["data"],
- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 2.0, 2.0],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_weekly_active_users_daily_based_on_action(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-10T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"name": "p3"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p3",
- timestamp="2020-01-09T12:00:00Z",
- properties={"key": "val"},
- )
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p3",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- cohort = Cohort.objects.create(
- team=self.team,
- groups=[
- {
- "properties": [
- {
- "key": "name",
- "operator": "exact",
- "value": ["p1", "p2"],
- "type": "person",
- }
- ]
- }
- ],
- )
-
- pageview_action = _create_action(
- name="$pageview",
- team=self.team,
- properties=[
- {
- "key": "name",
- "operator": "exact",
- "value": ["p1", "p2", "p3"],
- "type": "person",
- },
- {"type": "cohort", "key": "id", "value": cohort.pk},
- ],
- )
-
- data = {
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "key",
- "actions": [
- {
- "id": pageview_action.id,
- "type": "actions",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- self.assertEqual(
- result[0]["data"],
- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 0.0],
- )
-
- @also_test_with_materialized_columns(["key"])
- @snapshot_clickhouse_queries
- def test_breakdown_weekly_active_users_aggregated(self):
- self._create_active_users_events()
-
- data = {
- "date_from": "2020-01-11",
- "date_to": "2020-01-11",
- "display": TRENDS_TABLE,
- "events": [
- {
- "id": "$pageview",
- "type": "events",
- "order": 0,
- "math": "weekly_active",
- }
- ],
- "breakdown": "key",
- }
-
- filter = Filter(team=self.team, data=data)
- result = Trends().run(filter, self.team)
- # All were active on 2020-01-12 or in the preceding 6 days
- self.assertEqual(len(result), 2)
- self.assertEqual(result[0]["breakdown_value"], "bor")
- self.assertEqual(result[0]["aggregated_value"], 2)
- self.assertEqual(result[1]["breakdown_value"], "val")
- self.assertEqual(result[1]["aggregated_value"], 2)
-
- @also_test_with_materialized_columns(event_properties=["key"], person_properties=["name"])
- def test_filter_test_accounts(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-11T12:00:00Z",
- properties={"key": "val"},
- )
- self.team.test_account_filters = [{"key": "name", "value": "p1", "operator": "is_not", "type": "person"}]
- self.team.save()
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "filter_test_accounts": "true",
- },
- )
- result = Trends().run(filter, self.team)
- self.assertEqual(result[0]["count"], 1)
- filter2 = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- },
- )
- result = Trends().run(filter2, self.team)
- self.assertEqual(result[0]["count"], 2)
- result = Trends().run(filter.shallow_clone({"breakdown": "key"}), self.team)
- self.assertEqual(result[0]["count"], 1)
-
- @also_test_with_materialized_columns(["$some_property"])
- def test_breakdown_filtering_bar_chart_by_value(self):
- self._create_events()
-
- # test breakdown filtering
- with freeze_time("2020-01-04T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "breakdown": "$some_property",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- "display": TRENDS_BAR_VALUE,
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["aggregated_value"], 2) # the events without breakdown value
- self.assertEqual(response[1]["aggregated_value"], 1)
- self.assertEqual(response[2]["aggregated_value"], 1)
- self.assertEqual(
- response[0]["days"],
- [
- "2019-12-28",
- "2019-12-29",
- "2019-12-30",
- "2019-12-31",
- "2020-01-01",
- "2020-01-02",
- "2020-01-03",
- "2020-01-04",
- ],
- )
-
- @also_test_with_materialized_columns(person_properties=["key", "key_2"], verify_no_jsonextract=False)
- def test_breakdown_multiple_cohorts(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"key": "value"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-02T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"key_2": "value_2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-02T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"key_2": "value_2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p3",
- timestamp="2020-01-02T12:00:00Z",
- properties={"key": "val"},
- )
-
- cohort1 = _create_cohort(
- team=self.team,
- name="cohort_1",
- groups=[{"properties": [{"key": "key", "value": "value", "type": "person"}]}],
- )
- cohort2 = _create_cohort(
- team=self.team,
- name="cohort_2",
- groups=[{"properties": [{"key": "key_2", "value": "value_2", "type": "person"}]}],
- )
-
- # try different versions
- cohort1.calculate_people_ch(pending_version=1)
- cohort2.calculate_people_ch(pending_version=0)
-
- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True): # Normally this is False in tests
- with freeze_time("2020-01-04T13:01:01Z"):
- res = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "events": [{"id": "$pageview"}],
- "properties": [],
- "breakdown": [cohort1.pk, cohort2.pk],
- "breakdown_type": "cohort",
- },
- ),
- self.team,
- )
-
- self.assertEqual(res[0]["count"], 2)
- self.assertEqual(res[1]["count"], 1)
-
- @also_test_with_materialized_columns(person_properties=["key", "key_2"], verify_no_jsonextract=False)
- def test_breakdown_single_cohort(self):
- _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"key": "value"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p1",
- timestamp="2020-01-02T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"key_2": "value_2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p2",
- timestamp="2020-01-02T12:00:00Z",
- properties={"key": "val"},
- )
-
- _create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"key_2": "value_2"})
- _create_event(
- team=self.team,
- event="$pageview",
- distinct_id="p3",
- timestamp="2020-01-02T12:00:00Z",
- properties={"key": "val"},
- )
-
- cohort1 = _create_cohort(
- team=self.team,
- name="cohort_1",
- groups=[{"properties": [{"key": "key", "value": "value", "type": "person"}]}],
- )
-
- cohort1.calculate_people_ch(pending_version=0)
-
- with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True): # Normally this is False in tests
- with freeze_time("2020-01-04T13:01:01Z"):
- res = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "events": [{"id": "$pageview"}],
- "properties": [],
- "breakdown": cohort1.pk,
- "breakdown_type": "cohort",
- },
- ),
- self.team,
- )
-
- self.assertEqual(res[0]["count"], 1)
-
- @also_test_with_materialized_columns(["key", "$current_url"])
- def test_filtering_with_action_props(self):
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "val", "$current_url": "/some/page"},
- )
- _create_event(
- event="sign up",
- distinct_id="person2",
- team=self.team,
- properties={"key": "val", "$current_url": "/some/page"},
- )
- _create_event(
- event="sign up",
- distinct_id="person3",
- team=self.team,
- properties={"key": "val", "$current_url": "/another/page"},
- )
-
- action = Action.objects.create(
- name="sign up",
- team=self.team,
- steps_json=[
- {
- "event": "sign up",
- "url": "/some/page",
- "properties": [{"key": "key", "type": "event", "value": ["val"], "operator": "exact"}],
- }
- ],
- )
-
- response = Trends().run(
- Filter(
- data={
- "date_from": "-14d",
- "actions": [{"id": action.pk, "type": "actions", "order": 0}],
- }
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["count"], 2)
-
- def test_trends_math_without_math_property(self):
- with self.assertRaises(ValidationError):
- Trends().run(Filter(data={"events": [{"id": "sign up", "math": "sum"}]}), self.team)
-
- @patch("posthog.queries.trends.trends.insight_sync_execute")
- def test_should_throw_exception(self, patch_sync_execute):
- self._create_events()
- patch_sync_execute.side_effect = Exception()
- # test breakdown filtering
- with self.assertRaises(Exception):
- with self.settings(TEST=False, DEBUG=False):
- Trends().run(
- Filter(
- data={
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ]
- }
- ),
- self.team,
- )
-
- @also_test_with_different_timezones
- @snapshot_clickhouse_queries
- def test_timezones_hourly_relative_from(self):
- _create_person(team_id=self.team.pk, distinct_ids=["blabla"], properties={})
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-04T22:01:01",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-05T07:01:01",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-05T08:01:01",
- )
-
- query_time = datetime(2020, 1, 5, 10, 1, 1, tzinfo=ZoneInfo(self.team.timezone))
- assert query_time.tzinfo is not None
- utc_offset = query_time.tzinfo.utcoffset(query_time)
- assert utc_offset is not None
- utc_offset_hours = utc_offset.total_seconds() // 3600
- utc_offset_sign = "-" if utc_offset_hours < 0 else "+"
- with freeze_time(query_time):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "dStart",
- "interval": "hour",
- "events": [{"id": "sign up", "name": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
- self.assertEqual(
- response[0]["labels"],
- [
- "5-Jan-2020 00:00",
- "5-Jan-2020 01:00",
- "5-Jan-2020 02:00",
- "5-Jan-2020 03:00",
- "5-Jan-2020 04:00",
- "5-Jan-2020 05:00",
- "5-Jan-2020 06:00",
- "5-Jan-2020 07:00",
- "5-Jan-2020 08:00",
- "5-Jan-2020 09:00",
- "5-Jan-2020 10:00",
- ],
- )
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 0, 0, 0, 1, 1, 0, 0])
-
- assert dict(parse_qsl(urlparse(response[0]["persons_urls"][7]["url"]).query)) == {
- "breakdown_attribution_type": "first_touch",
- "breakdown_normalize_url": "False",
- "date_from": f"2020-01-05T07:00:00{utc_offset_sign}{abs(utc_offset_hours):02.0f}:00",
- "date_to": f"2020-01-05T08:00:00{utc_offset_sign}{abs(utc_offset_hours):02.0f}:00",
- "display": "ActionsLineGraph",
- "entity_id": "sign up",
- "entity_math": "dau",
- "entity_type": "events",
- "events": '[{"id": "sign up", "type": "events", "order": null, "name": "sign '
- 'up", "custom_name": null, "math": "dau", "math_property": null, "math_property_revenue_currency": null, '
- '"math_hogql": null, "math_group_type_index": null, "properties": {}, '
- '"id_field": null, "timestamp_field": null, "distinct_id_field": null, "table_name": null}]',
- "insight": "TRENDS",
- "interval": "hour",
- "smoothing_intervals": "1",
- "cache_invalidation_key": ANY,
- }
- persons = self.client.get("/" + response[0]["persons_urls"][7]["url"]).json()
- self.assertEqual(persons["results"][0]["count"], 1)
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "dStart",
- "interval": "hour",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(
- response[0]["labels"],
- [
- "5-Jan-2020 00:00",
- "5-Jan-2020 01:00",
- "5-Jan-2020 02:00",
- "5-Jan-2020 03:00",
- "5-Jan-2020 04:00",
- "5-Jan-2020 05:00",
- "5-Jan-2020 06:00",
- "5-Jan-2020 07:00",
- "5-Jan-2020 08:00",
- "5-Jan-2020 09:00",
- "5-Jan-2020 10:00",
- ],
- )
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 0, 0, 0, 1, 1, 0, 0])
-
- @also_test_with_different_timezones
- def test_timezones_hourly_absolute_from(self):
- _create_person(team_id=self.team.pk, distinct_ids=["blabla"], properties={})
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-02T17:01:01",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-03T17:01:01",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-06T00:30:01", # Shouldn't be included anywhere
- )
-
- # Custom date range, single day, hourly interval
- response = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-03 23:59:59",
- "interval": "hour",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- team=self.team,
- ),
- self.team,
- )
-
- self.assertEqual(
- response[0]["days"],
- [
- "2020-01-03 00:00:00",
- "2020-01-03 01:00:00",
- "2020-01-03 02:00:00",
- "2020-01-03 03:00:00",
- "2020-01-03 04:00:00",
- "2020-01-03 05:00:00",
- "2020-01-03 06:00:00",
- "2020-01-03 07:00:00",
- "2020-01-03 08:00:00",
- "2020-01-03 09:00:00",
- "2020-01-03 10:00:00",
- "2020-01-03 11:00:00",
- "2020-01-03 12:00:00",
- "2020-01-03 13:00:00",
- "2020-01-03 14:00:00",
- "2020-01-03 15:00:00",
- "2020-01-03 16:00:00",
- "2020-01-03 17:00:00",
- "2020-01-03 18:00:00",
- "2020-01-03 19:00:00",
- "2020-01-03 20:00:00",
- "2020-01-03 21:00:00",
- "2020-01-03 22:00:00",
- "2020-01-03 23:00:00",
- ],
- )
- self.assertEqual(response[0]["data"][17], 1)
- self.assertEqual(len(response[0]["data"]), 24)
-
- # Custom date range, single day, dayly interval
- response = Trends().run(
- Filter(
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-03",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- team=self.team,
- ),
- self.team,
- )
- self.assertEqual(response[0]["data"], [1.0])
-
- @also_test_with_different_timezones
- @snapshot_clickhouse_queries
- def test_timezones_daily(self):
- _create_person(team_id=self.team.pk, distinct_ids=["blabla"], properties={})
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-02T17:01:01",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-03T17:01:01",
- )
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-06T00:30:01", # Shouldn't be included anywhere
- )
-
- with freeze_time(datetime(2020, 1, 5, 5, 0, tzinfo=ZoneInfo(self.team.timezone))):
- response = Trends().run(
- Filter(
- data={
- "date_from": "-7d",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- team=self.team,
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0])
- self.assertEqual(
- response[0]["labels"],
- [
- "29-Dec-2019",
- "30-Dec-2019",
- "31-Dec-2019",
- "1-Jan-2020",
- "2-Jan-2020",
- "3-Jan-2020",
- "4-Jan-2020",
- "5-Jan-2020",
- ],
- )
-
- # DAU
- with freeze_time("2020-01-05T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "events": [{"id": "sign up", "name": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
- self.assertEqual(
- response[0]["data"],
- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0],
- )
- self.assertEqual(
- response[0]["labels"],
- [
- "22-Dec-2019",
- "23-Dec-2019",
- "24-Dec-2019",
- "25-Dec-2019",
- "26-Dec-2019",
- "27-Dec-2019",
- "28-Dec-2019",
- "29-Dec-2019",
- "30-Dec-2019",
- "31-Dec-2019",
- "1-Jan-2020",
- "2-Jan-2020",
- "3-Jan-2020",
- "4-Jan-2020",
- "5-Jan-2020",
- ],
- )
-
- with freeze_time("2020-01-05T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "math": "weekly_active",
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0])
- self.assertEqual(
- response[0]["labels"],
- [
- "29-Dec-2019",
- "30-Dec-2019",
- "31-Dec-2019",
- "1-Jan-2020",
- "2-Jan-2020",
- "3-Jan-2020",
- "4-Jan-2020",
- "5-Jan-2020",
- ],
- )
-
- with freeze_time("2020-01-05T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "events": [{"id": "sign up", "name": "sign up", "breakdown": "$os"}],
- },
- ),
- self.team,
- )
-
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0])
- self.assertEqual(
- response[0]["labels"],
- [
- "29-Dec-2019",
- "30-Dec-2019",
- "31-Dec-2019",
- "1-Jan-2020",
- "2-Jan-2020",
- "3-Jan-2020",
- "4-Jan-2020",
- "5-Jan-2020",
- ],
- )
-
- # breakdown + DAU
- with freeze_time("2020-01-05T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-7d",
- "breakdown": "$os",
- "events": [{"id": "sign up", "name": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0])
-
- # Regression test to ensure we handle non-deterministic timezones correctly
- # US/Pacific for example changes from PST to PDT due to Daylight Savings Time
- # In 2022, this happened on November 6, and previously we had a bug where
- # a graph starting before that date and ending after it would show all 0s
- # after November 6. Thus, this test ensures that doesn't happen
- @snapshot_clickhouse_queries
- def test_non_deterministic_timezones(self):
- self.team.timezone = "US/Pacific"
- self.team.save()
- _create_person(team_id=self.team.pk, distinct_ids=["blabla"], properties={})
- with freeze_time("2022-11-03T01:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- )
-
- with freeze_time("2022-11-10T01:01:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- )
-
- with freeze_time("2022-11-17T08:30:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- )
-
- with freeze_time("2022-11-24T08:30:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- )
-
- with freeze_time("2022-11-30T08:30:01Z"):
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- )
-
- with freeze_time("2022-11-30T13:01:01Z"):
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-30d",
- "events": [{"id": "sign up", "name": "sign up", "math": "wau"}],
- "interval": "week",
- },
- ),
- self.team,
- )
-
- # The key is to not get any 0s here
- self.assertEqual(response[0]["data"], [1.0, 1.0, 1.0, 1.0, 1.0])
-
- @also_test_with_different_timezones
- @snapshot_clickhouse_queries
- def test_timezones_weekly(self):
- _create_person(team_id=self.team.pk, distinct_ids=["blabla"], properties={})
- _create_event( # This event is before the time range (but counts towards week of 2020-01-06 in Monday mode)
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-11T19:01:01", # Saturday; TRICKY: This is the next UTC day in America/Phoenix
- )
- _create_event( # This event should count towards week of 2020-01-12 (or 2020-01-06 in Monday mode)
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-12T02:01:01", # Sunday; TRICKY: This is the previous UTC day in Asia/Tokyo
- )
- _create_event( # This event should count towards week of 2020-01-19 (or 2020-01-20 in Monday mode)
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "second url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-21T18:01:01", # Tuesday; TRICKY: This is the next UTC day in America/Phoenix
- )
-
- self.team.week_start_day = 0 # DB value for WeekStartDay.SUNDAY (the default, but let's be explicit)
- self.team.save()
-
- # TRICKY: This is the previous UTC day in Asia/Tokyo
- with freeze_time(datetime(2020, 1, 26, 3, 0, tzinfo=ZoneInfo(self.team.timezone))):
- # Total volume query
- response_sunday = Trends().run(
- Filter(
- data={
- "date_from": "-14d",
- "interval": "week",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- team=self.team,
- ),
- self.team,
- )
-
- self.assertEqual(response_sunday[0]["days"], ["2020-01-12", "2020-01-19", "2020-01-26"])
- self.assertEqual(response_sunday[0]["data"], [1.0, 1.0, 0.0])
-
- self.team.week_start_day = 1 # DB value for WeekStartDay.MONDAY
- self.team.save()
-
- # TRICKY: This is the previous UTC day in Asia/Tokyo
- with freeze_time(datetime(2020, 1, 26, 3, 0, tzinfo=ZoneInfo(self.team.timezone))):
- # Total volume query
- response_monday = Trends().run(
- Filter(
- data={
- "date_from": "-14d",
- "interval": "week",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- team=self.team,
- ),
- self.team,
- )
-
- self.assertEqual(response_monday[0]["days"], ["2020-01-06", "2020-01-13", "2020-01-20"])
- self.assertEqual(response_monday[0]["data"], [2.0, 0.0, 1.0])
-
- def test_same_day(self):
- _create_person(team_id=self.team.pk, distinct_ids=["blabla"], properties={})
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="blabla",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-03T01:01:01Z",
- )
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-03",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["data"], [1.0])
-
- @override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=True)
- @snapshot_clickhouse_queries
- def test_same_day_with_person_on_events_v2(self):
- person_id1 = str(uuid.uuid4())
- person_id2 = str(uuid.uuid4())
-
- _create_person(team_id=self.team.pk, distinct_ids=["distinctid1"], properties={})
- _create_person(team_id=self.team.pk, distinct_ids=["distinctid2"], properties={})
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="distinctid1",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-03T01:01:01Z",
- person_id=person_id1,
- )
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="distinctid2",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-03T01:01:01Z",
- person_id=person_id2,
- )
-
- create_person_id_override_by_distinct_id("distinctid1", "distinctid2", self.team.pk)
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-03",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["data"], [2.0])
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-03",
- "events": [{"id": "sign up", "name": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["data"], [1.0])
-
- @override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=True)
- @snapshot_clickhouse_queries
- def test_same_day_with_person_on_events_v2_latest_override(self):
- # In this test we check that we always prioritize the latest override (based on the `version`)
- # To do so, we first create an override to a person 2 that did not perform the event we're building
- # the insight on, which should lead us to have 2 DAUs. We then create an override to a person 3 that did
- # have the event, which should lead us to have 1 DAU only, since persons 1 and 3 are now the same person.
- # Lastly, we create an override back to person 2 and check that DAUs go back to 2.
- person_id1 = str(uuid.uuid4())
- person_id2 = str(uuid.uuid4())
- person_id3 = str(uuid.uuid4())
-
- _create_person(team_id=self.team.pk, distinct_ids=["distinctid1"], properties={})
- _create_person(team_id=self.team.pk, distinct_ids=["distinctid2"], properties={})
- _create_person(team_id=self.team.pk, distinct_ids=["distinctid3"], properties={})
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="distinctid1",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-03T01:01:01Z",
- person_id=person_id1,
- )
-
- _create_event(
- team=self.team,
- event="some other event",
- distinct_id="distinctid2",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-03T01:01:01Z",
- person_id=person_id2,
- )
-
- _create_event(
- team=self.team,
- event="sign up",
- distinct_id="distinctid3",
- properties={
- "$current_url": "first url",
- "$browser": "Firefox",
- "$os": "Mac",
- },
- timestamp="2020-01-03T01:01:01Z",
- person_id=person_id3,
- )
-
- create_person_id_override_by_distinct_id("distinctid1", "distinctid2", self.team.pk, 0)
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-03",
- "events": [{"id": "sign up", "name": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["data"], [2.0])
-
- create_person_id_override_by_distinct_id("distinctid1", "distinctid3", self.team.pk, 1)
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-03",
- "events": [{"id": "sign up", "name": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["data"], [1.0])
-
- create_person_id_override_by_distinct_id("distinctid1", "distinctid2", self.team.pk, 2)
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-03",
- "date_to": "2020-01-03",
- "events": [{"id": "sign up", "name": "sign up", "math": "dau"}],
- },
- ),
- self.team,
- )
- self.assertEqual(response[0]["data"], [2.0])
-
- @also_test_with_materialized_columns(event_properties=["email", "name"], person_properties=["email", "name"])
- def test_ilike_regression_with_current_clickhouse_version(self):
- # CH upgrade to 22.3 has this problem: https://github.com/ClickHouse/ClickHouse/issues/36279
- # While we're waiting to upgrade to a newer version, a workaround is to set `optimize_move_to_prewhere = 0`
- # Only happens in the materialized version
-
- # The requirements to end up in this case is
- # 1. Having a JOIN
- # 2. Having multiple properties that filter on the same value
-
- with freeze_time("2020-01-04T13:01:01Z"):
- Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "-14d",
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- "order": 0,
- }
- ],
- "properties": [
- {
- "key": "email",
- "type": "event",
- "value": "posthog.com",
- "operator": "not_icontains",
- },
- {
- "key": "name",
- "type": "event",
- "value": "posthog.com",
- "operator": "not_icontains",
- },
- {
- "key": "name",
- "type": "person",
- "value": "posthog.com",
- "operator": "not_icontains",
- },
- ],
- },
- ),
- self.team,
- )
-
- @also_test_with_person_on_events_v2
- @snapshot_clickhouse_queries
- def test_trends_count_per_user_average_daily(self):
- self._create_event_count_per_actor_events()
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "events": [{"id": "viewed video", "math": "avg_count_per_actor"}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 1
- assert daily_response[0]["days"] == [
- "2020-01-01",
- "2020-01-02",
- "2020-01-03",
- "2020-01-04",
- "2020-01-05",
- "2020-01-06",
- "2020-01-07",
- ]
- assert daily_response[0]["data"] == [1.5, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0]
-
- def test_trends_count_per_user_average_weekly(self):
- self._create_event_count_per_actor_events()
-
- weekly_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "events": [{"id": "viewed video", "math": "avg_count_per_actor"}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- "interval": "week",
- },
- ),
- self.team,
- )
-
- assert len(weekly_response) == 1
- assert weekly_response[0]["days"] == ["2019-12-29", "2020-01-05"]
- assert weekly_response[0]["data"] == [1.3333333333333333, 2.0]
-
- @also_test_with_person_on_events_v2
- @snapshot_clickhouse_queries
- def test_trends_count_per_user_average_aggregated(self):
- self._create_event_count_per_actor_events()
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "events": [{"id": "viewed video", "math": "avg_count_per_actor"}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 1
- assert daily_response[0]["aggregated_value"] == 2.6666666666666665 # 8 events divided by 3 users
-
- def test_trends_count_per_user_maximum(self):
- self._create_event_count_per_actor_events()
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "events": [{"id": "viewed video", "math": "max_count_per_actor"}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 1
- assert daily_response[0]["days"] == [
- "2020-01-01",
- "2020-01-02",
- "2020-01-03",
- "2020-01-04",
- "2020-01-05",
- "2020-01-06",
- "2020-01-07",
- ]
- assert daily_response[0]["data"] == [2.0, 0.0, 0.0, 1.0, 3.0, 0.0, 0.0]
-
- def test_trends_count_per_user_average_with_event_property_breakdown(self):
- self._create_event_count_per_actor_events()
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "breakdown": "color",
- "events": [{"id": "viewed video", "math": "avg_count_per_actor"}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 3
- assert daily_response[0]["breakdown_value"] == "red"
- assert daily_response[1]["breakdown_value"] == "blue"
- assert daily_response[2]["breakdown_value"] == "$$_posthog_breakdown_null_$$"
- assert daily_response[0]["days"] == [
- "2020-01-01",
- "2020-01-02",
- "2020-01-03",
- "2020-01-04",
- "2020-01-05",
- "2020-01-06",
- "2020-01-07",
- ]
- assert daily_response[1]["days"] == daily_response[0]["days"]
- assert daily_response[2]["days"] == daily_response[0]["days"]
- assert daily_response[0]["data"] == [1.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0] # red
- assert daily_response[1]["data"] == [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0] # blue
- assert daily_response[2]["data"] == [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # none
-
- def test_trends_count_per_user_average_with_person_property_breakdown(self):
- self._create_event_count_per_actor_events()
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "breakdown": "fruit",
- "breakdown_type": "person",
- "events": [{"id": "viewed video", "math": "avg_count_per_actor"}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 2
- assert daily_response[0]["breakdown_value"] == "mango"
- assert daily_response[1]["breakdown_value"] == "tomato"
- assert daily_response[0]["days"] == [
- "2020-01-01",
- "2020-01-02",
- "2020-01-03",
- "2020-01-04",
- "2020-01-05",
- "2020-01-06",
- "2020-01-07",
- ]
- assert daily_response[1]["days"] == daily_response[0]["days"]
- assert daily_response[0]["data"] == [2.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0] # red
- assert daily_response[1]["data"] == [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # blue
-
- def test_trends_count_per_user_average_aggregated_with_event_property_breakdown(self):
- self._create_event_count_per_actor_events()
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "breakdown": "color",
- "events": [{"id": "viewed video", "math": "avg_count_per_actor"}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 3
- assert daily_response[0]["breakdown_value"] == "red"
- assert daily_response[1]["breakdown_value"] == "$$_posthog_breakdown_null_$$"
- assert daily_response[2]["breakdown_value"] == "blue"
- assert daily_response[0]["aggregated_value"] == 2.0 # red
- assert daily_response[1]["aggregated_value"] == 1.0 # none
- assert daily_response[2]["aggregated_value"] == 1.0 # blue
-
- @snapshot_clickhouse_queries
- def test_trends_count_per_user_average_aggregated_with_event_property_breakdown_with_sampling(self):
- self._create_event_count_per_actor_events()
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "sampling_factor": 1,
- "display": TRENDS_TABLE,
- "breakdown": "color",
- "events": [{"id": "viewed video", "math": "avg_count_per_actor"}],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 3
- assert daily_response[0]["breakdown_value"] == "red"
- assert daily_response[1]["breakdown_value"] == "$$_posthog_breakdown_null_$$"
- assert daily_response[2]["breakdown_value"] == "blue"
- assert daily_response[0]["aggregated_value"] == 2.0 # red
- assert daily_response[1]["aggregated_value"] == 1.0 # none
- assert daily_response[2]["aggregated_value"] == 1.0 # blue
-
- @snapshot_clickhouse_queries
- def test_trends_count_per_group_average_daily(self):
- self._create_event_count_per_actor_events()
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="shape", group_type_index=0
- )
- create_group(team_id=self.team.pk, group_type_index=0, group_key="bouba")
- create_group(team_id=self.team.pk, group_type_index=0, group_key="kiki")
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "events": [
- {
- "id": "viewed video",
- "math": "avg_count_per_actor",
- "math_group_type_index": 0,
- }
- ],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 1
- assert daily_response[0]["days"] == [
- "2020-01-01",
- "2020-01-02",
- "2020-01-03",
- "2020-01-04",
- "2020-01-05",
- "2020-01-06",
- "2020-01-07",
- ]
- assert daily_response[0]["data"] == [
- 3.0, # 3 group-assigned "viewed video" events by 2 persons / 1 group (bouba)
- 0.0, # No events at all
- 0.0, # No "viewed video" events
- 1.0, # 1 group-assigned "viewed video" event by 1 person / 1 group (kiki)
- 1.5, # 3 group-assigned "viewed video" events by 1 person / 2 groups (bouba, kiki)
- # The group-less event is ignored!
- 0.0, # No events at all
- 0.0, # No events at all
- ]
-
- @snapshot_clickhouse_queries
- def test_trends_count_per_group_average_aggregated(self):
- self._create_event_count_per_actor_events()
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="shape", group_type_index=0
- )
- create_group(team_id=self.team.pk, group_type_index=0, group_key="bouba")
- create_group(team_id=self.team.pk, group_type_index=0, group_key="kiki")
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_TABLE,
- "events": [
- {
- "id": "viewed video",
- "math": "avg_count_per_actor",
- "math_group_type_index": 0,
- }
- ],
- "date_from": "2020-01-01",
- "date_to": "2020-01-07",
- },
- ),
- self.team,
- )
-
- assert len(daily_response) == 1
- assert daily_response[0]["aggregated_value"] == 3.5 # 7 relevant events divided by 2 groups
-
- def test_trends_breakdown_timezone(self):
- self.team.timezone = "US/Pacific"
- self.team.save()
- self._create_event_count_per_actor_events()
-
- with freeze_time("2020-01-03 19:06:34"):
- _create_person(team_id=self.team.pk, distinct_ids=["another_user"])
- _create_event(
- team=self.team,
- event="viewed video",
- distinct_id="another_user",
- properties={"color": "orange"},
- )
-
- daily_response = Trends().run(
- Filter(
- team=self.team,
- data={
- "display": TRENDS_LINEAR,
- "events": [{"id": "viewed video", "math": "dau"}],
- "breakdown": "color",
- "date_from": "2020-01-01",
- "date_to": "2020-03-07",
- "interval": "month",
- },
- ),
- self.team,
- )
-
- # assert len(daily_response) == 4
- assert daily_response[0]["days"] == ["2020-01-01", "2020-02-01", "2020-03-01"]
- assert daily_response[1]["days"] == ["2020-01-01", "2020-02-01", "2020-03-01"]
- assert daily_response[2]["days"] == ["2020-01-01", "2020-02-01", "2020-03-01"]
-
- def _create_groups(self):
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=1
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:5",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:6",
- properties={"industry": "technology"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:7",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=1,
- group_key="company:10",
- properties={"industry": "finance"},
- )
-
- # TODO: Delete this test when moved to person-on-events
- def test_breakdown_with_filter_groups(self):
- self._create_groups()
-
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "oh", "$group_0": "org:7", "$group_1": "company:10"},
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "uh", "$group_0": "org:5"},
- timestamp="2020-01-02T12:00:01Z",
- )
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "uh", "$group_0": "org:6"},
- timestamp="2020-01-02T12:00:02Z",
- )
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "key",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- "properties": [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(len(response), 2)
- self.assertEqual(response[0]["breakdown_value"], "oh")
- self.assertEqual(response[0]["count"], 1)
- self.assertEqual(response[1]["breakdown_value"], "uh")
- self.assertEqual(response[1]["count"], 1)
-
- @snapshot_clickhouse_queries
- def test_breakdown_with_filter_groups_person_on_events(self):
- self._create_groups()
-
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "oh", "$group_0": "org:7", "$group_1": "company:10"},
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "uh", "$group_0": "org:5"},
- timestamp="2020-01-02T12:00:01Z",
- )
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"key": "uh", "$group_0": "org:6"},
- timestamp="2020-01-02T12:00:02Z",
- )
-
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "key",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- }
- ],
- "properties": [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(len(response), 2)
- self.assertEqual(response[0]["breakdown_value"], "oh")
- self.assertEqual(response[0]["count"], 1)
- self.assertEqual(response[1]["breakdown_value"], "uh")
- self.assertEqual(response[1]["count"], 1)
-
- @override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=True)
- @snapshot_clickhouse_queries
- def test_breakdown_with_filter_groups_person_on_events_v2(self):
- self._create_groups()
-
- id1 = str(uuid.uuid4())
- id2 = str(uuid.uuid4())
- _create_event(
- event="sign up",
- distinct_id="test_breakdown_d1",
- team=self.team,
- properties={"key": "oh", "$group_0": "org:7", "$group_1": "company:10"},
- timestamp="2020-01-02T12:00:00Z",
- person_id=id1,
- )
- _create_event(
- event="sign up",
- distinct_id="test_breakdown_d1",
- team=self.team,
- properties={"key": "uh", "$group_0": "org:5"},
- timestamp="2020-01-02T12:00:01Z",
- person_id=id1,
- )
- _create_event(
- event="sign up",
- distinct_id="test_breakdown_d1",
- team=self.team,
- properties={"key": "uh", "$group_0": "org:6"},
- timestamp="2020-01-02T12:00:02Z",
- person_id=id1,
- )
- _create_event(
- event="sign up",
- distinct_id="test_breakdown_d2",
- team=self.team,
- properties={"key": "uh", "$group_0": "org:6"},
- timestamp="2020-01-02T12:00:02Z",
- person_id=id2,
- )
-
- create_person_id_override_by_distinct_id("test_breakdown_d1", "test_breakdown_d2", self.team.pk)
- response = Trends().run(
- Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "key",
- "events": [
- {
- "id": "sign up",
- "name": "sign up",
- "type": "events",
- "order": 0,
- "math": "dau",
- }
- ],
- "properties": [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- }
- ],
- },
- ),
- self.team,
- )
-
- self.assertEqual(len(response), 2)
- self.assertEqual(response[0]["breakdown_value"], "oh")
- self.assertEqual(response[0]["count"], 1)
- self.assertEqual(response[1]["breakdown_value"], "uh")
- self.assertEqual(response[1]["count"], 1)
-
- # TODO: Delete this test when moved to person-on-events
- def test_breakdown_by_group_props(self):
- self._create_groups()
-
- journey = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"$group_0": "org:5"},
- "group0_properties": {"industry": "finance"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$group_0": "org:6"},
- "group0_properties": {"industry": "technology"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$group_0": "org:7", "$group_1": "company:10"},
- "group0_properties": {"industry": "finance"},
- "group1_properties": {"industry": "finance"},
- },
- ]
- }
-
- journeys_for(events_by_person=journey, team=self.team)
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12",
- "breakdown": "industry",
- "breakdown_type": "group",
- "breakdown_group_type_index": 0,
- "events": [{"id": "sign up", "name": "sign up", "type": "events", "order": 0}],
- },
- )
- response = Trends().run(filter, self.team)
-
- self.assertEqual(len(response), 2)
- self.assertEqual(response[0]["breakdown_value"], "finance")
- self.assertEqual(response[0]["count"], 2)
- self.assertEqual(response[1]["breakdown_value"], "technology")
- self.assertEqual(response[1]["count"], 1)
-
- filter = filter.shallow_clone(
- {
- "breakdown_value": "technology",
- "date_from": "2020-01-02T00:00:00Z",
- "date_to": "2020-01-03",
- }
- )
- entity = Entity({"id": "sign up", "name": "sign up", "type": "events", "order": 0})
- res = self._get_trend_people(filter, entity)
-
- self.assertEqual(res[0]["distinct_ids"], ["person1"])
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_group_props_person_on_events(self):
- self._create_groups()
-
- journey = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"$group_0": "org:5"},
- "group0_properties": {"industry": "finance"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$group_0": "org:6"},
- "group0_properties": {"industry": "technology"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 15),
- "properties": {"$group_0": "org:7", "$group_1": "company:10"},
- "group0_properties": {"industry": "finance"},
- "group1_properties": {"industry": "finance"},
- },
- ]
- }
-
- journeys_for(events_by_person=journey, team=self.team)
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01",
- "date_to": "2020-01-12",
- "breakdown": "industry",
- "breakdown_type": "group",
- "breakdown_group_type_index": 0,
- "events": [{"id": "sign up", "name": "sign up", "type": "events", "order": 0}],
- },
- )
-
- with override_instance_config("PERSON_ON_EVENTS_ENABLED", True):
- response = Trends().run(filter, self.team)
-
- self.assertEqual(len(response), 2)
- self.assertEqual(response[0]["breakdown_value"], "finance")
- self.assertEqual(response[0]["count"], 2)
- self.assertEqual(response[1]["breakdown_value"], "technology")
- self.assertEqual(response[1]["count"], 1)
-
- filter = filter.shallow_clone(
- {
- "breakdown_value": "technology",
- "date_from": "2020-01-02T00:00:00Z",
- "date_to": "2020-01-02",
- }
- )
- entity = Entity({"id": "sign up", "name": "sign up", "type": "events", "order": 0})
- res = self._get_trend_people(filter, entity)
-
- self.assertEqual(res[0]["distinct_ids"], ["person1"])
-
- # TODO: Delete this test when moved to person-on-events
- def test_breakdown_by_group_props_with_person_filter(self):
- self._create_groups()
-
- create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})
-
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"$group_0": "org:5"},
- timestamp="2020-01-02T12:00:00Z",
- person_properties={"key": "value"},
- group0_properties={"industry": "finance"},
- )
- _create_event(
- event="sign up",
- distinct_id="person2",
- team=self.team,
- properties={"$group_0": "org:6"},
- timestamp="2020-01-02T12:00:00Z",
- person_properties={},
- group0_properties={"industry": "technology"},
- )
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "industry",
- "breakdown_type": "group",
- "breakdown_group_type_index": 0,
- "events": [{"id": "sign up", "name": "sign up", "type": "events", "order": 0}],
- "properties": [{"key": "key", "value": "value", "type": "person"}],
- },
- )
-
- response = Trends().run(filter, self.team)
-
- self.assertEqual(len(response), 1)
- self.assertEqual(response[0]["breakdown_value"], "finance")
- self.assertEqual(response[0]["count"], 1)
-
- # TODO: Delete this test when moved to person-on-events
- def test_filtering_with_group_props(self):
- self._create_groups()
-
- create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- properties={"$group_0": "org:5"},
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- properties={"$group_0": "org:6"},
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- properties={"$group_0": "org:6", "$group_1": "company:10"},
- timestamp="2020-01-02T12:00:00Z",
- )
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "properties": [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- },
- {"key": "key", "value": "value", "type": "person"},
- ],
- },
- )
-
- response = Trends().run(filter, self.team)
- self.assertEqual(response[0]["count"], 1)
-
- def test_filtering_with_group_props_event_with_no_group_data(self):
- self._create_groups()
-
- create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- timestamp="2020-01-02T12:00:00Z",
- )
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "properties": [
- {
- "key": "industry",
- "operator": "is_not",
- "value": "textiles",
- "type": "group",
- "group_type_index": 0,
- },
- {"key": "key", "value": "value", "type": "person"},
- ],
- },
- )
-
- response = Trends().run(filter, self.team)
-
- # we include all 4 events even though they do not have an associated group since the filter is a negative
- # i.e. "industry is not textiles" includes both events associated with a group that has the property "industry"
- # set to a value other than textiles AND events with no group at all
- self.assertEqual(response[0]["count"], 4)
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_group_props_with_person_filter_person_on_events(self):
- self._create_groups()
-
- create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})
-
- _create_event(
- event="sign up",
- distinct_id="person1",
- team=self.team,
- properties={"$group_0": "org:5"},
- timestamp="2020-01-02T12:00:00Z",
- person_properties={"key": "value"},
- group0_properties={"industry": "finance"},
- )
- _create_event(
- event="sign up",
- distinct_id="person2",
- team=self.team,
- properties={"$group_0": "org:6"},
- timestamp="2020-01-02T12:00:00Z",
- person_properties={},
- group0_properties={"industry": "technology"},
- )
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "industry",
- "breakdown_type": "group",
- "breakdown_group_type_index": 0,
- "events": [{"id": "sign up", "name": "sign up", "type": "events", "order": 0}],
- "properties": [{"key": "key", "value": "value", "type": "person"}],
- },
- )
-
- with override_instance_config("PERSON_ON_EVENTS_ENABLED", True):
- response = Trends().run(filter, self.team)
-
- self.assertEqual(len(response), 1)
- self.assertEqual(response[0]["breakdown_value"], "finance")
- self.assertEqual(response[0]["count"], 1)
-
- @snapshot_clickhouse_queries
- def test_filtering_with_group_props_person_on_events(self):
- self._create_groups()
-
- create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- properties={"$group_0": "org:5"},
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- properties={"$group_0": "org:6"},
- timestamp="2020-01-02T12:00:00Z",
- )
- _create_event(
- event="$pageview",
- distinct_id="person1",
- team=self.team,
- properties={"$group_0": "org:6", "$group_1": "company:10"},
- timestamp="2020-01-02T12:00:00Z",
- )
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "events": [{"id": "$pageview", "type": "events", "order": 0}],
- "properties": [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- },
- {"key": "key", "value": "value", "type": "person"},
- ],
- },
- )
-
- with override_instance_config("PERSON_ON_EVENTS_ENABLED", True):
- response = Trends().run(filter, self.team)
- self.assertEqual(response[0]["count"], 1)
-
- @snapshot_clickhouse_queries
- def test_filtering_by_multiple_groups_person_on_events(self):
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=2
- )
-
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:5",
- properties={"industry": "finance"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=0,
- group_key="org:6",
- properties={"industry": "technology"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=2,
- group_key="company:5",
- properties={"name": "five"},
- )
- create_group(
- team_id=self.team.pk,
- group_type_index=2,
- group_key="company:6",
- properties={"name": "six"},
- )
-
- journey = {
- "person1": [
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 12),
- "properties": {"$group_0": "org:5", "$group_2": "company:6"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 12, 30),
- "properties": {"$group_2": "company:6"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 2, 13),
- "properties": {"$group_0": "org:6"},
- },
- {
- "event": "sign up",
- "timestamp": datetime(2020, 1, 3, 15),
- "properties": {"$group_2": "company:5"},
- },
- ]
- }
-
- journeys_for(events_by_person=journey, team=self.team)
-
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-01T00:00:00Z",
- "date_to": "2020-01-12",
- "events": [{"id": "sign up", "name": "sign up", "type": "events", "order": 0}],
- "properties": [
- {
- "key": "industry",
- "value": "finance",
- "type": "group",
- "group_type_index": 0,
- },
- {
- "key": "name",
- "value": "six",
- "type": "group",
- "group_type_index": 2,
- },
- ],
- },
- )
-
- with override_instance_config("PERSON_ON_EVENTS_ENABLED", True):
- response = Trends().run(filter, self.team)
-
- self.assertEqual(len(response), 1)
- self.assertEqual(response[0]["count"], 1)
- self.assertEqual(
- response[0]["data"],
- [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- )
-
- filter = filter.shallow_clone({"date_from": "2020-01-02T00:00:00Z", "date_to": "2020-01-02T00:00:00Z"})
- entity = Entity({"id": "sign up", "name": "sign up", "type": "events", "order": 0})
- res = self._get_trend_people(filter, entity)
-
- self.assertEqual(res[0]["distinct_ids"], ["person1"])
-
-
-class TestTrendUtils(ClickhouseTestMixin, APIBaseTest):
- maxDiff = None
-
- def test_get_cached_result_no_cache(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- filter = Filter(
- team=self.team,
- data={
- "date_to": "2020-11-01 10:26:00",
- "events": [{"id": "sign up", "name": "sign up"}],
- "interval": "hour",
- },
- )
-
- is_present = Trends().get_cached_result(filter, self.team)
- self.assertIsNone(is_present)
-
- def test_get_cached_result_bad_cache(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- fake_cached = {
- "result": [
- {
- "days": [
- "2020-11-01 05:20:00",
- "2020-11-01 10:22:00",
- "2020-11-01 10:25:00",
- ],
- "data": [],
- }
- ]
- }
-
- filter = Filter(
- team=self.team,
- data={
- "date_to": "2020-11-01 10:26:00",
- "events": [{"id": "sign up", "name": "sign up"}],
- "interval": "hour",
- },
- )
- cache_key = generate_cache_key(self.team.pk, f"{filter.toJSON()}_{self.team.pk}")
- cache.set(cache_key, fake_cached, settings.CACHED_RESULTS_TTL)
-
- is_present = Trends().get_cached_result(filter, self.team)
- self.assertIsNone(is_present)
-
- def test_get_cached_result_hour(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- fake_cached = {
- "result": [
- {
- "days": [
- "2020-11-01 05:20:00",
- "2020-11-01 10:22:00",
- "2020-11-01 10:25:00",
- ],
- "data": [0.0, 0.0, 0.0],
- }
- ]
- }
-
- filter = Filter(
- team=self.team,
- data={
- "date_to": "2020-11-01 10:26:00",
- "events": [{"id": "sign up", "name": "sign up"}],
- "interval": "hour",
- },
- )
- cache_key = generate_cache_key(self.team.pk, f"{filter.toJSON()}_{self.team.pk}")
- cache.set(cache_key, fake_cached, settings.CACHED_RESULTS_TTL)
-
- res = Trends().get_cached_result(filter, self.team)
- self.assertIsNotNone(res)
-
- filter = Filter(
- team=self.team,
- data={
- "date_to": "2020-11-02 05:26:00",
- "events": [{"id": "sign up", "name": "sign up"}],
- "interval": "hour",
- },
- )
-
- res = Trends().get_cached_result(filter, self.team)
- self.assertIsNone(res)
-
- def test_get_cached_result_day(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
- fake_cached = {
- "result": [
- {
- "days": ["2020-01-02", "2020-01-03", "2020-01-04"],
- "data": [0.0, 0.0, 0.0],
- }
- ]
- }
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-02",
- "date_to": "2020-01-04",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- )
- cache_key = generate_cache_key(self.team.pk, f"{filter.toJSON()}_{self.team.pk}")
- cache.set(cache_key, fake_cached, settings.CACHED_RESULTS_TTL)
-
- res = Trends().get_cached_result(filter, self.team)
- self.assertTrue(res)
-
- fake_cached = {
- "result": [
- {
- "days": ["2020-01-01", "2020-01-02", "2020-01-03"],
- "data": [0.0, 0.0, 0.0],
- }
- ]
- }
-
- cache.set(cache_key, fake_cached, settings.CACHED_RESULTS_TTL)
-
- res = Trends().get_cached_result(filter, self.team)
- self.assertFalse(res)
-
- def test_get_cached_result_week(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- fake_cached = {
- "result": [
- {
- "days": ["2020-11-01", "2020-11-08", "2020-11-15"],
- "data": [0.0, 0.0, 0.0],
- }
- ]
- }
-
- filter = Filter(
- team=self.team,
- data={
- "date_to": "2020-11-16",
- "events": [{"id": "sign up", "name": "sign up"}],
- "interval": "week",
- },
- )
- cache_key = generate_cache_key(self.team.pk, f"{filter.toJSON()}_{self.team.pk}")
- cache.set(cache_key, fake_cached, settings.CACHED_RESULTS_TTL)
-
- res = Trends().get_cached_result(filter, self.team)
- self.assertTrue(res)
-
- filter = Filter(
- team=self.team,
- data={
- "date_to": "2020-11-23",
- "events": [{"id": "sign up", "name": "sign up"}],
- "interval": "week",
- },
- )
-
- res = Trends().get_cached_result(filter, self.team)
- self.assertFalse(res)
-
- def test_get_cached_result_month(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
-
- fake_cached = {
- "result": [
- {
- "days": ["2020-09-01", "2020-10-01", "2020-11-01"],
- "data": [0.0, 0.0, 0.0],
- }
- ]
- }
-
- filter = Filter(
- team=self.team,
- data={
- "date_to": "2020-11-16",
- "events": [{"id": "sign up", "name": "sign up"}],
- "interval": "month",
- },
- )
- cache_key = generate_cache_key(self.team.pk, f"{filter.toJSON()}_{self.team.pk}")
- cache.set(cache_key, fake_cached, settings.CACHED_RESULTS_TTL)
-
- res = Trends().get_cached_result(filter, self.team)
- self.assertTrue(res)
-
- filter = Filter(
- team=self.team,
- data={
- "date_to": "2020-12-01",
- "events": [{"id": "sign up", "name": "sign up"}],
- "interval": "week",
- },
- )
-
- res = Trends().get_cached_result(filter, self.team)
- self.assertFalse(res)
-
- def test_merge_result(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
- fake_cached = {
- "sign up - Chrome_0": {
- "label": "sign up - Chrome",
- "days": ["2020-01-02", "2020-01-03", "2020-01-04"],
- "data": [23.0, 15.0, 1.0],
- }
- }
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-02",
- "date_to": "2020-01-04",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- )
- result = [{"label": "sign up - Chrome", "data": [15.0, 12.0]}]
-
- merged_result, _ = Trends().merge_results(result, fake_cached, 0, filter, self.team)
- self.assertEqual(merged_result[0]["data"], [23.0, 15.0, 12.0])
-
- def test_merge_result_no_cache(self):
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-02",
- "date_to": "2020-01-04",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- )
-
- result = [{"label": "sign up - Chrome", "data": [15.0, 12.0]}]
-
- merged_result, _ = Trends().merge_results(result, {}, 0, filter, self.team)
-
- self.assertEqual(merged_result[0]["data"], [15.0, 12.0])
-
- def test_merge_result_multiple(self):
- set_instance_setting("STRICT_CACHING_TEAMS", "all")
- fake_cached = {
- "sign up - Chrome_0": {
- "label": "sign up - Chrome",
- "days": ["2020-01-02", "2020-01-03", "2020-01-04"],
- "data": [23.0, 15.0, 1.0],
- },
- "sign up - Safari_0": {
- "label": "sign up - Safari",
- "days": ["2020-01-02", "2020-01-03", "2020-01-04"],
- "data": [12.0, 11.0, 8.0],
- },
- }
- filter = Filter(
- team=self.team,
- data={
- "date_from": "2020-01-02",
- "date_to": "2020-01-04",
- "events": [{"id": "sign up", "name": "sign up"}],
- },
- )
-
- result = [
- {"label": "sign up - Chrome", "data": [15.0, 12.0]},
- {"label": "sign up - Safari", "data": [15.0, 9.0]},
- ]
-
- merged_result, _ = Trends().merge_results(result, fake_cached, 0, filter, self.team)
-
- self.assertEqual(merged_result[0]["data"], [23.0, 15.0, 12.0])
- self.assertEqual(merged_result[1]["data"], [12.0, 11.0, 9.0])
diff --git a/posthog/queries/test/test_util.py b/posthog/queries/test/test_util.py
index b2d3cec18fb5..c7aa2bb5b4f9 100644
--- a/posthog/queries/test/test_util.py
+++ b/posthog/queries/test/test_util.py
@@ -1,12 +1,6 @@
-from datetime import UTC, date, datetime
-
-from unittest.mock import patch
-
from django.test import TestCase
-from parameterized import parameterized
-
-from posthog.queries.util import correct_result_for_sampling, get_earliest_timestamp
+from posthog.queries.util import correct_result_for_sampling
class TestQueriesUtil(TestCase):
@@ -28,21 +22,3 @@ class TestQueriesUtil(TestCase):
res = correct_result_for_sampling(1, 0.01, "sum")
self.assertEqual(res, 100)
-
- @parameterized.expand(
- [
- ("date", date(2024, 3, 21), datetime(2024, 3, 21, 0, 0, 0, tzinfo=UTC)),
- (
- "datetime_passthrough",
- datetime(2024, 3, 21, 13, 45, 12, tzinfo=UTC),
- datetime(2024, 3, 21, 13, 45, 12, tzinfo=UTC),
- ),
- ]
- )
- def test_get_earliest_timestamp_coerces_date_to_datetime(self, _name, returned, expected):
- # ClickHouse may hand back a `date` for some teams; downstream interval alignment needs a `datetime`.
- with patch("posthog.queries.util.insight_sync_execute", return_value=[[returned]]):
- result = get_earliest_timestamp(1)
-
- self.assertIsInstance(result, datetime)
- self.assertEqual(result, expected)
diff --git a/posthog/queries/time_to_see_data/__init__.py b/posthog/queries/time_to_see_data/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/queries/time_to_see_data/hierarchy.py b/posthog/queries/time_to_see_data/hierarchy.py
deleted file mode 100644
index 260a1fad0efb..000000000000
--- a/posthog/queries/time_to_see_data/hierarchy.py
+++ /dev/null
@@ -1,92 +0,0 @@
-from dataclasses import dataclass, field
-from enum import Enum
-
-
-class NodeType(Enum):
- SESSION = "session"
- INTERACTION = "interaction"
- EVENT = "event"
- QUERY = "query"
- SUBQUERY = "subquery"
-
-
-NODE_TYPE_WEIGHTS = {
- NodeType.SESSION: 0,
- NodeType.INTERACTION: 1,
- NodeType.EVENT: 2,
- NodeType.QUERY: 3,
- NodeType.SUBQUERY: 4,
-}
-
-
-@dataclass
-class Node:
- type: NodeType
- data: dict
- children: list["Node"] = field(default_factory=list)
-
- def to_dict(self):
- return {
- "type": self.type.value,
- "data": self.data,
- "children": [node.to_dict() for node in self.children],
- }
-
-
-def construct_hierarchy(session, interactions_and_events, queries) -> dict:
- """
- Constructs a tree-like hierarchy for session based on interactions and queries, to expose
- triggered-by relationships.
- """
- nodes: list[Node] = []
- nodes.extend(make_empty_node(interaction_type, data) for data in interactions_and_events)
- nodes.extend(make_empty_node(query_type, data) for data in queries)
-
- root_node = Node(type=NodeType.SESSION, data=session, children=[])
-
- # :KLUDGE: This is n^2 complexity. Could be sped up by sorting or doing other clever things.
- for node in nodes:
- potential_parents = [parent_node for parent_node in nodes if is_child(parent_node, node)]
-
- # Select the least specific potential parent
- if len(potential_parents) > 0:
- parent = max(potential_parents, key=lambda parent: NODE_TYPE_WEIGHTS[parent.type])
- else:
- parent = root_node
- parent.children.append(node)
-
- return root_node.to_dict()
-
-
-def is_child(parent: Node, child: Node) -> bool:
- if parent.type == child.type:
- return False
-
- if parent.type == NodeType.SESSION:
- return parent.data["session_id"] == child.data["session_id"]
-
- if parent.type == NodeType.INTERACTION and child.type == NodeType.EVENT:
- return parent.data["primary_interaction_id"] == child.data["primary_interaction_id"]
-
- if parent.type == NodeType.INTERACTION and child.type == NodeType.QUERY:
- return parent.data["primary_interaction_id"] in child.data["client_query_id"]
-
- if parent.type == NodeType.EVENT and child.type == NodeType.QUERY:
- return parent.data["query_id"] in child.data["client_query_id"]
-
- if parent.type == NodeType.QUERY and child.type == NodeType.SUBQUERY:
- return parent.data["client_query_id"] == child.data["client_query_id"]
-
- return False
-
-
-def make_empty_node(type_getter, data: dict):
- return Node(type=type_getter(data), data=data, children=[])
-
-
-def interaction_type(data):
- return NodeType.INTERACTION if data["is_primary_interaction"] else NodeType.EVENT
-
-
-def query_type(data):
- return NodeType.QUERY if data["is_initial_query"] else NodeType.SUBQUERY
diff --git a/posthog/queries/time_to_see_data/serializers.py b/posthog/queries/time_to_see_data/serializers.py
deleted file mode 100644
index ee665f39820b..000000000000
--- a/posthog/queries/time_to_see_data/serializers.py
+++ /dev/null
@@ -1,53 +0,0 @@
-from functools import cached_property
-
-from rest_framework import serializers
-
-from posthog.models.user import User
-
-
-class SessionsQuerySerializer(serializers.Serializer):
- team_id = serializers.IntegerField(required=False)
- session_id = serializers.CharField(required=False)
-
-
-class SessionEventsQuerySerializer(serializers.Serializer):
- session_id = serializers.CharField()
- team_id = serializers.IntegerField()
- session_start = serializers.DateTimeField()
- session_end = serializers.DateTimeField()
-
-
-class SessionResponseSerializer(serializers.Serializer):
- session_id = serializers.CharField()
- user_id = serializers.IntegerField()
- team_id = serializers.IntegerField()
- session_start = serializers.DateTimeField()
- session_end = serializers.DateTimeField()
- duration_ms = serializers.IntegerField()
-
- team_events_last_month = serializers.IntegerField()
- events_count = serializers.IntegerField()
- interactions_count = serializers.IntegerField()
- total_interaction_time_to_see_data_ms = serializers.IntegerField()
- frustrating_interactions_count = serializers.IntegerField()
-
- user = serializers.SerializerMethodField()
-
- def get_user(self, session):
- from posthog.api.shared import UserBasicSerializer
-
- user = self.context.get("user_lookup", UserLookup([session])).get(session["user_id"])
- return UserBasicSerializer(user).data
-
-
-class UserLookup:
- def __init__(self, results):
- self.user_ids = [row["user_id"] for row in results]
-
- @cached_property
- def users(self):
- users = User.objects.filter(pk__in=self.user_ids)
- return {user.pk: user for user in users}
-
- def get(self, id):
- return self.users.get(id)
diff --git a/posthog/queries/time_to_see_data/sessions.py b/posthog/queries/time_to_see_data/sessions.py
deleted file mode 100644
index b12a773dcc1e..000000000000
--- a/posthog/queries/time_to_see_data/sessions.py
+++ /dev/null
@@ -1,102 +0,0 @@
-from typing import Optional
-
-from posthog.clickhouse.client import query_with_columns
-from posthog.queries.time_to_see_data.hierarchy import construct_hierarchy
-from posthog.queries.time_to_see_data.serializers import (
- SessionEventsQuerySerializer,
- SessionResponseSerializer,
- SessionsQuerySerializer,
- UserLookup,
-)
-
-IS_FRUSTRATING_INTERACTION = "time_to_see_data_ms >= 5000"
-
-GET_SESSIONS = f"""
-SELECT
- session_id,
- any(user_id) AS user_id,
- any(team_id) AS team_id,
- min(timestamp - toIntervalSecond(time_to_see_data_ms / 1000)) AS session_start,
- max(timestamp) AS session_end,
- 1000 * dateDiff('second', session_start, session_end) AS duration_ms,
- argMax(team_events_last_month, _timestamp) as team_events_last_month,
- count() AS events_count,
- countIf(is_primary_interaction) AS interactions_count,
- sumIf(time_to_see_data_ms, is_primary_interaction) AS total_interaction_time_to_see_data_ms,
- countIf(is_primary_interaction and {IS_FRUSTRATING_INTERACTION}) AS frustrating_interactions_count
-FROM metrics_time_to_see_data
-WHERE {{condition}}
-GROUP BY session_id
-ORDER BY session_end DESC
-"""
-
-GET_SESSION_EVENTS = f"""
-SELECT *, {IS_FRUSTRATING_INTERACTION} AS is_frustrating
-FROM metrics_time_to_see_data
-WHERE team_id = %(team_id)s
- AND session_id = %(session_id)s
- AND timestamp >= %(session_start)s
- AND timestamp <= toDateTime(%(session_end)s) + toIntervalHour(2)
-"""
-
-GET_SESSION_QUERIES = f"""
-SELECT * EXCEPT (ProfileEvents), query_duration_ms >= 5000 AS is_frustrating
-FROM metrics_query_log
-WHERE team_id = %(team_id)s
- AND session_id = %(session_id)s
- AND timestamp >= %(session_start)s
- AND timestamp <= toDateTime(%(session_end)s) + toIntervalHour(2)
-"""
-
-
-def get_sessions(query: SessionsQuerySerializer) -> SessionResponseSerializer:
- sessions = _fetch_sessions(query)
- response_serializer = SessionResponseSerializer(
- data=sessions, many=True, context={"user_lookup": UserLookup(sessions)}
- )
- response_serializer.is_valid(raise_exception=True)
- return response_serializer
-
-
-def get_session_events(query: SessionEventsQuerySerializer) -> Optional[dict]:
- params = {
- "team_id": query.validated_data["team_id"],
- "session_id": query.validated_data["session_id"],
- "session_start": query.validated_data["session_start"].strftime("%Y-%m-%d %H:%M:%S"),
- "session_end": query.validated_data["session_end"].strftime("%Y-%m-%d %H:%M:%S"),
- }
- events = query_with_columns(GET_SESSION_EVENTS, params)
- queries = query_with_columns(GET_SESSION_QUERIES, params)
- session_query = SessionsQuerySerializer(
- data={
- "team_id": query.validated_data["team_id"],
- "session_id": query.validated_data["session_id"],
- }
- )
- session_query.is_valid(raise_exception=True)
- sessions = get_sessions(session_query).data
-
- if len(sessions) == 0:
- return None
-
- return construct_hierarchy(sessions[0], events, queries)
-
-
-def _fetch_sessions(query: SessionsQuerySerializer) -> list[dict]:
- condition, params = _sessions_condition(query)
- return query_with_columns(GET_SESSIONS.format(condition=condition), params)
-
-
-def _sessions_condition(query: SessionsQuerySerializer) -> tuple[str, dict]:
- conditions = []
-
- if "team_id" in query.validated_data:
- conditions.append("metrics_time_to_see_data.team_id = %(team_id)s")
-
- if "session_id" in query.validated_data:
- conditions.append("metrics_time_to_see_data.session_id = %(session_id)s")
-
- if len(conditions) > 0:
- return " AND ".join(conditions), query.validated_data
- else:
- return "1 = 1", {}
diff --git a/posthog/queries/time_to_see_data/test/__init__.py b/posthog/queries/time_to_see_data/test/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/queries/time_to_see_data/test/test_hierarchy.py b/posthog/queries/time_to_see_data/test/test_hierarchy.py
deleted file mode 100644
index 44066b917726..000000000000
--- a/posthog/queries/time_to_see_data/test/test_hierarchy.py
+++ /dev/null
@@ -1,193 +0,0 @@
-import pytest
-
-from posthog.queries.time_to_see_data.hierarchy import Node, NodeType, construct_hierarchy, is_child
-
-
- "potential_parent,potential_child,expected_result",
- [
- # Sessions
- (
- Node(NodeType.SESSION, {"session_id": 1}),
- Node(NodeType.INTERACTION, {"session_id": 1}),
- True,
- ),
- (
- Node(NodeType.SESSION, {"session_id": 1}),
- Node(NodeType.QUERY, {"session_id": 1}),
- True,
- ),
- (
- Node(NodeType.SESSION, {"session_id": 2}),
- Node(NodeType.QUERY, {"session_id": 1}),
- False,
- ),
- (
- Node(NodeType.SESSION, {"session_id": 1}),
- Node(NodeType.SESSION, {"session_id": 1}),
- False,
- ),
- # Interactions
- (
- Node(NodeType.INTERACTION, {"primary_interaction_id": "1"}),
- Node(NodeType.EVENT, {"primary_interaction_id": "1"}),
- True,
- ),
- (
- Node(NodeType.INTERACTION, {"primary_interaction_id": "1"}),
- Node(NodeType.EVENT, {"primary_interaction_id": "2"}),
- False,
- ),
- (
- Node(NodeType.INTERACTION, {"primary_interaction_id": "123"}),
- Node(NodeType.QUERY, {"client_query_id": "123::2543245"}),
- True,
- ),
- (
- Node(NodeType.INTERACTION, {"primary_interaction_id": "456"}),
- Node(NodeType.QUERY, {"client_query_id": "123::2543245"}),
- False,
- ),
- (
- Node(NodeType.INTERACTION, {"primary_interaction_id": "123"}),
- Node(NodeType.SUBQUERY, {"client_query_id": "123::2543245"}),
- False,
- ),
- (
- Node(NodeType.INTERACTION, {"session_id": 1}),
- Node(NodeType.SESSION, {}),
- False,
- ),
- (Node(NodeType.INTERACTION, {}), Node(NodeType.INTERACTION, {}), False),
- # Events
- (
- Node(NodeType.EVENT, {"query_id": "2543245"}),
- Node(NodeType.QUERY, {"client_query_id": "123::2543245"}),
- True,
- ),
- (
- Node(NodeType.EVENT, {"query_id": "foobar"}),
- Node(NodeType.QUERY, {"client_query_id": "123::2543245"}),
- False,
- ),
- (
- Node(NodeType.EVENT, {"query_id": "2543245"}),
- Node(NodeType.SUBQUERY, {"client_query_id": "123::2543245"}),
- False,
- ),
- # Queries
- (
- Node(NodeType.QUERY, {"client_query_id": "123::2543245"}),
- Node(NodeType.SUBQUERY, {"client_query_id": "123::2543245"}),
- True,
- ),
- (
- Node(NodeType.QUERY, {"client_query_id": "123::"}),
- Node(NodeType.SUBQUERY, {"client_query_id": "123::2543245"}),
- False,
- ),
- ],
-)
-def test_is_child(potential_parent, potential_child, expected_result):
- assert is_child(potential_parent, potential_child) == expected_result
-
-
-def test_construct_hierarchy():
- session = {"session_id": 1}
-
- interaction_1 = {
- **session,
- "is_primary_interaction": True,
- "primary_interaction_id": "123",
- }
- event_11 = {
- **session,
- "is_primary_interaction": False,
- "primary_interaction_id": "123",
- "query_id": "456",
- }
- query_111 = {**session, "client_query_id": "123::456", "is_initial_query": True}
- subquery_1111 = {
- **session,
- "client_query_id": "123::456",
- "is_initial_query": False,
- }
- event_12 = {
- **session,
- "is_primary_interaction": False,
- "primary_interaction_id": "123",
- "query_id": "789",
- }
- query_121 = {**session, "client_query_id": "123::789", "is_initial_query": True}
- query_13 = {**session, "client_query_id": "123::1111", "is_initial_query": True}
-
- interaction_2 = {
- **session,
- "is_primary_interaction": True,
- "primary_interaction_id": "8888",
- }
-
- stray_event = {
- **session,
- "is_primary_interaction": False,
- "primary_interaction_id": "efg",
- "query_id": "9999",
- }
- stray_query = {**session, "client_query_id": "foobar", "is_initial_query": True}
-
- result = construct_hierarchy(
- session,
- [interaction_1, event_11, event_12, interaction_2, stray_event],
- [query_111, subquery_1111, query_121, query_13, stray_query],
- )
-
- assert result == {
- "type": "session",
- "data": session,
- "children": [
- {
- "type": "interaction",
- "data": interaction_1,
- "children": [
- {
- "type": "event",
- "data": event_11,
- "children": [
- {
- "type": "query",
- "data": query_111,
- "children": [
- {
- "type": "subquery",
- "data": subquery_1111,
- "children": [],
- }
- ],
- }
- ],
- },
- {
- "type": "event",
- "data": event_12,
- "children": [{"type": "query", "data": query_121, "children": []}],
- },
- {"type": "query", "data": query_13, "children": []},
- ],
- },
- {
- "type": "interaction",
- "data": interaction_2,
- "children": [],
- },
- {
- "type": "event",
- "data": stray_event,
- "children": [],
- },
- {
- "type": "query",
- "data": stray_query,
- "children": [],
- },
- ],
- }
diff --git a/posthog/queries/time_to_see_data/test/test_sessions.py b/posthog/queries/time_to_see_data/test/test_sessions.py
deleted file mode 100644
index 318d8c02ae3a..000000000000
--- a/posthog/queries/time_to_see_data/test/test_sessions.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import pytest
-
-
- "query,expected_condition",
- [
- ({}, "1 = 1"),
- (
- {"team_id": 4},
- "metrics_time_to_see_data.team_id = %(team_id)s",
- ),
- (
- {"team_id": 4, "session_id": "456"},
- "metrics_time_to_see_data.team_id = %(team_id)s AND metrics_time_to_see_data.session_id = %(session_id)s",
- ),
- ],
-)
-def test_sessions_condition(query, expected_condition):
- from posthog.queries.time_to_see_data.serializers import SessionsQuerySerializer
- from posthog.queries.time_to_see_data.sessions import _sessions_condition
-
- serializer = SessionsQuerySerializer(data=query)
- serializer.is_valid(raise_exception=True)
-
- assert _sessions_condition(serializer) == (expected_condition, query)
diff --git a/posthog/queries/trends/breakdown.py b/posthog/queries/trends/breakdown.py
deleted file mode 100644
index 4da9ad44ce15..000000000000
--- a/posthog/queries/trends/breakdown.py
+++ /dev/null
@@ -1,795 +0,0 @@
-import re
-import json
-import urllib.parse
-from collections.abc import Callable
-from datetime import datetime
-from typing import Any, Optional, Union
-from zoneinfo import ZoneInfo
-
-from django.forms import ValidationError
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.constants import (
- MONTHLY_ACTIVE,
- NON_TIME_SERIES_DISPLAY_TYPES,
- TREND_FILTER_TYPE_ACTIONS,
- TREND_FILTER_TYPE_EVENTS,
- TRENDS_CUMULATIVE,
- UNIQUE_USERS,
- WEEKLY_ACTIVE,
- PropertyOperatorType,
-)
-from posthog.models.entity import Entity
-from posthog.models.event.sql import EVENT_JOIN_PERSON_SQL
-from posthog.models.filters import Filter
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.models.property import PropertyGroup
-from posthog.models.property.util import get_property_string_expr, normalize_url_breakdown, parse_prop_grouped_clauses
-from posthog.models.team import Team
-from posthog.queries.breakdown_props import (
- ALL_USERS_COHORT_ID,
- format_breakdown_cohort_join_query,
- get_breakdown_cohort_name,
- get_breakdown_prop_values,
-)
-from posthog.queries.column_optimizer.column_optimizer import ColumnOptimizer
-from posthog.queries.event_query import EventQuery
-from posthog.queries.groups_join_query import GroupsJoinQuery
-from posthog.queries.person_distinct_id_query import get_team_distinct_ids_query
-from posthog.queries.person_on_events_v2_sql import PERSON_DISTINCT_ID_OVERRIDES_JOIN_SQL
-from posthog.queries.person_query import PersonQuery
-from posthog.queries.query_date_range import TIME_IN_SECONDS, QueryDateRange
-from posthog.queries.trends.sql import (
- BREAKDOWN_ACTIVE_USER_AGGREGATE_SQL,
- BREAKDOWN_ACTIVE_USER_CONDITIONS_SQL,
- BREAKDOWN_ACTIVE_USER_INNER_SQL,
- BREAKDOWN_AGGREGATE_QUERY_SQL,
- BREAKDOWN_COHORT_JOIN_SQL,
- BREAKDOWN_CUMULATIVE_INNER_SQL,
- BREAKDOWN_HISTOGRAM_PROP_JOIN_SQL,
- BREAKDOWN_INNER_SQL,
- BREAKDOWN_PROP_JOIN_SQL,
- BREAKDOWN_PROP_JOIN_WITH_OTHER_SQL,
- BREAKDOWN_QUERY_SQL,
- SESSION_DURATION_BREAKDOWN_AGGREGATE_SQL,
- SESSION_DURATION_BREAKDOWN_INNER_SQL,
- VOLUME_PER_ACTOR_BREAKDOWN_AGGREGATE_SQL,
- VOLUME_PER_ACTOR_BREAKDOWN_INNER_SQL,
-)
-from posthog.queries.trends.util import (
- COUNT_PER_ACTOR_MATH_FUNCTIONS,
- PROPERTY_MATH_FUNCTIONS,
- correct_result_for_sampling,
- enumerate_time_range,
- get_active_user_params,
- offset_time_series_date_by_interval,
- parse_response,
- process_math,
-)
-from posthog.queries.util import (
- alias_poe_mode_for_legacy,
- get_interval_func_ch,
- get_person_properties_mode,
- get_start_of_interval_sql,
-)
-from posthog.session_recordings.queries.session_query import SessionQuery
-from posthog.utils import encode_get_request_params, generate_short_id
-
-from products.actions.backend.models.util import format_action_filter
-
-BREAKDOWN_OTHER_DISPLAY = "Other (i.e. all remaining values)"
-BREAKDOWN_NULL_DISPLAY = "None (i.e. no value)"
-
-
-BREAKDOWN_OTHER_STRING_LABEL = "$$_posthog_breakdown_other_$$"
-BREAKDOWN_OTHER_NUMERIC_LABEL = 9007199254740991 # pow(2, 53) - 1, for JS compatibility
-BREAKDOWN_NULL_STRING_LABEL = "$$_posthog_breakdown_null_$$"
-BREAKDOWN_NULL_NUMERIC_LABEL = 9007199254740990 # pow(2, 53) - 2, for JS compatibility
-
-
-class TrendsBreakdown:
- DISTINCT_ID_TABLE_ALIAS = EventQuery.DISTINCT_ID_TABLE_ALIAS
- EVENT_TABLE_ALIAS = EventQuery.EVENT_TABLE_ALIAS
- PERSON_ID_OVERRIDES_TABLE_ALIAS = EventQuery.PERSON_ID_OVERRIDES_TABLE_ALIAS
-
- def __init__(
- self,
- entity: Entity,
- filter: Filter,
- team: Team,
- column_optimizer: Optional[ColumnOptimizer] = None,
- person_on_events_mode: PersonsOnEventsMode = PersonsOnEventsMode.DISABLED,
- add_person_urls: bool = False,
- ):
- self.entity = entity
- self.filter = filter
- self.team = team
- self.team_id = team.pk
- self.params: dict[str, Any] = {"team_id": team.pk}
- self.column_optimizer = column_optimizer or ColumnOptimizer(self.filter, self.team_id)
- self.add_person_urls = add_person_urls
- self.person_on_events_mode = alias_poe_mode_for_legacy(person_on_events_mode)
- if person_on_events_mode == PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS:
- self._person_id_alias = f"if(notEmpty({self.PERSON_ID_OVERRIDES_TABLE_ALIAS}.distinct_id), {self.PERSON_ID_OVERRIDES_TABLE_ALIAS}.person_id, {self.EVENT_TABLE_ALIAS}.person_id)"
- elif person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:
- self._person_id_alias = f"{self.EVENT_TABLE_ALIAS}.person_id"
- else:
- self._person_id_alias = f"{self.DISTINCT_ID_TABLE_ALIAS}.person_id"
-
- @cached_property
- def actor_aggregator(self) -> str:
- if self.team.aggregate_users_by_distinct_id:
- return "e.distinct_id"
- return self._person_id_alias
-
- @cached_property
- def _props_to_filter(self) -> tuple[str, dict]:
- props_to_filter = self.filter.property_groups.combine_property_group(
- PropertyOperatorType.AND, self.entity.property_groups
- )
-
- target_properties: Optional[PropertyGroup] = props_to_filter
- if self.person_on_events_mode == PersonsOnEventsMode.DISABLED:
- target_properties = self.column_optimizer.property_optimizer.parse_property_groups(props_to_filter).outer
-
- return parse_prop_grouped_clauses(
- team_id=self.team_id,
- property_group=target_properties,
- table_name=self.EVENT_TABLE_ALIAS,
- person_properties_mode=get_person_properties_mode(self.team),
- person_id_joined_alias=self._person_id_alias,
- hogql_context=self.filter.hogql_context,
- )
-
- def get_query(self) -> tuple[str, dict, Callable]:
- date_params = {}
-
- query_date_range = QueryDateRange(filter=self.filter, team=self.team)
- parsed_date_from, date_from_params = query_date_range.date_from
- parsed_date_to, date_to_params = query_date_range.date_to
- num_intervals = query_date_range.num_intervals
- seconds_in_interval = TIME_IN_SECONDS[self.filter.interval]
-
- date_params.update(date_from_params)
- date_params.update(date_to_params)
-
- prop_filters, prop_filter_params = self._props_to_filter
-
- aggregate_operation, _, math_params = process_math(
- self.entity,
- self.team,
- filter=self.filter,
- event_table_alias=self.EVENT_TABLE_ALIAS,
- person_id_alias=(
- f"person_id"
- if self.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
- else self._person_id_alias
- ),
- )
-
- action_query = ""
- action_params: dict = {}
- if self.entity.type == TREND_FILTER_TYPE_ACTIONS:
- action = self.entity.get_action(self.team_id)
- action_query, action_params = format_action_filter(
- team_id=self.team_id,
- action=action,
- table_name=self.EVENT_TABLE_ALIAS,
- person_properties_mode=get_person_properties_mode(self.team),
- person_id_joined_alias=self._person_id_alias,
- hogql_context=self.filter.hogql_context,
- )
-
- self.params = {
- **self.params,
- **math_params,
- **prop_filter_params,
- **action_params,
- "event": self.entity.id,
- "key": self.filter.breakdown,
- **date_params,
- "timezone": self.team.timezone,
- }
-
- breakdown_filter_params = {
- "parsed_date_from": parsed_date_from,
- "parsed_date_to": parsed_date_to,
- "actions_query": "AND {}".format(action_query) if action_query else "",
- "event_filter": (
- "AND event = %(event)s"
- if self.entity.type == TREND_FILTER_TYPE_EVENTS and self.entity.id is not None
- else ""
- ),
- "filters": prop_filters,
- "null_person_filter": (
- f"AND notEmpty(e.person_id)" if self.person_on_events_mode != PersonsOnEventsMode.DISABLED else ""
- ),
- }
-
- _params, _breakdown_filter_params = {}, {}
-
- if self.filter.breakdown_type == "cohort":
- (
- _params,
- breakdown_filter,
- _breakdown_filter_params,
- breakdown_value,
- ) = self._breakdown_cohort_params()
- else:
- aggregate_operation_for_breakdown_init = (
- "count(*)"
- if self.entity.math == "dau" or self.entity.math in COUNT_PER_ACTOR_MATH_FUNCTIONS
- else aggregate_operation
- )
- (
- _params,
- breakdown_filter,
- _breakdown_filter_params,
- breakdown_value,
- ) = self._breakdown_prop_params(aggregate_operation_for_breakdown_init, math_params)
-
- if len(_params["values"]) == 0:
- # If there are no breakdown values, we are sure that there's no relevant events, so instead of adjusting
- # a "real" SELECT for this, we only include the below dummy SELECT.
- # It's a drop-in replacement for a "real" one, simply always returning 0 rows.
- # See https://github.com/PostHog/posthog/pull/5674 for context.
- return (
- "SELECT [now()] AS date, [0] AS total, '' AS breakdown_value LIMIT 0",
- {},
- lambda _: [],
- )
-
- person_join_condition, person_join_params = self._person_join_condition()
- groups_join_condition, groups_join_params = self._groups_join_condition()
- sessions_join_condition, sessions_join_params = self._sessions_join_condition()
-
- sample_clause = "SAMPLE %(sampling_factor)s" if self.filter.sampling_factor else ""
- sampling_params = {"sampling_factor": self.filter.sampling_factor}
-
- self.params = {
- **self.params,
- **_params,
- **person_join_params,
- **groups_join_params,
- **sessions_join_params,
- **sampling_params,
- }
- breakdown_filter_params = {
- **breakdown_filter_params,
- **_breakdown_filter_params,
- }
-
- if self.filter.display in NON_TIME_SERIES_DISPLAY_TYPES:
- breakdown_filter = breakdown_filter.format(**breakdown_filter_params)
-
- if self.entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE]:
- interval_func = get_interval_func_ch(self.filter.interval)
- (
- active_user_format_params,
- active_user_query_params,
- ) = get_active_user_params(self.filter, self.entity, self.team_id)
- self.params.update(active_user_query_params)
- conditions = BREAKDOWN_ACTIVE_USER_CONDITIONS_SQL.format(
- **breakdown_filter_params, **active_user_format_params
- )
- content_sql = BREAKDOWN_ACTIVE_USER_AGGREGATE_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join=sessions_join_condition,
- aggregate_operation=aggregate_operation,
- timestamp_truncated=get_start_of_interval_sql(self.filter.interval, team=self.team),
- date_to_truncated=get_start_of_interval_sql(
- self.filter.interval, team=self.team, source="%(date_to)s"
- ),
- interval_func=interval_func,
- breakdown_value=breakdown_value,
- conditions=conditions,
- GET_TEAM_PERSON_DISTINCT_IDS=get_team_distinct_ids_query(self.team_id),
- sample_clause=sample_clause,
- **active_user_format_params,
- **breakdown_filter_params,
- )
- elif self.entity.math in PROPERTY_MATH_FUNCTIONS and self.entity.math_property == "$session_duration":
- # TODO: When we add more person/group properties to math_property,
- # generalise this query to work for everything, not just sessions.
- content_sql = SESSION_DURATION_BREAKDOWN_AGGREGATE_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join_condition=sessions_join_condition,
- aggregate_operation=aggregate_operation,
- breakdown_value=breakdown_value,
- event_sessions_table_alias=SessionQuery.SESSION_TABLE_ALIAS,
- sample_clause=sample_clause,
- )
- elif self.entity.math in COUNT_PER_ACTOR_MATH_FUNCTIONS:
- content_sql = VOLUME_PER_ACTOR_BREAKDOWN_AGGREGATE_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join_condition=sessions_join_condition,
- aggregate_operation=aggregate_operation,
- aggregator=self.actor_aggregator,
- breakdown_value=breakdown_value,
- sample_clause=sample_clause,
- )
- else:
- content_sql = BREAKDOWN_AGGREGATE_QUERY_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join_condition=sessions_join_condition,
- aggregate_operation=aggregate_operation,
- breakdown_value=breakdown_value,
- sample_clause=sample_clause,
- )
- time_range = enumerate_time_range(self.filter, seconds_in_interval)
-
- return (
- content_sql,
- self.params,
- self._parse_single_aggregate_result(self.filter, self.entity, {"days": time_range}),
- )
-
- else:
- breakdown_filter = breakdown_filter.format(**breakdown_filter_params)
-
- if self.entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE]:
- (
- active_user_format_params,
- active_user_query_params,
- ) = get_active_user_params(self.filter, self.entity, self.team_id)
- self.params.update(active_user_query_params)
- conditions = BREAKDOWN_ACTIVE_USER_CONDITIONS_SQL.format(
- **breakdown_filter_params, **active_user_format_params
- )
- inner_sql = BREAKDOWN_ACTIVE_USER_INNER_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join=sessions_join_condition,
- person_id_alias=self._person_id_alias,
- aggregate_operation=aggregate_operation,
- timestamp_truncated=get_start_of_interval_sql(self.filter.interval, team=self.team),
- breakdown_value=breakdown_value,
- conditions=conditions,
- GET_TEAM_PERSON_DISTINCT_IDS=get_team_distinct_ids_query(self.team_id),
- sample_clause=sample_clause,
- **active_user_format_params,
- **breakdown_filter_params,
- )
- elif self.filter.display == TRENDS_CUMULATIVE and self.entity.math == "dau":
- # TRICKY: This is a subquery, so the person_id_alias expression is not available in the outer query.
- # Hence, we overwrite the aggregation_operation with the apprioriate one for the outer query.
- cummulative_aggregate_operation = f"count(DISTINCT person_id)"
-
- inner_sql = BREAKDOWN_CUMULATIVE_INNER_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join=sessions_join_condition,
- person_id_alias=self._person_id_alias,
- aggregate_operation=cummulative_aggregate_operation,
- timestamp_truncated=get_start_of_interval_sql(self.filter.interval, team=self.team),
- breakdown_value=breakdown_value,
- sample_clause=sample_clause,
- **breakdown_filter_params,
- )
- elif self.entity.math in PROPERTY_MATH_FUNCTIONS and self.entity.math_property == "$session_duration":
- # TODO: When we add more person/group properties to math_property,
- # generalise this query to work for everything, not just sessions.
- inner_sql = SESSION_DURATION_BREAKDOWN_INNER_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join=sessions_join_condition,
- aggregate_operation=aggregate_operation,
- timestamp_truncated=get_start_of_interval_sql(self.filter.interval, team=self.team),
- breakdown_value=breakdown_value,
- event_sessions_table_alias=SessionQuery.SESSION_TABLE_ALIAS,
- sample_clause=sample_clause,
- **breakdown_filter_params,
- )
- elif self.entity.math in COUNT_PER_ACTOR_MATH_FUNCTIONS:
- inner_sql = VOLUME_PER_ACTOR_BREAKDOWN_INNER_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join=sessions_join_condition,
- aggregate_operation=aggregate_operation,
- timestamp_truncated=get_start_of_interval_sql(self.filter.interval, team=self.team),
- aggregator=self.actor_aggregator,
- breakdown_value=breakdown_value,
- sample_clause=sample_clause,
- **breakdown_filter_params,
- )
- else:
- inner_sql = BREAKDOWN_INNER_SQL.format(
- breakdown_filter=breakdown_filter,
- person_join=person_join_condition,
- groups_join=groups_join_condition,
- sessions_join=sessions_join_condition,
- aggregate_operation=aggregate_operation,
- timestamp_truncated=get_start_of_interval_sql(self.filter.interval, team=self.team),
- breakdown_value=breakdown_value,
- sample_clause=sample_clause,
- **breakdown_filter_params,
- )
-
- breakdown_query = BREAKDOWN_QUERY_SQL.format(
- num_intervals=num_intervals,
- inner_sql=inner_sql,
- date_from_truncated=get_start_of_interval_sql(
- self.filter.interval, team=self.team, source="%(date_from)s"
- ),
- date_to_truncated=get_start_of_interval_sql(self.filter.interval, team=self.team, source="%(date_to)s"),
- interval_func=get_interval_func_ch(self.filter.interval),
- )
- self.params.update(
- {
- "seconds_in_interval": seconds_in_interval,
- "num_intervals": num_intervals,
- }
- )
- return breakdown_query, self.params, self._parse_trend_result(self.filter, self.entity)
-
- def _breakdown_cohort_params(self):
- cohort_queries, cohort_ids, cohort_params = format_breakdown_cohort_join_query(
- self.team, self.filter, entity=self.entity
- )
- params = {"values": cohort_ids, **cohort_params}
- breakdown_filter = BREAKDOWN_COHORT_JOIN_SQL
- breakdown_filter_params = {"cohort_queries": cohort_queries}
-
- return params, breakdown_filter, breakdown_filter_params, "value"
-
- def _breakdown_prop_params(self, aggregate_operation: str, math_params: dict):
- values_arr, has_more_values = get_breakdown_prop_values(
- self.filter,
- self.entity,
- aggregate_operation,
- self.team,
- extra_params=math_params,
- column_optimizer=self.column_optimizer,
- person_properties_mode=get_person_properties_mode(self.team),
- )
-
- # :TRICKY: We only support string breakdown for event/person properties
- assert isinstance(self.filter.breakdown, str)
-
- breakdown_value = self._get_breakdown_value(self.filter.breakdown)
- breakdown_other_value: str | int = BREAKDOWN_OTHER_STRING_LABEL
- breakdown_null_value: str | int = BREAKDOWN_NULL_STRING_LABEL
- numeric_property_filter = ""
- if self.filter.using_histogram:
- numeric_property_filter = f"AND {breakdown_value} is not null"
- breakdown_value, values_arr = self._get_histogram_breakdown_values(breakdown_value, values_arr)
-
- elif self.filter.breakdown_type == "session" and self.filter.breakdown == "$session_duration":
- # Not adding "Other" for the custom session duration filter.
- pass
- else:
- all_values_are_numeric_or_none = all(
- isinstance(value, int) or isinstance(value, float) or value is None for value in values_arr
- )
- all_values_are_string_or_none = all(isinstance(value, str) or value is None for value in values_arr)
-
- if all_values_are_numeric_or_none:
- breakdown_other_value = BREAKDOWN_OTHER_NUMERIC_LABEL
- breakdown_null_value = BREAKDOWN_NULL_NUMERIC_LABEL
- values_arr = [BREAKDOWN_NULL_NUMERIC_LABEL if value is None else value for value in values_arr]
- else:
- if not all_values_are_string_or_none:
- breakdown_value = f"toString({breakdown_value})"
- breakdown_value = f"nullIf({breakdown_value}, '')"
- values_arr = [BREAKDOWN_NULL_STRING_LABEL if value in (None, "") else value for value in values_arr]
- breakdown_value = f"transform(ifNull({breakdown_value}, %(breakdown_null_value)s), (%(values)s), (%(values)s), %(breakdown_other_value)s)"
-
- if self.filter.using_histogram:
- sql_query = BREAKDOWN_HISTOGRAM_PROP_JOIN_SQL
- elif self.filter.breakdown_hide_other_aggregation:
- sql_query = BREAKDOWN_PROP_JOIN_SQL
- else:
- sql_query = BREAKDOWN_PROP_JOIN_WITH_OTHER_SQL
-
- return (
- {
- "values": (
- [*values_arr, breakdown_other_value]
- if has_more_values and not self.filter.breakdown_hide_other_aggregation
- else values_arr
- ),
- "breakdown_other_value": breakdown_other_value,
- "breakdown_null_value": breakdown_null_value,
- },
- sql_query,
- {
- "breakdown_value_expr": breakdown_value,
- "numeric_property_filter": numeric_property_filter,
- },
- breakdown_value,
- )
-
- def _get_breakdown_value(self, breakdown: str) -> str:
- if self.filter.breakdown_type == "hogql":
- from posthog.hogql.hogql import translate_hogql
-
- breakdown_value = translate_hogql(breakdown, self.filter.hogql_context)
- elif self.filter.breakdown_type == "session":
- if breakdown == "$session_duration":
- # Return the session duration expression right away because it's already an number,
- # so it doesn't need casting for the histogram case (like the other properties)
- breakdown_value = f"{SessionQuery.SESSION_TABLE_ALIAS}.session_duration"
- else:
- raise ValidationError(f'Invalid breakdown "{breakdown}" for breakdown type "session"')
- elif self.person_on_events_mode != PersonsOnEventsMode.DISABLED and self.filter.breakdown_type != "group":
- if self.filter.breakdown_type == "person":
- breakdown_value, _ = get_property_string_expr(
- "events",
- breakdown,
- "%(key)s",
- "person_properties",
- materialised_table_column="person_properties",
- )
- else:
- breakdown_value, _ = get_property_string_expr("events", breakdown, "%(key)s", "properties")
- else:
- if self.filter.breakdown_type == "person":
- breakdown_value, _ = get_property_string_expr("person", breakdown, "%(key)s", "person_props")
- elif self.filter.breakdown_type == "group":
- properties_field = f"group_properties_{self.filter.breakdown_group_type_index}"
- breakdown_value, _ = get_property_string_expr(
- "groups",
- breakdown,
- "%(key)s",
- properties_field,
- materialised_table_column="group_properties",
- )
- else:
- breakdown_value, _ = get_property_string_expr("events", breakdown, "%(key)s", "properties")
-
- if self.filter.using_histogram:
- breakdown_value = f"toFloat64OrNull(toString({breakdown_value}))"
-
- breakdown_value = normalize_url_breakdown(breakdown_value, self.filter.breakdown_normalize_url)
-
- return breakdown_value
-
- def _get_histogram_breakdown_values(self, raw_breakdown_value: str, buckets: list[int]):
- multi_if_conditionals = []
- values_arr = []
-
- if len(buckets) == 1:
- # Only one value, so treat this as a single bucket
- # starting at this value, ending at the same value.
- buckets = [buckets[0], buckets[0]]
-
- for i in range(len(buckets) - 1):
- last_bucket = i == len(buckets) - 2
-
- # Since we always `floor(x, 2)` the value, we add 0.01 to the last bucket
- # to ensure it's always slightly greater than the maximum value
- lower_bound = buckets[i]
- upper_bound = buckets[i + 1] + 0.01 if last_bucket else buckets[i + 1]
- multi_if_conditionals.append(
- f"{raw_breakdown_value} >= {lower_bound} AND {raw_breakdown_value} < {upper_bound}"
- )
- bucket_value = f"[{lower_bound},{upper_bound}]"
- multi_if_conditionals.append(f"'{bucket_value}'")
- values_arr.append(bucket_value)
-
- # else condition
- multi_if_conditionals.append(f"""'["",""]'""")
-
- return f"multiIf({','.join(multi_if_conditionals)})", values_arr
-
- def breakdown_sort_function(self, value):
- if self.filter.using_histogram:
- breakdown_value = value.get("breakdown_value")
- breakdown_value = re.sub(r"\bnan\b", "NaN", breakdown_value) # fix NaN values for JSON loading
- return json.loads(breakdown_value)[0]
- if value.get("breakdown_value") == "all":
- return (-1, "")
- if self.filter.breakdown_type == "session":
- # if session duration breakdown, we want ordering based on the time buckets, not the value
- return (-1, "")
-
- count_or_aggregated_value = value.get("count", value.get("aggregated_value") or 0)
- return count_or_aggregated_value * -1, value.get("label") # reverse it
-
- def _parse_single_aggregate_result(
- self, filter: Filter, entity: Entity, additional_values: dict[str, Any]
- ) -> Callable:
- def _parse(result: list) -> list:
- parsed_results = []
- cache_invalidation_key = generate_short_id()
- for stats in result:
- aggregated_value = stats[0]
- result_descriptors = self._breakdown_result_descriptors(stats[1], filter, entity)
- filter_params = filter.to_params()
- extra_params = {
- "entity_id": entity.id,
- "entity_type": entity.type,
- "entity_math": entity.math,
- "breakdown_value": result_descriptors["breakdown_value"],
- "breakdown_type": filter.breakdown_type or "event",
- }
- parsed_params: dict[str, str] = encode_get_request_params({**filter_params, **extra_params})
- parsed_result = {
- "aggregated_value": (
- float(correct_result_for_sampling(aggregated_value, filter.sampling_factor, entity.math))
- if aggregated_value is not None
- else None
- ),
- "filter": filter_params,
- "persons": {
- "filter": extra_params,
- "url": f"api/projects/{self.team_id}/persons/trends/?{urllib.parse.urlencode(parsed_params)}&cache_invalidation_key={cache_invalidation_key}",
- },
- **result_descriptors,
- **additional_values,
- }
- parsed_results.append(parsed_result)
- try:
- return sorted(parsed_results, key=lambda x: self.breakdown_sort_function(x))
- except TypeError:
- return sorted(parsed_results, key=lambda x: str(self.breakdown_sort_function(x)))
-
- return _parse
-
- def _parse_trend_result(self, filter: Filter, entity: Entity) -> Callable:
- def _parse(result: list) -> list:
- parsed_results = []
- for stats in result:
- result_descriptors = self._breakdown_result_descriptors(stats[2], filter, entity)
- parsed_result = parse_response(stats, filter, additional_values=result_descriptors, entity=entity)
- if self.add_person_urls:
- parsed_result.update(
- {
- "persons_urls": self._get_persons_url(
- filter,
- entity,
- self.team,
- stats[0],
- result_descriptors["breakdown_value"],
- )
- }
- )
- parsed_results.append(parsed_result)
- parsed_result.update({"filter": filter.to_dict()})
-
- try:
- return sorted(parsed_results, key=lambda x: self.breakdown_sort_function(x))
- except TypeError:
- return sorted(parsed_results, key=lambda x: str(self.breakdown_sort_function(x)))
-
- return _parse
-
- def _get_persons_url(
- self,
- filter: Filter,
- entity: Entity,
- team: Team,
- point_dates: list[datetime],
- breakdown_value: Union[str, int],
- ) -> list[dict[str, Any]]:
- persons_url = []
- cache_invalidation_key = generate_short_id()
- for point_date in point_dates:
- point_datetime = datetime(
- point_date.year,
- point_date.month,
- point_date.day,
- getattr(point_date, "hour", 0),
- getattr(point_date, "minute", 0),
- getattr(point_date, "second", 0),
- tzinfo=getattr(point_date, "tzinfo", ZoneInfo("UTC")),
- ).astimezone(ZoneInfo("UTC"))
-
- filter_params = filter.to_params()
- extra_params = {
- "entity_id": entity.id,
- "entity_type": entity.type,
- "entity_math": entity.math,
- "date_from": filter.date_from if filter.display == TRENDS_CUMULATIVE else point_datetime,
- "date_to": offset_time_series_date_by_interval(point_datetime, filter=filter, team=team),
- "breakdown_value": breakdown_value,
- "breakdown_type": filter.breakdown_type or "event",
- }
- parsed_params: dict[str, str] = encode_get_request_params({**filter_params, **extra_params})
- persons_url.append(
- {
- "filter": extra_params,
- "url": f"api/projects/{team.pk}/persons/trends/?{urllib.parse.urlencode(parsed_params)}&cache_invalidation_key={cache_invalidation_key}",
- }
- )
- return persons_url
-
- def _breakdown_result_descriptors(self, breakdown_value, filter: Filter, entity: Entity):
- extra_label = self._determine_breakdown_label(breakdown_value, filter.breakdown_type, breakdown_value)
- if len(filter.entities) > 1:
- # if there are multiple entities in the query, include the entity name in the labels
- label = "{} - {}".format(entity.name, extra_label)
- else:
- label = extra_label
- additional_values = {"label": label}
- if filter.breakdown_type == "cohort":
- additional_values["breakdown_value"] = "all" if breakdown_value == ALL_USERS_COHORT_ID else breakdown_value
- else:
- additional_values["breakdown_value"] = breakdown_value
-
- return additional_values
-
- def _determine_breakdown_label(
- self,
- breakdown_value: int,
- breakdown_type: Optional[str],
- value: Union[str, int],
- ) -> str:
- if breakdown_type == "cohort":
- return get_breakdown_cohort_name(breakdown_value, self.team)
- elif str(value) == BREAKDOWN_OTHER_STRING_LABEL or value == BREAKDOWN_OTHER_NUMERIC_LABEL:
- return BREAKDOWN_OTHER_DISPLAY
- elif str(value) == BREAKDOWN_NULL_STRING_LABEL or value == BREAKDOWN_NULL_NUMERIC_LABEL:
- return BREAKDOWN_NULL_DISPLAY
- else:
- return str(value) or BREAKDOWN_NULL_DISPLAY
-
- def _person_join_condition(self) -> tuple[str, dict]:
- if self.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:
- return "", {}
-
- if self.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS:
- return (
- PERSON_DISTINCT_ID_OVERRIDES_JOIN_SQL.format(
- person_overrides_table_alias=self.PERSON_ID_OVERRIDES_TABLE_ALIAS,
- event_table_alias=self.EVENT_TABLE_ALIAS,
- ),
- {"team_id": self.team_id},
- )
-
- person_query = PersonQuery(self.filter, self.team_id, self.column_optimizer, entity=self.entity)
- event_join = EVENT_JOIN_PERSON_SQL.format(
- GET_TEAM_PERSON_DISTINCT_IDS=get_team_distinct_ids_query(self.team_id)
- )
- if person_query.is_used:
- query, params = person_query.get_query()
- return (
- f"""
- {event_join}
- INNER JOIN ({query}) person
- ON person.id = {self.DISTINCT_ID_TABLE_ALIAS}.person_id
- """,
- params,
- )
- elif (
- self.entity.math in [UNIQUE_USERS, WEEKLY_ACTIVE, MONTHLY_ACTIVE]
- and not self.team.aggregate_users_by_distinct_id
- ) or self.column_optimizer.is_using_cohort_propertes:
- # Only join distinct_ids
- return event_join, {}
- else:
- return "", {}
-
- def _groups_join_condition(self) -> tuple[str, dict]:
- return GroupsJoinQuery(
- self.filter,
- self.team_id,
- self.column_optimizer,
- person_on_events_mode=self.person_on_events_mode,
- ).get_join_query()
-
- def _sessions_join_condition(self) -> tuple[str, dict]:
- session_query = SessionQuery(filter=self.filter, team=self.team)
- if session_query.is_used:
- query, session_params = session_query.get_query()
- return (
- f"""
- INNER JOIN ({query}) {SessionQuery.SESSION_TABLE_ALIAS}
- ON {SessionQuery.SESSION_TABLE_ALIAS}."$session_id" = e."$session_id"
- """,
- session_params,
- )
- return "", {}
diff --git a/posthog/queries/trends/lifecycle.py b/posthog/queries/trends/lifecycle.py
deleted file mode 100644
index d87a841d0a42..000000000000
--- a/posthog/queries/trends/lifecycle.py
+++ /dev/null
@@ -1,195 +0,0 @@
-import urllib
-from collections.abc import Callable
-from typing import Any
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.models.entity import Entity
-from posthog.models.entity.util import get_entity_filtering_params
-from posthog.models.filters import Filter
-from posthog.models.filters.lifecycle_filter import LifecycleFilter
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.models.team import Team
-from posthog.queries.event_query import EventQuery
-from posthog.queries.person_query import PersonQuery
-from posthog.queries.query_date_range import QueryDateRange
-from posthog.queries.trends.sql import LIFECYCLE_EVENTS_QUERY, LIFECYCLE_SQL
-from posthog.queries.trends.util import parse_response
-from posthog.queries.util import get_person_properties_mode
-from posthog.utils import encode_get_request_params, generate_short_id
-
-# Lifecycle takes an event/action, time range, interval and for every period, splits the users who did the action into 4:
-#
-# 1. NEW - Users who did the action during interval and were also created during that period
-# 2. RESURRECTING - Users who did the action during this interval, but not one prior
-# 3. RETURNING - Users who did the action during this interval and prior one
-# 4. DORMANT - Users who did not do the action during this period but did an action the previous period
-#
-# To do this, we need for every period (+1 prior to the first period), list of person_ids who did the event/action
-# during that period and their creation dates.
-
-
-class Lifecycle:
- def _format_lifecycle_query(self, entity: Entity, filter: Filter, team: Team) -> tuple[str, dict, Callable]:
- event_query, event_params = LifecycleEventQuery(
- team=team, filter=filter, person_on_events_mode=team.person_on_events_mode
- ).get_query()
-
- return (
- LIFECYCLE_SQL.format(events_query=event_query, interval_expr=filter.interval),
- event_params,
- self._parse_result(filter, entity, team),
- )
-
- def _parse_result(self, filter: Filter, entity: Entity, team: Team) -> Callable:
- def _parse(result: list) -> list:
- res = []
- for val in result:
- label = "{} - {}".format(entity.name, val[2])
- additional_values = {"label": label, "status": val[2]}
- parsed_result = parse_response(val, filter, additional_values=additional_values, entity=entity)
- parsed_result.update(
- {"persons_urls": self._get_persons_urls(filter, entity, parsed_result["days"], val[2])}
- )
- res.append(parsed_result)
-
- return res
-
- return _parse
-
- def get_people(self, filter: LifecycleFilter, team: Team):
- from posthog.queries.trends.lifecycle_actors import LifecycleActors
-
- _, serialized_actors, _ = LifecycleActors(filter=filter, team=team, limit_actors=True).get_actors()
- return serialized_actors
-
- def _get_persons_urls(self, filter: Filter, entity: Entity, times: list[str], status) -> list[dict[str, Any]]:
- persons_url = []
- cache_invalidation_key = generate_short_id()
- for target_date in times:
- filter_params = filter.to_params()
- extra_params = {
- "entity_id": entity.id,
- "entity_type": entity.type,
- "entity_math": entity.math,
- "target_date": target_date,
- "entity_order": entity.order,
- "lifecycle_type": status,
- }
-
- parsed_params: dict[str, str] = encode_get_request_params({**filter_params, **extra_params})
- persons_url.append(
- {
- "filter": extra_params,
- "url": f"api/person/lifecycle/?{urllib.parse.urlencode(parsed_params)}&cache_invalidation_key={cache_invalidation_key}",
- }
- )
- return persons_url
-
-
-class LifecycleEventQuery(EventQuery):
- _filter: Filter
-
- def get_query(self):
- date_query, date_params = self._get_date_filter()
- self.params.update(date_params)
-
- prop_query, prop_params = self._get_prop_groups(
- self._filter.property_groups,
- person_properties_mode=get_person_properties_mode(self._team),
- person_id_joined_alias=self._person_id_alias,
- )
-
- self.params.update(prop_params)
-
- person_query, person_params = self._get_person_query()
- self.params.update(person_params)
-
- groups_query, groups_params = self._get_groups_query()
- self.params.update(groups_params)
-
- entity_params, entity_format_params = get_entity_filtering_params(
- allowed_entities=[self._filter.entities[0]],
- team_id=self._team_id,
- table_name=self.EVENT_TABLE_ALIAS,
- person_properties_mode=get_person_properties_mode(self._team),
- hogql_context=self._filter.hogql_context,
- )
- self.params.update(entity_params)
-
- entity_prop_query, entity_prop_params = self._get_prop_groups(
- self._filter.entities[0].property_groups,
- person_properties_mode=get_person_properties_mode(self._team),
- person_id_joined_alias=self._person_id_alias,
- prepend="entity_props",
- )
-
- self.params.update(entity_prop_params)
-
- created_at_clause = (
- "person.created_at" if self._person_on_events_mode == PersonsOnEventsMode.DISABLED else "person_created_at"
- )
-
- null_person_filter = (
- ""
- if self._person_on_events_mode == PersonsOnEventsMode.DISABLED
- else f"AND notEmpty({self.EVENT_TABLE_ALIAS}.person_id)"
- )
-
- sample_clause = "SAMPLE %(sampling_factor)s" if self._filter.sampling_factor else ""
- self.params.update({"sampling_factor": self._filter.sampling_factor})
-
- return (
- LIFECYCLE_EVENTS_QUERY.format(
- event_table_alias=self.EVENT_TABLE_ALIAS,
- person_column=self._person_id_alias,
- created_at_clause=created_at_clause,
- distinct_id_query=self._get_person_ids_query(),
- person_query=person_query,
- groups_query=groups_query,
- prop_query=prop_query,
- entity_filter=entity_format_params["entity_query"],
- date_query=date_query,
- null_person_filter=null_person_filter,
- entity_prop_query=entity_prop_query,
- interval=self._filter.interval,
- sample_clause=sample_clause,
- ),
- self.params,
- )
-
- @cached_property
- def _person_query(self):
- return PersonQuery(
- self._filter,
- self._team_id,
- self._column_optimizer,
- extra_fields=["created_at"],
- entity=self._filter.entities[0],
- )
-
- def _get_date_filter(self):
- date_params: dict[str, Any] = {}
- query_date_range = QueryDateRange(self._filter, self._team, should_round=False)
- _, date_from_params = query_date_range.date_from
- _, date_to_params = query_date_range.date_to
- date_params.update(date_from_params)
- date_params.update(date_to_params)
-
- params = {**date_params, "interval": self._filter.interval}
- # :TRICKY: We fetch all data even for the period before the graph starts up until the end of the last period
- return (
- f"""
- AND timestamp >= toDateTime(dateTrunc(%(interval)s, toDateTime(%(date_from)s, %(timezone)s))) - INTERVAL 1 {self._filter.interval}
- AND timestamp < toDateTime(dateTrunc(%(interval)s, toDateTime(%(date_to)s, %(timezone)s))) + INTERVAL 1 {self._filter.interval}
- """,
- params,
- )
-
- def _determine_should_join_distinct_ids(self) -> None:
- self._should_join_distinct_ids = (
- self._person_on_events_mode != PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
- )
-
- def _determine_should_join_persons(self) -> None:
- self._should_join_persons = self._person_on_events_mode == PersonsOnEventsMode.DISABLED
diff --git a/posthog/queries/trends/lifecycle_actors.py b/posthog/queries/trends/lifecycle_actors.py
deleted file mode 100644
index b879d314925b..000000000000
--- a/posthog/queries/trends/lifecycle_actors.py
+++ /dev/null
@@ -1,39 +0,0 @@
-from typing import Optional
-
-from posthog.models.filters.lifecycle_filter import LifecycleFilter
-from posthog.queries.actor_base_query import ActorBaseQuery
-from posthog.queries.trends.lifecycle import LifecycleEventQuery
-from posthog.queries.trends.sql import LIFECYCLE_PEOPLE_SQL
-
-
-class LifecycleActors(ActorBaseQuery):
- event_query_class = LifecycleEventQuery
- _filter: LifecycleFilter
-
- QUERY_TYPE = "lifecycle"
-
- def actor_query(self, limit_actors: Optional[bool] = True) -> tuple[str, dict]:
- events_query, event_params = self.event_query_class(
- filter=self._filter,
- team=self._team,
- person_on_events_mode=self._team.person_on_events_mode,
- ).get_query()
-
- lifecycle_type = self._filter.lifecycle_type
- target_date = self._filter.target_date
-
- return (
- LIFECYCLE_PEOPLE_SQL.format(
- events_query=events_query,
- limit=f"{'LIMIT %(limit)s' if limit_actors else ''}",
- offset=f"{'OFFSET %(offset)s' if limit_actors else ''}",
- ),
- {
- **event_params,
- **self._filter.hogql_context.values,
- "offset": self._filter.offset,
- "limit": self._filter.limit,
- "status": lifecycle_type,
- "target_date": target_date,
- },
- )
diff --git a/posthog/queries/trends/test/__init__.py b/posthog/queries/trends/test/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/posthog/queries/trends/test/__snapshots__/test_breakdowns.ambr b/posthog/queries/trends/test/__snapshots__/test_breakdowns.ambr
deleted file mode 100644
index d2fcaede0b91..000000000000
--- a/posthog/queries/trends/test/__snapshots__/test_breakdowns.ambr
+++ /dev/null
@@ -1,1027 +0,0 @@
-# serializer version: 1
-# name: TestBreakdowns.test_breakdown_by_event_property_of_unique_sessions_with_bucketing
- '''
-
- SELECT arrayCompact(arrayMap(x -> floor(x, 2), quantiles(0.00, 0.33, 0.67, 1.00)(value)))
- FROM
- (SELECT toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) AS value,
- count(DISTINCT e."$session_id") as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value)
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_event_property_of_unique_sessions_with_bucketing.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['[25.0,66.25]',
- '[66.25,98.37]',
- '[98.37,1000.01]'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT e."$session_id") as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- multiIf(toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) >= 25.0
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) < 66.25, '[25.0,66.25]', toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) >= 66.25
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) < 98.37, '[66.25,98.37]', toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) >= 98.37
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) < 1000.01, '[98.37,1000.01]', '["",""]') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) is not null
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_event_property_with_bucketing
- '''
-
- SELECT arrayCompact(arrayMap(x -> floor(x, 2), quantiles(0.00, 0.33, 0.67, 1.00)(value)))
- FROM
- (SELECT toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value)
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_event_property_with_bucketing.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['[25.0,66.25]',
- '[66.25,98.37]',
- '[98.37,1000.01]'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- multiIf(toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) >= 25.0
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) < 66.25, '[25.0,66.25]', toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) >= 66.25
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) < 98.37, '[66.25,98.37]', toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) >= 98.37
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) < 1000.01, '[98.37,1000.01]', '["",""]') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'movie_length'), '^"|"$', ''))) is not null
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_event_property_with_entity_session_filter
- '''
-
- SELECT replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (sessions.session_duration > 30.0)
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_event_property_with_entity_session_filter.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$', 'https://example.com/', 'https://example.com'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'https://example.com/', 'https://example.com']), (['$$_posthog_breakdown_null_$$', 'https://example.com/', 'https://example.com']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND (sessions.session_duration > 30.0)
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_events
- '''
-
- SELECT sessions.session_duration AS value,
- count(*) as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (NOT has(['https://test.com'], replaceRegexpAll(JSONExtractRaw(e.properties, '$current_url'), '^"|"$', '')))
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_events.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT [120, 180, 60, 91, 0] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- sessions.session_duration as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND (NOT has(['https://test.com'], replaceRegexpAll(JSONExtractRaw(e.properties, '$current_url'), '^"|"$', '')))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_events_single_aggregate
- '''
-
- SELECT arrayCompact(arrayMap(x -> floor(x, 2), quantiles(0.00, 0.33, 0.67, 1.00)(value)))
- FROM
- (SELECT toFloat64OrNull(toString(sessions.session_duration)) AS value,
- count(*) as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value)
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_events_single_aggregate.1
- '''
-
- SELECT count(*) AS total,
- multiIf(toFloat64OrNull(toString(sessions.session_duration)) >= 0.0
- AND toFloat64OrNull(toString(sessions.session_duration)) < 69.92, '[0.0,69.92]', toFloat64OrNull(toString(sessions.session_duration)) >= 69.92
- AND toFloat64OrNull(toString(sessions.session_duration)) < 110.72, '[69.92,110.72]', toFloat64OrNull(toString(sessions.session_duration)) >= 110.72
- AND toFloat64OrNull(toString(sessions.session_duration)) < 180.01, '[110.72,180.01]', '["",""]') AS breakdown_value
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND toFloat64OrNull(toString(sessions.session_duration)) is not null
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_events_with_bucketing
- '''
-
- SELECT arrayCompact(arrayMap(x -> floor(x, 2), quantiles(0.00, 0.33, 0.67, 1.00)(value)))
- FROM
- (SELECT toFloat64OrNull(toString(sessions.session_duration)) AS value,
- count(*) as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND (NOT has(['https://test.com'], replaceRegexpAll(JSONExtractRaw(e.properties, '$current_url'), '^"|"$', '')))
- GROUP BY value)
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_events_with_bucketing.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['[0.0,69.92]',
- '[69.92,110.72]',
- '[110.72,180.01]'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- multiIf(toFloat64OrNull(toString(sessions.session_duration)) >= 0.0
- AND toFloat64OrNull(toString(sessions.session_duration)) < 69.92, '[0.0,69.92]', toFloat64OrNull(toString(sessions.session_duration)) >= 69.92
- AND toFloat64OrNull(toString(sessions.session_duration)) < 110.72, '[69.92,110.72]', toFloat64OrNull(toString(sessions.session_duration)) >= 110.72
- AND toFloat64OrNull(toString(sessions.session_duration)) < 180.01, '[110.72,180.01]', '["",""]') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND (NOT has(['https://test.com'], replaceRegexpAll(JSONExtractRaw(e.properties, '$current_url'), '^"|"$', '')))
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND toFloat64OrNull(toString(sessions.session_duration)) is not null
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_unique_sessions
- '''
-
- SELECT sessions.session_duration AS value,
- count(DISTINCT e."$session_id") as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_unique_sessions.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT [180, 120, 91, 60, 0] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT e."$session_id") as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- sessions.session_duration as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_unique_sessions_with_bucketing
- '''
-
- SELECT arrayCompact(arrayMap(x -> floor(x, 2), quantiles(0.00, 0.33, 0.67, 1.00)(value)))
- FROM
- (SELECT toFloat64OrNull(toString(sessions.session_duration)) AS value,
- count(DISTINCT e."$session_id") as count
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") AS sessions ON sessions."$session_id" = e."$session_id"
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value)
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_by_session_duration_of_unique_sessions_with_bucketing.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['[0.0,69.92]',
- '[69.92,110.72]',
- '[110.72,180.01]'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(DISTINCT e."$session_id") as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- multiIf(toFloat64OrNull(toString(sessions.session_duration)) >= 0.0
- AND toFloat64OrNull(toString(sessions.session_duration)) < 69.92, '[0.0,69.92]', toFloat64OrNull(toString(sessions.session_duration)) >= 69.92
- AND toFloat64OrNull(toString(sessions.session_duration)) < 110.72, '[69.92,110.72]', toFloat64OrNull(toString(sessions.session_duration)) >= 110.72
- AND toFloat64OrNull(toString(sessions.session_duration)) < 180.01, '[110.72,180.01]', '["",""]') as breakdown_value
- FROM events e
- INNER JOIN
- (SELECT "$session_id",
- dateDiff('second', min(timestamp), max(timestamp)) as session_duration
- FROM events
- WHERE "$session_id" != ''
- AND team_id = 99999
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC') - INTERVAL 24 HOUR
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC') + INTERVAL 24 HOUR
- GROUP BY "$session_id") sessions ON sessions."$session_id" = e."$session_id"
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND toFloat64OrNull(toString(sessions.session_duration)) is not null
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_histogram_by_missing_property_regression
- '''
-
- SELECT arrayCompact(arrayMap(x -> floor(x, 2), quantiles(0.00, 0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.00)(value)))
- FROM
- (SELECT toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'this_property_does_not_exist'), '^"|"$', ''))) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value)
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_histogram_by_missing_property_regression.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['[nan,nan]'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- multiIf(toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'this_property_does_not_exist'), '^"|"$', ''))) >= nan
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'this_property_does_not_exist'), '^"|"$', ''))) < nan, '[nan,nan]', '["",""]') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND toFloat64OrNull(toString(replaceRegexpAll(JSONExtractRaw(properties, 'this_property_does_not_exist'), '^"|"$', ''))) is not null
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_numeric_hogql
- '''
-
- SELECT length(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 3
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_numeric_hogql.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT [9007199254740990, 19, 9007199254740991] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(length(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '')), 9007199254740990), ([9007199254740990, 19, 9007199254740991]), ([9007199254740990, 19, 9007199254740991]), 9007199254740991) as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_numeric_hogql_hide_other
- '''
-
- SELECT length(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 3
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_numeric_hogql_hide_other.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT [1, 2] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(length(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '')), 9007199254740990), ([9007199254740990, 19]), ([9007199254740990, 19]), 9007199254740991) as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND transform(ifNull(length(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '')), 9007199254740990), ([9007199254740990, 19]), ([9007199254740990, 19]), 9007199254740991) in ([9007199254740990, 19])
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_numeric_hogql_hide_other.2
- '''
-
- SELECT length(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '')) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 4
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_numeric_hogql_hide_other.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT [9007199254740990, 19, 20] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(length(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '')), 9007199254740990), ([9007199254740990, 19, 20]), ([9007199254740990, 19, 20]), 9007199254740991) as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND transform(ifNull(length(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '')), 9007199254740990), ([9007199254740990, 19, 20]), ([9007199254740990, 19, 20]), 9007199254740991) in ([9007199254740990, 19, 20])
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_string_hogql
- '''
-
- SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 3
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_string_hogql.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$', 'https://example.com', '$$_posthog_breakdown_other_$$'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'https://example.com', '$$_posthog_breakdown_other_$$']), (['$$_posthog_breakdown_null_$$', 'https://example.com', '$$_posthog_breakdown_other_$$']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_string_hogql_hide_other
- '''
-
- SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 3
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_string_hogql_hide_other.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$', 'https://example.com'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'https://example.com']), (['$$_posthog_breakdown_null_$$', 'https://example.com']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND transform(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'https://example.com']), (['$$_posthog_breakdown_null_$$', 'https://example.com']), '$$_posthog_breakdown_other_$$') in (['$$_posthog_breakdown_null_$$', 'https://example.com'])
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_string_hogql_hide_other.2
- '''
-
- SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', '') AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 4
- OFFSET 0
- '''
-# ---
-# name: TestBreakdowns.test_breakdown_string_hogql_hide_other.3
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['$$_posthog_breakdown_null_$$', 'https://example.com', 'https://example.com/'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'https://example.com', 'https://example.com/']), (['$$_posthog_breakdown_null_$$', 'https://example.com', 'https://example.com/']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- AND transform(ifNull(nullIf(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(properties, '$current_url'), ''), 'null'), '^"|"$', ''), ''), '$$_posthog_breakdown_null_$$'), (['$$_posthog_breakdown_null_$$', 'https://example.com', 'https://example.com/']), (['$$_posthog_breakdown_null_$$', 'https://example.com', 'https://example.com/']), '$$_posthog_breakdown_other_$$') in (['$$_posthog_breakdown_null_$$', 'https://example.com', 'https://example.com/'])
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
diff --git a/posthog/queries/trends/test/__snapshots__/test_breakdowns_by_current_url.ambr b/posthog/queries/trends/test/__snapshots__/test_breakdowns_by_current_url.ambr
deleted file mode 100644
index 73fdd664d6ef..000000000000
--- a/posthog/queries/trends/test/__snapshots__/test_breakdowns_by_current_url.ambr
+++ /dev/null
@@ -1,131 +0,0 @@
-# serializer version: 1
-# name: TestBreakdownsByCurrentURL.test_breakdown_by_current_url
- '''
-
- SELECT if(empty(trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestBreakdownsByCurrentURL.test_breakdown_by_current_url.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['https://example.com/home', 'https://example.com'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(if(empty(trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$current_url'), '^"|"$', ''))), ''), '$$_posthog_breakdown_null_$$'), (['https://example.com/home', 'https://example.com']), (['https://example.com/home', 'https://example.com']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
-# name: TestBreakdownsByCurrentURL.test_breakdown_by_pathname
- '''
-
- SELECT if(empty(trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$pathname'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$pathname'), '^"|"$', ''))) AS value,
- count(*) as count
- FROM events e
- WHERE team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2020-01-02 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY value
- ORDER BY count DESC, value DESC
- LIMIT 26
- OFFSET 0
- '''
-# ---
-# name: TestBreakdownsByCurrentURL.test_breakdown_by_pathname.1
- '''
-
- SELECT groupArray(day_start) as date,
- groupArray(count) AS total,
- breakdown_value
- FROM
- (SELECT SUM(total) as count,
- day_start,
- breakdown_value
- FROM
- (SELECT *
- FROM
- (SELECT toUInt16(0) AS total,
- ticks.day_start as day_start,
- breakdown_value
- FROM
- (SELECT toStartOfDay(toDateTime('2020-01-12 23:59:59', 'UTC')) - toIntervalDay(number) as day_start
- FROM numbers(11)
- UNION ALL SELECT toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')) as day_start) as ticks
- CROSS JOIN
- (SELECT breakdown_value
- FROM
- (SELECT ['/home', '/'] as breakdown_value) ARRAY
- JOIN breakdown_value) as sec
- ORDER BY breakdown_value,
- day_start
- UNION ALL SELECT count(*) as total,
- toStartOfDay(toTimeZone(toDateTime(timestamp, 'UTC'), 'UTC')) as day_start,
- transform(ifNull(nullIf(if(empty(trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$pathname'), '^"|"$', ''))), '/', trim(TRAILING '/?#'
- from replaceRegexpAll(JSONExtractRaw(properties, '$pathname'), '^"|"$', ''))), ''), '$$_posthog_breakdown_null_$$'), (['/home', '/']), (['/home', '/']), '$$_posthog_breakdown_other_$$') as breakdown_value
- FROM events e
- WHERE e.team_id = 99999
- AND event = 'watched movie'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime(toStartOfDay(toDateTime('2020-01-02 00:00:00', 'UTC')), 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2020-01-12 23:59:59', 'UTC')
- GROUP BY day_start,
- breakdown_value))
- GROUP BY day_start,
- breakdown_value
- ORDER BY breakdown_value,
- day_start)
- GROUP BY breakdown_value
- ORDER BY breakdown_value
- '''
-# ---
diff --git a/posthog/queries/trends/test/__snapshots__/test_person.ambr b/posthog/queries/trends/test/__snapshots__/test_person.ambr
deleted file mode 100644
index b1b7fc89992f..000000000000
--- a/posthog/queries/trends/test/__snapshots__/test_person.ambr
+++ /dev/null
@@ -1,77 +0,0 @@
-# serializer version: 1
-# name: TestPerson.test_group_query_includes_recording_events
- '''
-
- SELECT $group_0 AS actor_id,
- count() AS actor_value ,
- groupUniqArray(100)((timestamp, uuid,
- $session_id,
- $window_id)) as matching_events
- FROM
- (SELECT e.timestamp as timestamp,
- e."$group_0" as "$group_0",
- e."$window_id" as $window_id,
- e."$session_id" as $session_id,
- e.uuid as uuid
- FROM events e
- WHERE team_id = 99999
- AND event = 'pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-21 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-21 23:59:59', 'UTC')
- AND "$group_0" != '')
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
- '''
-# ---
-# name: TestPerson.test_group_query_includes_recording_events.1
- '''
-
- SELECT session_id
- FROM session_replay_events
- WHERE team_id = 99999
- and session_id in ['s1']
- AND min_first_timestamp >= '2021-01-20 00:00:00'
- AND max_last_timestamp <= '2021-01-22 23:59:59'
- GROUP BY session_id
- HAVING max(is_deleted) = 0
- '''
-# ---
-# name: TestPerson.test_person_query_does_not_include_recording_events_if_flag_not_set
- '''
-
- SELECT person_id AS actor_id,
- count() AS actor_value
- FROM
- (SELECT e.timestamp as timestamp,
- if(notEmpty(pdi.distinct_id), pdi.person_id, e.person_id) as person_id,
- e.distinct_id as distinct_id,
- e.team_id as team_id
- FROM events e
- LEFT OUTER JOIN
- (SELECT distinct_id,
- argMax(person_id, version) as person_id
- FROM person_distinct_id2
- WHERE team_id = 99999
- AND distinct_id IN
- (SELECT distinct_id
- FROM events
- WHERE team_id = 99999
- AND event = 'pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-21 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-21 23:59:59', 'UTC'))
- GROUP BY distinct_id
- HAVING argMax(is_deleted, version) = 0) AS pdi ON e.distinct_id = pdi.distinct_id
- WHERE team_id = 99999
- AND event = 'pageview'
- AND toTimeZone(timestamp, 'UTC') >= toDateTime('2021-01-21 00:00:00', 'UTC')
- AND toTimeZone(timestamp, 'UTC') <= toDateTime('2021-01-21 23:59:59', 'UTC'))
- GROUP BY actor_id
- ORDER BY actor_value DESC,
- actor_id DESC
- LIMIT 100
- OFFSET 0
- '''
-# ---
diff --git a/posthog/queries/trends/test/test_breakdowns.py b/posthog/queries/trends/test/test_breakdowns.py
deleted file mode 100644
index 5e7027cd7606..000000000000
--- a/posthog/queries/trends/test/test_breakdowns.py
+++ /dev/null
@@ -1,603 +0,0 @@
-from datetime import datetime
-from typing import Optional
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
-
-from posthog.constants import TRENDS_TABLE
-from posthog.models import Filter
-from posthog.queries.trends.breakdown import (
- BREAKDOWN_NULL_NUMERIC_LABEL,
- BREAKDOWN_NULL_STRING_LABEL,
- BREAKDOWN_OTHER_NUMERIC_LABEL,
- BREAKDOWN_OTHER_STRING_LABEL,
-)
-from posthog.queries.trends.trends import Trends
-from posthog.test.test_journeys import journeys_for
-
-
-class TestBreakdowns(ClickhouseTestMixin, APIBaseTest):
- def setUp(self):
- super().setUp()
- journey = {
- # Duration 0
- "person1": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$session_id": "1",
- "movie_length": 100,
- "$current_url": "https://example.com",
- },
- }
- ],
- # Duration 60 seconds, with 2 events in 1 session
- "person2": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$session_id": "2",
- "movie_length": 50,
- "$current_url": "https://example.com",
- },
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 2),
- "properties": {
- "$session_id": "2",
- "movie_length": 75,
- "$current_url": "https://example.com/",
- },
- },
- ],
- # Duration 90 seconds, but session spans query boundary, so only a single event is counted
- "person3": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 1, 23, 59),
- "properties": {"$session_id": "3"},
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 0, 0, 0),
- "properties": {"$session_id": "3", "movie_length": 25},
- },
- {
- "event": "finished movie",
- "timestamp": datetime(2020, 1, 2, 0, 0, 31),
- "properties": {"$session_id": "3"},
- },
- ],
- # Duration 180.5 seconds, with 2 events counted, each in a different day bucket
- "person4": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 4, 23, 59),
- "properties": {"$session_id": "4", "movie_length": 1000},
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 5, 0, 2, 0, 500000),
- "properties": {"$session_id": "4", "movie_length": 97.5},
- },
- ],
- # Duration 120 seconds, with 2 events counted. Movie length properties are strings
- "person5": [
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 5, 12, 1),
- "properties": {"$session_id": "5", "movie_length": "25"},
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 5, 12, 1),
- "properties": {"$session_id": "5", "movie_length": 25},
- },
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 5, 12, 3),
- "properties": {"$session_id": "5", "movie_length": "not a number"},
- },
- ],
- }
-
- journeys_for(journey, team=self.team, create_people=True)
-
- def _run(self, extra: Optional[dict] = None, events_extra: Optional[dict] = None):
- if events_extra is None:
- events_extra = {}
- if extra is None:
- extra = {}
- response = Trends().run(
- Filter(
- data={
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- **events_extra,
- }
- ],
- "date_from": "2020-01-02T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- **extra,
- },
- team=self.team,
- ),
- self.team,
- )
- return response
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_session_duration_of_events(self):
- response = self._run(
- {
- "breakdown": "$session_duration",
- "breakdown_type": "session",
- "properties": [
- {
- "key": "$current_url",
- "operator": "is_not",
- "value": ["https://test.com"],
- }
- ],
- }
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (0, 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (60, 2.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (91, 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (120, 3.0, [0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (180, 2.0, [0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_session_duration_of_events_with_bucketing(self):
- response = self._run(
- {
- "breakdown": "$session_duration",
- "breakdown_type": "session",
- "breakdown_histogram_bin_count": 3,
- "properties": [
- {
- "key": "$current_url",
- "operator": "is_not",
- "value": ["https://test.com"],
- }
- ],
- }
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (
- "[0.0,69.92]",
- 3.0,
- [3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "[69.92,110.72]",
- 1.0,
- [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "[110.72,180.01]",
- 5.0,
- [0.0, 0.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_session_duration_of_events_single_aggregate(self):
- response = self._run(
- {
- "breakdown": "$session_duration",
- "breakdown_type": "session",
- "breakdown_histogram_bin_count": 3,
- "display": TRENDS_TABLE,
- }
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["aggregated_value"]) for item in response],
- [("[0.0,69.92]", 3), ("[69.92,110.72]", 1), ("[110.72,180.01]", 5)],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_session_duration_of_unique_sessions(self):
- response = self._run(
- {"breakdown": "$session_duration", "breakdown_type": "session"},
- events_extra={"math": "unique_session"},
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (0, 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (60, 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (91, 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (120, 1.0, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (180, 2.0, [0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_session_duration_of_unique_sessions_with_bucketing(self):
- response = self._run(
- {
- "breakdown": "$session_duration",
- "breakdown_type": "session",
- "breakdown_histogram_bin_count": 3,
- },
- events_extra={"math": "unique_session"},
- )
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (
- "[0.0,69.92]",
- 2.0,
- [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "[69.92,110.72]",
- 1.0,
- [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "[110.72,180.01]",
- 3.0,
- [0.0, 0.0, 1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_event_property_with_bucketing(self):
- response = self._run(
- {
- "breakdown": "movie_length",
- "breakdown_type": "event",
- "breakdown_histogram_bin_count": 3,
- }
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (
- "[25.0,66.25]",
- 4.0,
- [2.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "[66.25,98.37]",
- 2.0,
- [1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "[98.37,1000.01]",
- 2.0,
- [1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_event_property_of_unique_sessions_with_bucketing(self):
- response = self._run(
- {
- "breakdown": "movie_length",
- "breakdown_type": "event",
- "breakdown_histogram_bin_count": 3,
- },
- events_extra={"math": "unique_session"},
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (
- "[25.0,66.25]",
- 3.0,
- [2.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "[66.25,98.37]",
- 2.0,
- [1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "[98.37,1000.01]",
- 2.0,
- [1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- ],
- )
-
- def test_breakdown_by_event_property_with_bucketing_and_duplicate_buckets(self):
- journey = {
- "person1": [
- {
- "event": "watched tv",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {"episode_length": 300},
- }
- ],
- "person2": [
- {
- "event": "watched tv",
- "timestamp": datetime(2020, 1, 4, 12, 1),
- "properties": {"episode_length": 300},
- }
- ],
- "person3": [
- {
- "event": "watched tv",
- "timestamp": datetime(2020, 1, 6, 12, 1),
- "properties": {"episode_length": 300},
- }
- ],
- "person4": [
- {
- "event": "watched tv",
- "timestamp": datetime(2020, 1, 8, 12, 1),
- "properties": {"episode_length": 300},
- }
- ],
- }
-
- journeys_for(journey, team=self.team, create_people=True)
-
- # only one unique value, means all quantiles are the same
-
- response = Trends().run(
- Filter(
- data={
- "events": [{"id": "watched tv", "name": "watched tv", "type": "events"}],
- "date_from": "2020-01-02T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "episode_length",
- "breakdown_type": "event",
- "breakdown_histogram_bin_count": 5,
- }
- ),
- self.team,
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (
- "[300.0,300.01]",
- 4.0,
- [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
- )
- ],
- )
-
- def test_breakdown_by_event_property_with_bucketing_and_single_bucket(self):
- journey = {
- "person1": [
- {
- "event": "watched tv",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {"episode_length": 300},
- }
- ],
- "person2": [
- {
- "event": "watched tv",
- "timestamp": datetime(2020, 1, 4, 12, 1),
- "properties": {"episode_length": 300},
- }
- ],
- "person3": [
- {
- "event": "watched tv",
- "timestamp": datetime(2020, 1, 5, 12, 1),
- "properties": {"episode_length": 320},
- }
- ],
- "person4": [
- {
- "event": "watched tv",
- "timestamp": datetime(2020, 1, 6, 12, 1),
- "properties": {"episode_length": 305},
- }
- ],
- }
-
- journeys_for(journey, team=self.team, create_people=True)
-
- response = Trends().run(
- Filter(
- data={
- "events": [{"id": "watched tv", "name": "watched tv", "type": "events"}],
- "date_from": "2020-01-02T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- "breakdown": "episode_length",
- "breakdown_type": "event",
- "breakdown_histogram_bin_count": 1,
- }
- ),
- self.team,
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (
- "[300.0,320.01]",
- 4.0,
- [1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- )
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_event_property_with_entity_session_filter(self):
- response = self._run(
- {"breakdown": "$current_url", "breakdown_type": "event"},
- events_extra={
- "properties": [
- {
- "key": "$session_duration",
- "type": "session",
- "operator": "gt",
- "value": 30,
- }
- ]
- },
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (BREAKDOWN_NULL_STRING_LABEL, 6.0, [1.0, 0.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (
- "https://example.com",
- 1.0,
- [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "https://example.com/",
- 1.0,
- [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_histogram_by_missing_property_regression(self):
- response = self._run(
- {
- "breakdown": "this_property_does_not_exist",
- "breakdown_type": "event",
- "breakdown_histogram_bin_count": 10,
- },
- )
-
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (
- "[nan,nan]",
- 0.0,
- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_numeric_hogql(self):
- response = self._run(
- {
- "breakdown": "length(properties.$current_url)",
- "breakdown_type": "hogql",
- "breakdown_limit": 2,
- },
- )
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (BREAKDOWN_NULL_NUMERIC_LABEL, 6.0, [1.0, 0.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (19, 2.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (BREAKDOWN_OTHER_NUMERIC_LABEL, 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_numeric_hogql_hide_other(self):
- response = self._run(
- {
- "breakdown": "length(properties.$current_url)",
- "breakdown_type": "hogql",
- "breakdown_hide_other_aggregation": True,
- "breakdown_limit": 2,
- },
- )
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (BREAKDOWN_NULL_NUMERIC_LABEL, 6.0, [1.0, 0.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (19, 2.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ],
- )
- response = self._run(
- {
- "breakdown": "length(properties.$current_url)",
- "breakdown_type": "hogql",
- "breakdown_hide_other_aggregation": True,
- "breakdown_limit": 3,
- },
- )
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (BREAKDOWN_NULL_NUMERIC_LABEL, 6.0, [1.0, 0.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (19, 2.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (20, 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_string_hogql(self):
- response = self._run(
- {
- "breakdown": "properties.$current_url",
- "breakdown_type": "hogql",
- "breakdown_limit": 2,
- },
- )
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (BREAKDOWN_NULL_STRING_LABEL, 6.0, [1.0, 0.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ("https://example.com", 2.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- (BREAKDOWN_OTHER_STRING_LABEL, 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ],
- )
-
- @snapshot_clickhouse_queries
- def test_breakdown_string_hogql_hide_other(self):
- response = self._run(
- {
- "breakdown": "properties.$current_url",
- "breakdown_type": "hogql",
- "breakdown_hide_other_aggregation": True,
- "breakdown_limit": 2,
- },
- )
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (BREAKDOWN_NULL_STRING_LABEL, 6.0, [1.0, 0.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ("https://example.com", 2.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ],
- )
- response = self._run(
- {
- "breakdown": "properties.$current_url",
- "breakdown_type": "hogql",
- "breakdown_hide_other_aggregation": True,
- "breakdown_limit": 3,
- },
- )
- self.assertEqual(
- [(item["breakdown_value"], item["count"], item["data"]) for item in response],
- [
- (BREAKDOWN_NULL_STRING_LABEL, 6.0, [1.0, 0.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ("https://example.com", 2.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ("https://example.com/", 1.0, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ],
- )
diff --git a/posthog/queries/trends/test/test_breakdowns_by_current_url.py b/posthog/queries/trends/test/test_breakdowns_by_current_url.py
deleted file mode 100644
index 093565aa62ea..000000000000
--- a/posthog/queries/trends/test/test_breakdowns_by_current_url.py
+++ /dev/null
@@ -1,160 +0,0 @@
-from datetime import datetime
-from typing import Optional
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
-
-from posthog.models import Filter
-from posthog.queries.trends.trends import Trends
-from posthog.test.test_journeys import journeys_for
-
-
-class TestBreakdownsByCurrentURL(ClickhouseTestMixin, APIBaseTest):
- def setUp(self):
- super().setUp()
- journey = {
- "person1": [
- # no trailing slash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com",
- "$pathname": "",
- },
- },
- # trailing question mark
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com?",
- "$pathname": "?",
- },
- },
- ],
- "person2": [
- # trailing slash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com/",
- "$pathname": "/",
- },
- },
- # trailing hash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com#",
- "$pathname": "#",
- },
- },
- ],
- "person3": [
- # no trailing slash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com/home",
- "$pathname": "/home",
- },
- },
- ],
- "person4": [
- # trailing slash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com/home/",
- "$pathname": "/home/",
- },
- },
- # trailing hash
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com/home#",
- "$pathname": "/home#",
- },
- },
- # all the things
- {
- "event": "watched movie",
- "timestamp": datetime(2020, 1, 2, 12, 1),
- "properties": {
- "$current_url": "https://example.com/home/?#",
- "$pathname": "/home/?#",
- },
- },
- ],
- }
-
- journeys_for(journey, team=self.team, create_people=True)
-
- def _run(self, extra: Optional[dict] = None, events_extra: Optional[dict] = None):
- if events_extra is None:
- events_extra = {}
- if extra is None:
- extra = {}
- response = Trends().run(
- Filter(
- data={
- "events": [
- {
- "id": "watched movie",
- "name": "watched movie",
- "type": "events",
- **events_extra,
- }
- ],
- "date_from": "2020-01-02T00:00:00Z",
- "date_to": "2020-01-12T00:00:00Z",
- **extra,
- }
- ),
- self.team,
- )
- return response
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_pathname(self) -> None:
- response = self._run(
- {
- "breakdown": "$pathname",
- "breakdown_type": "event",
- "breakdown_normalize_url": True,
- }
- )
-
- assert [(item["breakdown_value"], item["count"], item["data"]) for item in response] == [
- ("/", 4.0, [4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ("/home", 4.0, [4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
- ]
-
- @snapshot_clickhouse_queries
- def test_breakdown_by_current_url(self) -> None:
- response = self._run(
- {
- "breakdown": "$current_url",
- "breakdown_type": "event",
- "breakdown_normalize_url": True,
- }
- )
-
- assert [(item["breakdown_value"], item["count"], item["data"]) for item in response] == [
- (
- "https://example.com",
- 4.0,
- [4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- (
- "https://example.com/home",
- 4.0,
- [4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
- ),
- ]
diff --git a/posthog/queries/trends/test/test_paging_breakdowns.py b/posthog/queries/trends/test/test_paging_breakdowns.py
deleted file mode 100644
index 4f506ca1a6ad..000000000000
--- a/posthog/queries/trends/test/test_paging_breakdowns.py
+++ /dev/null
@@ -1,97 +0,0 @@
-from typing import Optional
-
-from freezegun import freeze_time
-from posthog.test.base import APIBaseTest
-
-from posthog.models import Filter
-from posthog.queries.trends.trends import Trends
-from posthog.test.test_journeys import journeys_for
-
-BREAKDOWN_OTHER_DISPLAY = "Other (i.e. all remaining values)"
-
-
-class TestPagingBreakdowns(APIBaseTest):
- """
- A test to explore a report from a customer
- https://posthog.slack.com/archives/C02LR7352SG/p1643738897887099
- """
-
- CLASS_DATA_LEVEL_SETUP = False
-
- def setUp(self):
- super().setUp()
-
- # create 2 pages of events each with a unique property
- with freeze_time("2020-01-02T13:01:01Z"):
- journeys_for(
- events_by_person={
- "p1": [
- {
- "team": self.team,
- "event": "$pageview",
- "distinct_id": "blabla",
- "properties": {"wildcard_route": f"/1/*/{i}"},
- }
- for i in range(50)
- ]
- },
- team=self.team,
- create_people=True,
- )
-
- def _run(self, extra: Optional[dict] = None, run_at: Optional[str] = None):
- if extra is None:
- extra = {}
- with freeze_time(run_at or "2020-01-04T13:01:01Z"):
- action_response = Trends().run(
- Filter(
- data={
- "events": [
- {
- "id": "$pageview",
- "name": "$pageview",
- "type": "events",
- "order": 0,
- }
- ],
- **extra,
- }
- ),
- self.team,
- )
- return action_response
-
- def test_with_breakdown_loads_two_unqiue_pages_of_values(self):
- response = self._run({"breakdown": "wildcard_route", "breakdown_type": "event"})
-
- assert len(response) == 26
- page_labels = [r["label"] for r in response if r["label"] != BREAKDOWN_OTHER_DISPLAY]
- assert len(page_labels) == 25
- assert sorted(page_labels), sorted(set(page_labels)) # all values are unique
-
- second_page_response = self._run({"breakdown": "wildcard_route", "breakdown_type": "event", "offset": 25})
- second_page_labels = [r["label"] for r in second_page_response if r["label"] != BREAKDOWN_OTHER_DISPLAY]
-
- assert len(page_labels) == len(second_page_labels) # should be two pages of different results
-
- assert sorted(second_page_labels) == sorted(set(second_page_labels)) # all values are unique
-
- # no values from page one should be in page two
- assert [value for value in second_page_labels if value in page_labels] == []
-
- all_pages_response = self._run(
- {"breakdown": "wildcard_route", "breakdown_type": "event", "offset": 0, "breakdown_limit": 50}
- )
- all_pages_labels = [r["label"] for r in all_pages_response]
-
- assert len(all_pages_labels) == 50
- assert set(all_pages_labels) == set(page_labels + second_page_labels)
-
- def test_without_breakdown(self):
- response = self._run({})
-
- self.assertEqual(len(response), 1)
- self.assertEqual(response[0]["label"], "$pageview")
-
- self.assertEqual(response[0]["data"], [0.0, 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, 0.0])
- self.assertEqual(response[0]["count"], 50.0)
diff --git a/posthog/queries/trends/test/test_person.py b/posthog/queries/trends/test/test_person.py
deleted file mode 100644
index 908bcd5f1d89..000000000000
--- a/posthog/queries/trends/test/test_person.py
+++ /dev/null
@@ -1,182 +0,0 @@
-from uuid import UUID
-
-from freezegun.api import freeze_time
-from posthog.test.base import (
- APIBaseTest,
- ClickhouseTestMixin,
- _create_event,
- _create_person,
- snapshot_clickhouse_queries,
-)
-
-from django.utils import timezone
-
-from dateutil.relativedelta import relativedelta
-
-from posthog.models.entity import Entity
-from posthog.models.filters import Filter
-from posthog.models.group.util import create_group
-from posthog.queries.trends.trends_actors import TrendsActors
-from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
-from posthog.test.test_utils import create_group_type_mapping_without_created_at
-
-
-class TestPerson(ClickhouseTestMixin, APIBaseTest):
- # Note: not using `@snapshot_clickhouse_queries` here because the ordering of the session_ids in the recording
- # query is not guaranteed, so adding it would lead to a flaky test.
- @freeze_time("2021-01-21T20:00:00.000Z")
- def test_person_query_includes_recording_events(self):
- _create_person(team_id=self.team.pk, distinct_ids=["u1"], properties={"email": "bla"})
- _create_event(
- event="pageview", distinct_id="u1", team=self.team, timestamp=timezone.now()
- ) # No $session_id, so not included
- _create_event(
- event="pageview",
- distinct_id="u1",
- team=self.team,
- timestamp=timezone.now(),
- properties={"$session_id": "s2", "$window_id": "w2"},
- ) # No associated recording, so not included
- timestamp = timezone.now()
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s1",
- distinct_id="u1",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- )
-
- _create_event(
- event="pageview",
- distinct_id="u1",
- team=self.team,
- timestamp=timezone.now() + relativedelta(hours=2),
- properties={"$session_id": "s1", "$window_id": "w1"},
- event_uuid="b06e5a5e-e001-4293-af81-ac73e194569d",
- )
- _create_event(
- event="pageview",
- distinct_id="u1",
- team=self.team,
- timestamp=timezone.now() + relativedelta(hours=3),
- properties={"$session_id": "s1", "$window_id": "w1"},
- event_uuid="206e5a5e-e001-4293-af81-ac73e194569d",
- )
- event = {"id": "pageview", "name": "pageview", "type": "events", "order": 0}
- filter = Filter(
- data={
- "date_from": "2021-01-21T00:00:00Z",
- "date_to": "2021-01-21T23:59:59Z",
- "events": [event],
- "include_recordings": "true",
- }
- )
- entity = Entity(event)
-
- _, serialized_actors, _ = TrendsActors(self.team, entity, filter).get_actors()
- self.assertEqual(len(serialized_actors), 1)
- self.assertEqual(len(serialized_actors[0]["matched_recordings"]), 1)
- self.assertEqual(serialized_actors[0]["matched_recordings"][0]["session_id"], "s1")
- self.assertCountEqual(
- serialized_actors[0]["matched_recordings"][0]["events"],
- [
- {
- "window_id": "w1",
- "timestamp": timezone.now() + relativedelta(hours=3),
- "uuid": UUID("206e5a5e-e001-4293-af81-ac73e194569d"),
- },
- {
- "window_id": "w1",
- "timestamp": timezone.now() + relativedelta(hours=2),
- "uuid": UUID("b06e5a5e-e001-4293-af81-ac73e194569d"),
- },
- ],
- )
-
- @snapshot_clickhouse_queries
- @freeze_time("2021-01-21T20:00:00.000Z")
- def test_person_query_does_not_include_recording_events_if_flag_not_set(self):
- _create_person(team_id=self.team.pk, distinct_ids=["u1"], properties={"email": "bla"})
- _create_event(event="pageview", distinct_id="u1", team=self.team, timestamp=timezone.now())
-
- event = {"id": "pageview", "name": "pageview", "type": "events", "order": 0}
- filter = Filter(
- data={
- "date_from": "2021-01-21T00:00:00Z",
- "date_to": "2021-01-21T23:59:59Z",
- "events": [event],
- }
- )
- entity = Entity(event)
- _, serialized_actors, _ = TrendsActors(self.team, entity, filter).get_actors()
-
- self.assertEqual(serialized_actors[0].get("matched_recordings"), [])
-
- @snapshot_clickhouse_queries
- @freeze_time("2021-01-21T20:00:00.000Z")
- def test_group_query_includes_recording_events(self):
- create_group_type_mapping_without_created_at(
- team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0
- )
- create_group(team_id=self.team.pk, group_type_index=0, group_key="bla", properties={})
- timestamp = timezone.now()
- produce_replay_summary(
- team_id=self.team.pk,
- session_id="s1",
- distinct_id="u1",
- first_timestamp=timestamp,
- last_timestamp=timestamp,
- )
-
- _create_event(
- event="pageview",
- distinct_id="u1",
- team=self.team,
- timestamp=timezone.now(),
- properties={"$group_0": "bla"},
- )
- _create_event(
- event="pageview",
- distinct_id="u1",
- team=self.team,
- timestamp=timezone.now() + relativedelta(hours=2),
- properties={"$session_id": "s1", "$window_id": "w1", "$group_0": "bla"},
- event_uuid="b06e5a5e-e001-4293-af81-ac73e194569d",
- )
-
- event = {
- "id": "pageview",
- "name": "pageview",
- "type": "events",
- "order": 0,
- "math": "unique_group",
- "math_group_type_index": 0,
- }
-
- filter = Filter(
- data={
- "date_from": "2021-01-21T00:00:00Z",
- "date_to": "2021-01-21T23:59:59Z",
- "events": [event],
- "include_recordings": "true",
- }
- )
- entity = Entity(event)
-
- _, serialized_actors, _ = TrendsActors(self.team, entity, filter).get_actors()
-
- self.assertCountEqual(
- serialized_actors[0].get("matched_recordings", []),
- [
- {
- "session_id": "s1",
- "events": [
- {
- "window_id": "w1",
- "timestamp": timezone.now() + relativedelta(hours=2),
- "uuid": UUID("b06e5a5e-e001-4293-af81-ac73e194569d"),
- }
- ],
- }
- ],
- )
diff --git a/posthog/queries/trends/total_volume.py b/posthog/queries/trends/total_volume.py
deleted file mode 100644
index 339deb4ab513..000000000000
--- a/posthog/queries/trends/total_volume.py
+++ /dev/null
@@ -1,315 +0,0 @@
-import urllib.parse
-from collections.abc import Callable
-from datetime import date, datetime, timedelta
-from typing import Any, Union
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.clickhouse.query_tagging import tag_queries
-from posthog.constants import (
- MONTHLY_ACTIVE,
- NON_TIME_SERIES_DISPLAY_TYPES,
- TRENDS_CUMULATIVE,
- UNIQUE_GROUPS,
- UNIQUE_USERS,
- WEEKLY_ACTIVE,
-)
-from posthog.models.entity import Entity
-from posthog.models.event.sql import NULL_SQL
-from posthog.models.filters import Filter
-from posthog.models.team import Team
-from posthog.queries.event_query import EventQuery
-from posthog.queries.trends.sql import (
- ACTIVE_USERS_AGGREGATE_SQL,
- ACTIVE_USERS_SQL,
- CUMULATIVE_SQL,
- FINAL_TIME_SERIES_SQL,
- SESSION_DURATION_AGGREGATE_SQL,
- SESSION_DURATION_SQL,
- VOLUME_AGGREGATE_SQL,
- VOLUME_PER_ACTOR_AGGREGATE_SQL,
- VOLUME_PER_ACTOR_SQL,
- VOLUME_SQL,
-)
-from posthog.queries.trends.trends_event_query import TrendsEventQuery
-from posthog.queries.trends.util import (
- COUNT_PER_ACTOR_MATH_FUNCTIONS,
- PROPERTY_MATH_FUNCTIONS,
- determine_aggregator,
- enumerate_time_range,
- offset_time_series_date_by_interval,
- parse_response,
- process_math,
-)
-from posthog.queries.util import TIME_IN_SECONDS, get_interval_func_ch, get_start_of_interval_sql
-from posthog.utils import encode_get_request_params, generate_short_id
-
-
-class TrendsTotalVolume:
- DISTINCT_ID_TABLE_ALIAS = EventQuery.DISTINCT_ID_TABLE_ALIAS
- EVENT_TABLE_ALIAS = EventQuery.EVENT_TABLE_ALIAS
- PERSON_ID_OVERRIDES_TABLE_ALIAS = EventQuery.PERSON_ID_OVERRIDES_TABLE_ALIAS
-
- def _total_volume_query(self, entity: Entity, filter: Filter, team: Team) -> tuple[str, dict, Callable]:
- interval_func = get_interval_func_ch(filter.interval)
-
- person_id_alias = f"{self.DISTINCT_ID_TABLE_ALIAS}.person_id"
- if team.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS:
- person_id_alias = f"if(notEmpty({self.PERSON_ID_OVERRIDES_TABLE_ALIAS}.person_id), {self.PERSON_ID_OVERRIDES_TABLE_ALIAS}.person_id, {self.EVENT_TABLE_ALIAS}.person_id)"
- elif team.person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:
- person_id_alias = f"{self.EVENT_TABLE_ALIAS}.person_id"
-
- aggregate_operation, join_condition, math_params = process_math(
- entity,
- team,
- filter=filter,
- event_table_alias=TrendsEventQuery.EVENT_TABLE_ALIAS,
- person_id_alias=person_id_alias,
- )
-
- trend_event_query = TrendsEventQuery(
- filter=filter,
- entity=entity,
- team=team,
- should_join_distinct_ids=(
- True
- if join_condition != ""
- or (entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE] and not team.aggregate_users_by_distinct_id)
- else False
- ),
- person_on_events_mode=team.person_on_events_mode,
- )
- event_query_base, event_query_params = trend_event_query.get_query_base()
-
- content_sql_params = {
- "aggregate_operation": aggregate_operation,
- "timestamp": "e.timestamp",
- "interval_func": interval_func,
- }
- params: dict = {"team_id": team.id, "timezone": team.timezone}
- params = {**params, **math_params, **event_query_params}
-
- if filter.display in NON_TIME_SERIES_DISPLAY_TYPES:
- tag_queries(trend_volume_display="non_time_series")
- if entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE]:
- tag_queries(trend_volume_type="active_users")
- content_sql = ACTIVE_USERS_AGGREGATE_SQL.format(
- event_query_base=event_query_base,
- aggregator="distinct_id" if team.aggregate_users_by_distinct_id else "person_id",
- **content_sql_params,
- **trend_event_query.active_user_params,
- )
- elif entity.math in PROPERTY_MATH_FUNCTIONS and entity.math_property == "$session_duration":
- # TODO: When we add more person/group properties to math_property,
- # generalise this query to work for everything, not just sessions.
- tag_queries(trend_volume_type="session_duration_math")
- content_sql = SESSION_DURATION_AGGREGATE_SQL.format(
- event_query_base=event_query_base, **content_sql_params
- )
- elif entity.math in COUNT_PER_ACTOR_MATH_FUNCTIONS:
- tag_queries(trend_volume_type="count_per_actor")
- content_sql = VOLUME_PER_ACTOR_AGGREGATE_SQL.format(
- event_query_base=event_query_base,
- **content_sql_params,
- aggregator=determine_aggregator(entity, team),
- )
- else:
- if entity.math == "hogql":
- tag_queries(trend_volume_type="hogql")
- else:
- tag_queries(trend_volume_type="volume_aggregate")
- content_sql = VOLUME_AGGREGATE_SQL.format(event_query_base=event_query_base, **content_sql_params)
-
- return (
- content_sql,
- params,
- self._parse_aggregate_volume_result(filter, entity, team.id),
- )
- else:
- tag_queries(trend_volume_display="time_series")
- null_sql = NULL_SQL.format(
- date_to_truncated=get_start_of_interval_sql(filter.interval, team=team, source="%(date_to)s"),
- date_from_truncated=get_start_of_interval_sql(filter.interval, team=team, source="%(date_from)s"),
- interval_func=interval_func,
- )
-
- if entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE]:
- tag_queries(trend_volume_type="active_users")
- content_sql = ACTIVE_USERS_SQL.format(
- event_query_base=event_query_base,
- parsed_date_to=trend_event_query.parsed_date_to,
- parsed_date_from=trend_event_query.parsed_date_from,
- aggregator=determine_aggregator(entity, team), # TODO: Support groups officialy and with tests
- date_to_truncated=get_start_of_interval_sql(filter.interval, team=team, source="%(date_to)s"),
- date_from_active_users_adjusted_truncated=get_start_of_interval_sql(
- filter.interval,
- team=team,
- source="%(date_from_active_users_adjusted)s",
- ),
- **content_sql_params,
- **trend_event_query.active_user_params,
- )
- elif filter.display == TRENDS_CUMULATIVE and entity.math in (
- UNIQUE_USERS,
- UNIQUE_GROUPS,
- ):
- # :TODO: Consider using bitmap-per-date to speed this up
- tag_queries(trend_volume_type="cumulative_actors")
- cumulative_sql = CUMULATIVE_SQL.format(
- actor_expression=determine_aggregator(entity, team),
- event_query_base=event_query_base,
- )
- content_sql_params["aggregate_operation"] = "COUNT(DISTINCT actor_id)"
- content_sql = VOLUME_SQL.format(
- timestamp_truncated=get_start_of_interval_sql(
- filter.interval, team=team, source="first_seen_timestamp"
- ),
- event_query_base=f"FROM ({cumulative_sql})",
- **content_sql_params,
- )
- elif entity.math in COUNT_PER_ACTOR_MATH_FUNCTIONS:
- tag_queries(trend_volume_type="count_per_actor")
- # Calculate average number of events per actor
- # (only including actors with at least one matching event in a period)
- content_sql = VOLUME_PER_ACTOR_SQL.format(
- event_query_base=event_query_base,
- aggregator=determine_aggregator(entity, team),
- timestamp_truncated=get_start_of_interval_sql(filter.interval, team=team),
- **content_sql_params,
- )
- elif entity.math_property == "$session_duration":
- tag_queries(trend_volume_type="session_duration_math")
- # TODO: When we add more person/group properties to math_property,
- # generalise this query to work for everything, not just sessions.
- content_sql = SESSION_DURATION_SQL.format(
- event_query_base=event_query_base,
- timestamp_truncated=get_start_of_interval_sql(filter.interval, team=team),
- **content_sql_params,
- )
- else:
- if entity.math == "hogql":
- tag_queries(trend_volume_type="hogql")
- else:
- tag_queries(trend_volume_type="volume")
- content_sql = VOLUME_SQL.format(
- event_query_base=event_query_base,
- timestamp_truncated=get_start_of_interval_sql(filter.interval, team=team),
- **content_sql_params,
- )
-
- params["interval"] = filter.interval
-
- # If we have a smoothing interval > 1 then add in the sql to
- # handling rolling average. Else just do a sum. This is possibly an
- # nessacary optimization.
- if filter.smoothing_intervals > 1:
- smoothing_operation = f"""
- AVG(SUM(total))
- OVER (
- ORDER BY day_start
- ROWS BETWEEN {filter.smoothing_intervals - 1} PRECEDING
- AND CURRENT ROW
- )"""
- else:
- smoothing_operation = "SUM(total)"
-
- final_query = FINAL_TIME_SERIES_SQL.format(
- null_sql=null_sql,
- content_sql=content_sql,
- smoothing_operation=smoothing_operation,
- aggregate="count" if filter.smoothing_intervals < 2 else "floor(count)",
- )
-
- return final_query, params, self._parse_total_volume_result(filter, entity, team)
-
- def _parse_total_volume_result(self, filter: Filter, entity: Entity, team: Team) -> Callable:
- def _parse(result: list) -> list:
- parsed_results = []
- if result is not None:
- for stats in result:
- parsed_result = parse_response(stats, filter, entity=entity)
- point_dates: list[Union[datetime, date]] = stats[0]
- # Ensure we have datetimes for all points
- point_datetimes: list[datetime] = [
- datetime.combine(d, datetime.min.time()) if not isinstance(d, datetime) else d
- for d in point_dates
- ]
- parsed_result.update({"persons_urls": self._get_persons_url(filter, entity, team, point_datetimes)})
- parsed_results.append(parsed_result)
- parsed_result.update({"filter": filter.to_dict()})
- return parsed_results
-
- return _parse
-
- def _parse_aggregate_volume_result(self, filter: Filter, entity: Entity, team_id: int) -> Callable:
- def _parse(result: list) -> list:
- aggregated_value = result[0][0] if result else 0
- seconds_in_interval = TIME_IN_SECONDS[filter.interval]
- time_range = enumerate_time_range(filter, seconds_in_interval)
- filter_params = filter.to_params()
- extra_params = {
- "entity_id": entity.id,
- "entity_type": entity.type,
- "entity_math": entity.math,
- "entity_order": entity.order,
- }
- parsed_params: dict[str, str] = encode_get_request_params({**filter_params, **extra_params})
- cache_invalidation_key = generate_short_id()
-
- return [
- {
- "aggregated_value": aggregated_value,
- "days": time_range,
- "filter": filter_params,
- "persons": {
- "filter": extra_params,
- "url": f"api/projects/{team_id}/persons/trends/?{urllib.parse.urlencode(parsed_params)}&cache_invalidation_key={cache_invalidation_key}",
- },
- }
- ]
-
- return _parse
-
- def _offset_date_from(self, point_datetime: datetime, filter: Filter, entity: Entity) -> datetime | None:
- if filter.display == TRENDS_CUMULATIVE:
- return filter.date_from
- elif entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE]:
- # :TRICKY: We have to offset the date by one, as the final query already subtracts 7 days
- return point_datetime + timedelta(days=1)
- else:
- return point_datetime
-
- def _offset_date_to(self, point_datetime: datetime, filter: Filter, entity: Entity, team: Team) -> datetime:
- if entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE]:
- return point_datetime
- else:
- return offset_time_series_date_by_interval(point_datetime, filter=filter, team=team)
-
- def _get_persons_url(
- self,
- filter: Filter,
- entity: Entity,
- team: Team,
- point_datetimes: list[datetime],
- ) -> list[dict[str, Any]]:
- persons_url = []
- cache_invalidation_key = generate_short_id()
- for point_datetime in point_datetimes:
- filter_params = filter.to_params()
- extra_params = {
- "entity_id": entity.id,
- "entity_type": entity.type,
- "entity_math": entity.math,
- "date_from": self._offset_date_from(point_datetime, filter=filter, entity=entity),
- "date_to": self._offset_date_to(point_datetime, filter=filter, entity=entity, team=team),
- "entity_order": entity.order,
- }
-
- parsed_params: dict[str, str] = encode_get_request_params({**filter_params, **extra_params})
- persons_url.append(
- {
- "filter": extra_params,
- "url": f"api/projects/{team.pk}/persons/trends/?{urllib.parse.urlencode(parsed_params)}&cache_invalidation_key={cache_invalidation_key}",
- }
- )
- return persons_url
diff --git a/posthog/queries/trends/trends.py b/posthog/queries/trends/trends.py
deleted file mode 100644
index 2be8ffff58a5..000000000000
--- a/posthog/queries/trends/trends.py
+++ /dev/null
@@ -1,315 +0,0 @@
-import copy
-import threading
-from collections.abc import Callable
-from datetime import datetime, timedelta
-from itertools import accumulate
-from typing import Any, Optional, cast
-from zoneinfo import ZoneInfo
-
-import posthoganalytics
-from dateutil import parser
-
-from posthog.clickhouse.query_tagging import QueryTags, get_query_tags, update_tags
-from posthog.constants import (
- INSIGHT_LIFECYCLE,
- NON_BREAKDOWN_DISPLAY_TYPES,
- TREND_FILTER_TYPE_ACTIONS,
- TRENDS_CUMULATIVE,
- TRENDS_LIFECYCLE,
- TRENDS_LINEAR,
-)
-from posthog.models.entity import Entity
-from posthog.models.filters import Filter
-from posthog.models.team import Team
-from posthog.queries.base import handle_compare
-from posthog.queries.insight import insight_sync_execute
-from posthog.queries.trends.breakdown import TrendsBreakdown
-from posthog.queries.trends.lifecycle import Lifecycle
-from posthog.queries.trends.total_volume import TrendsTotalVolume
-from posthog.utils import generate_cache_key, get_safe_cache
-
-from products.actions.backend.models.action import Action
-
-
-class Trends(TrendsTotalVolume, Lifecycle):
- def _get_sql_for_entity(self, filter: Filter, team: Team, entity: Entity) -> tuple[str, str, dict, Callable]:
- if filter.breakdown and filter.display not in NON_BREAKDOWN_DISPLAY_TYPES:
- query_type = "trends_breakdown"
- sql, params, parse_function = TrendsBreakdown(
- entity,
- filter,
- team,
- person_on_events_mode=team.person_on_events_mode,
- add_person_urls=not self.is_csv_export,
- ).get_query()
- elif filter.insight == INSIGHT_LIFECYCLE or filter.shown_as == TRENDS_LIFECYCLE:
- query_type = "trends_lifecycle"
- sql, params, parse_function = self._format_lifecycle_query(entity, filter, team)
- else:
- query_type = "trends_total_volume"
- sql, params, parse_function = self._total_volume_query(entity, filter, team)
-
- return query_type, sql, params, parse_function
-
- # Use cached result even on refresh if team has strict caching enabled
- def get_cached_result(self, filter: Filter, team: Team) -> Optional[list[dict[str, Any]]]:
- if not team.strict_caching_enabled or filter.breakdown or filter.display != TRENDS_LINEAR:
- return None
-
- cache_key = generate_cache_key(team.pk, f"{filter.toJSON()}_{team.pk}")
- cached_result_package = get_safe_cache(cache_key)
- cached_result = (
- cached_result_package.get("result")
- if cached_result_package and isinstance(cached_result_package, dict)
- else None
- )
-
- if not cached_result:
- return None
-
- _is_present = self.is_present_timerange(cached_result, filter, team)
-
- return cached_result if _is_present else None
-
- # Determine if the current timerange is present in the cache
- def is_present_timerange(self, cached_result: list[dict[str, Any]], filter: Filter, team: Team) -> bool:
- if (
- len(cached_result) > 0
- and cached_result[0].get("days")
- and cached_result[0].get("data")
- and len(cached_result[0]["days"]) > 0
- and len(cached_result[0]["days"]) == len(cached_result[0]["data"])
- ):
- latest_date = cached_result[0]["days"][len(cached_result[0]["days"]) - 1]
-
- parsed_latest_date = parser.parse(latest_date)
- parsed_latest_date = parsed_latest_date.replace(tzinfo=ZoneInfo(team.timezone))
- _is_present = is_filter_date_present(filter, parsed_latest_date)
- else:
- _is_present = False
-
- return _is_present
-
- # Use a condensed filter if a cached result exists in the current timerange
- def adjusted_filter(self, filter: Filter, team: Team) -> tuple[Filter, Optional[dict[str, Any]]]:
- cached_result = self.get_cached_result(filter, team)
-
- new_filter = filter.shallow_clone({"date_from": interval_unit(filter.interval)}) if cached_result else filter
-
- label_to_payload = {}
- if cached_result:
- for payload in cached_result:
- label_to_payload[f"{payload['label']}_{payload['action']['order']}"] = payload
-
- return new_filter, label_to_payload
-
- def merge_results(
- self,
- result,
- cached_result: Optional[dict[str, Any]],
- entity_order: int,
- filter: Filter,
- team: Team,
- ):
- if cached_result and filter.display != TRENDS_CUMULATIVE:
- new_res = []
-
- for payload in result:
- cached_series = cached_result.pop(f"{payload['label']}_{entity_order}")
- data = cached_series["data"]
- data.pop()
- data.append(payload["data"].pop())
- cached_series["data"] = data
- new_res.append(cached_series)
-
- return new_res, cached_result
- elif filter.display == TRENDS_CUMULATIVE:
- return self._handle_cumulative(result), {}
- else:
- return result, {}
-
- def _run_query(self, filter: Filter, team: Team, entity: Entity) -> list[dict[str, Any]]:
- adjusted_filter, cached_result = self.adjusted_filter(filter, team)
- with posthoganalytics.new_context():
- query_type, sql, params, parse_function = self._get_sql_for_entity(adjusted_filter, team, entity)
- posthoganalytics.tag("filter", filter.to_dict())
- posthoganalytics.tag("team_id", str(team.pk))
- query_params = {**params, **adjusted_filter.hogql_context.values}
- posthoganalytics.tag("query", {"sql": sql, "params": query_params})
- result = insight_sync_execute(
- sql,
- query_params,
- settings={"timeout_before_checking_execution_speed": 60},
- query_type=query_type,
- filter=adjusted_filter,
- team_id=team.pk,
- )
- result = parse_function(result)
- serialized_data = self._format_serialized(entity, result)
- merged_results, cached_result = self.merge_results(
- serialized_data,
- cached_result,
- entity.order or entity.index,
- filter,
- team,
- )
-
- if cached_result:
- for value in cached_result.values():
- merged_results.append(value)
-
- return merged_results
-
- def _run_query_for_threading(
- self,
- result: list,
- index: int,
- query_type,
- sql,
- params,
- query_tags: QueryTags,
- filter: Filter,
- team_id: int,
- ):
- update_tags(query_tags)
- with posthoganalytics.new_context():
- posthoganalytics.tag("query", {"sql": sql, "params": params})
- result[index] = insight_sync_execute(sql, params, query_type=query_type, filter=filter, team_id=team_id)
-
- def _run_parallel(self, filter: Filter, team: Team) -> list[dict[str, Any]]:
- result: list[Optional[list[dict[str, Any]]]] = [None] * len(filter.entities)
- parse_functions: list[Optional[Callable]] = [None] * len(filter.entities)
- sql_statements_with_params: list[tuple[Optional[str], dict]] = [(None, {})] * len(filter.entities)
- cached_result = None
- jobs = []
-
- for entity in filter.entities:
- adjusted_filter, cached_result = self.adjusted_filter(filter, team)
- query_type, sql, params, parse_function = self._get_sql_for_entity(adjusted_filter, team, entity)
- parse_functions[entity.index] = parse_function
- query_params = {**params, **adjusted_filter.hogql_context.values}
- sql_statements_with_params[entity.index] = (sql, query_params)
- thread = threading.Thread(
- target=self._run_query_for_threading,
- args=(
- result,
- entity.index,
- query_type,
- sql,
- query_params,
- get_query_tags().model_copy(deep=True),
- adjusted_filter,
- team.pk,
- ),
- )
- jobs.append(thread)
-
- # Start the threads (i.e. calculate the random number lists)
- for j in jobs:
- j.start()
-
- # Ensure all of the threads have finished
- for j in jobs:
- j.join()
-
- # Parse results for each thread
- with posthoganalytics.new_context():
- posthoganalytics.tag("filter", filter.to_dict())
- posthoganalytics.tag("team_id", str(team.pk))
- for entity in filter.entities:
- serialized_data = cast(list[Callable], parse_functions)[entity.index](result[entity.index])
- serialized_data = self._format_serialized(entity, serialized_data)
- merged_results, cached_result = self.merge_results(
- serialized_data,
- cached_result,
- entity.order or entity.index,
- filter,
- team,
- )
- result[entity.index] = merged_results
-
- # flatten results
- flat_results: list[dict[str, Any]] = []
- for item in result:
- for flat in cast(list[dict[str, Any]], item):
- flat_results.append(flat)
-
- if cached_result:
- for value in cached_result.values():
- flat_results.append(value)
-
- return flat_results
-
- def run(self, filter: Filter, team: Team, is_csv_export: bool = False, *args, **kwargs) -> list[dict[str, Any]]:
- self.is_csv_export = is_csv_export
- actions = Action.objects.filter(team__project_id=team.project_id).order_by("-id")
- if len(filter.actions) > 0:
- actions = Action.objects.filter(
- pk__in=[entity.id for entity in filter.actions], team__project_id=team.project_id
- )
-
- for entity in filter.entities:
- if entity.type == TREND_FILTER_TYPE_ACTIONS and entity.id is not None:
- try:
- entity.name = actions.get(id=entity.id).name
- except Action.DoesNotExist:
- return []
-
- if len(filter.entities) == 1 or filter.compare:
- result = []
- for entity in filter.entities:
- result.extend(handle_compare(filter, self._run_query, team, entity=entity))
- else:
- result = self._run_parallel(filter, team)
-
- return result
-
- def _format_serialized(self, entity: Entity, result: list[dict[str, Any]]):
- serialized_data = []
-
- serialized: dict[str, Any] = {
- "action": entity.to_dict(),
- "label": entity.name,
- "count": 0,
- "data": [],
- "labels": [],
- "days": [],
- }
-
- for queried_metric in result:
- serialized_copy = copy.deepcopy(serialized)
- serialized_copy.update(queried_metric)
- serialized_data.append(serialized_copy)
-
- return serialized_data
-
- def _handle_cumulative(self, entity_metrics: list) -> list[dict[str, Any]]:
- for metrics in entity_metrics:
- metrics.update(data=list(accumulate(metrics["data"])))
- return entity_metrics
-
-
-def is_filter_date_present(filter: Filter, latest_cached_datetime: datetime) -> bool:
- diff = filter.date_to - latest_cached_datetime
-
- if filter.interval == "hour":
- return diff < timedelta(hours=1)
- elif filter.interval == "day":
- return diff < timedelta(days=1)
- elif filter.interval == "week":
- return diff < timedelta(weeks=1)
- elif filter.interval == "month":
- return diff < timedelta(days=30)
-
-
-def interval_unit(interval: str) -> str:
- if interval == "hour":
- return "-1hr"
- if interval == "day":
- return "-1d"
- elif interval == "week":
- return "-1w"
- elif interval == "month":
- return "-1m"
- else:
- raise ValueError("Invalid interval")
diff --git a/posthog/queries/trends/trends_actors.py b/posthog/queries/trends/trends_actors.py
deleted file mode 100644
index abdc221f332a..000000000000
--- a/posthog/queries/trends/trends_actors.py
+++ /dev/null
@@ -1,156 +0,0 @@
-import json
-from typing import Any, Optional, cast
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.constants import PropertyOperatorType
-from posthog.models.entity import Entity
-from posthog.models.filters import Filter
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.models.person.sql import GET_ACTORS_FROM_EVENT_QUERY
-from posthog.models.property import Property
-from posthog.models.team import Team
-from posthog.queries.actor_base_query import ActorBaseQuery
-from posthog.queries.trends.trends_event_query import TrendsEventQuery
-from posthog.queries.trends.util import PROPERTY_MATH_FUNCTIONS, is_series_group_based, process_math
-
-from products.cohorts.backend.models.cohort import Cohort
-
-
-class TrendsActors(ActorBaseQuery):
- ACTOR_VALUES_INCLUDED = True
- QUERY_TYPE = "trends_actors"
-
- entity: Entity
- _filter: Filter
-
- def __init__(self, team: Team, entity: Optional[Entity], filter: Filter, **kwargs):
- if not entity:
- raise ValueError("Entity is required for TrendsActors")
- super().__init__(team, filter, entity, **kwargs)
-
- @cached_property
- def aggregation_group_type_index(self):
- if is_series_group_based(self.entity):
- return self.entity.math_group_type_index
- return None
-
- def actor_query(self, limit_actors: Optional[bool] = True) -> tuple[str, dict]:
- if self._filter.breakdown_type == "cohort" and self._filter.breakdown_value != "all":
- cohort = Cohort.objects.get(
- pk=cast(str | int, self._filter.breakdown_value), team__project_id=self._team.project_id
- )
- self._filter = self._filter.shallow_clone(
- {
- "properties": self._filter.property_groups.combine_properties(
- PropertyOperatorType.AND,
- [Property(key="id", value=cohort.pk, type="cohort")],
- ).to_dict()
- }
- )
- elif (
- self._filter.breakdown_type
- and isinstance(self._filter.breakdown, str)
- and isinstance(self._filter.breakdown_value, str)
- ):
- if self._filter.using_histogram:
- lower_bound, upper_bound = json.loads(self._filter.breakdown_value)
- breakdown_props = [
- Property(
- key=self._filter.breakdown,
- value=lower_bound,
- operator="gte",
- type=self._filter.breakdown_type,
- group_type_index=(
- self._filter.breakdown_group_type_index if self._filter.breakdown_type == "group" else None
- ),
- ),
- Property(
- key=self._filter.breakdown,
- value=upper_bound,
- operator="lt",
- type=self._filter.breakdown_type,
- group_type_index=(
- self._filter.breakdown_group_type_index if self._filter.breakdown_type == "group" else None
- ),
- ),
- ]
- else:
- breakdown_props = [
- Property(
- key=self._filter.breakdown,
- value=self._filter.breakdown_value,
- type=self._filter.breakdown_type,
- group_type_index=(
- self._filter.breakdown_group_type_index if self._filter.breakdown_type == "group" else None
- ),
- )
- ]
-
- self._filter = self._filter.shallow_clone(
- {
- "properties": self._filter.property_groups.combine_properties(
- PropertyOperatorType.AND, breakdown_props
- ).to_dict()
- }
- )
-
- extra_fields: list[str] = ["distinct_id", "team_id"] if not self.is_aggregating_by_groups else []
- if self._filter.include_recordings:
- extra_fields += ["uuid"]
-
- events_query, params = TrendsEventQuery(
- filter=self._filter,
- team=self._team,
- entity=self.entity,
- should_join_distinct_ids=not self.is_aggregating_by_groups
- and self._team.person_on_events_mode != PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,
- extra_event_properties=["$window_id", "$session_id"] if self._filter.include_recordings else [],
- extra_fields=extra_fields,
- person_on_events_mode=self._team.person_on_events_mode,
- ).get_query()
-
- matching_events_select_statement = (
- ", groupUniqArray(100)((timestamp, uuid, $session_id, $window_id)) as matching_events"
- if self._filter.include_recordings
- else ""
- )
-
- (
- actor_value_expression,
- actor_value_params,
- ) = self._aggregation_actor_value_expression_with_params
-
- return (
- GET_ACTORS_FROM_EVENT_QUERY.format(
- id_field=self._aggregation_actor_field,
- actor_value_expression=actor_value_expression,
- matching_events_select_statement=matching_events_select_statement,
- events_query=events_query,
- limit="LIMIT %(limit)s" if limit_actors else "",
- offset="OFFSET %(offset)s" if limit_actors else "",
- ),
- {
- **params,
- **actor_value_params,
- "offset": self._filter.offset,
- "limit": self._filter.limit or 100,
- },
- )
-
- @cached_property
- def _aggregation_actor_field(self) -> str:
- if self.is_aggregating_by_groups:
- group_type_index = self.entity.math_group_type_index
- return f"$group_{group_type_index}"
- else:
- return "person_id"
-
- @cached_property
- def _aggregation_actor_value_expression_with_params(self) -> tuple[str, dict[str, Any]]:
- if self.entity.math in PROPERTY_MATH_FUNCTIONS:
- math_aggregate_operation, _, math_params = process_math(
- self.entity, self._team, filter=self._filter, event_table_alias="e"
- )
- return math_aggregate_operation, math_params
- return "count()", {}
diff --git a/posthog/queries/trends/trends_event_query.py b/posthog/queries/trends/trends_event_query.py
deleted file mode 100644
index 41aa344f0a8c..000000000000
--- a/posthog/queries/trends/trends_event_query.py
+++ /dev/null
@@ -1,86 +0,0 @@
-from typing import Any
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.models.property.util import get_property_string_expr
-from posthog.queries.trends.trends_event_query_base import TrendsEventQueryBase
-
-
-class TrendsEventQuery(TrendsEventQueryBase):
- def get_query(self) -> tuple[str, dict[str, Any]]:
- person_id_field = ""
- if self._should_join_distinct_ids:
- person_id_field = f", {self._person_id_alias} as person_id"
- elif self._person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:
- person_id_field = f", {self.EVENT_TABLE_ALIAS}.person_id as person_id"
-
- _fields = (
- f"{self.EVENT_TABLE_ALIAS}.timestamp as timestamp"
- + (
- " ".join(
- f', {self.EVENT_TABLE_ALIAS}."{column_name}" as "{column_name}"'
- for column_name in self._column_optimizer.event_columns_to_query
- )
- )
- + " ".join(
- [
- ", "
- + get_property_string_expr(
- "events",
- property,
- f"'{property}'",
- "properties",
- table_alias="e",
- )[0]
- + f" as {property}"
- for property in self._extra_event_properties
- ]
- )
- + person_id_field
- + (
- f", {self.SESSION_TABLE_ALIAS}.session_duration as session_duration"
- if self._should_join_sessions
- else ""
- )
- + (
- f", {self.SESSION_TABLE_ALIAS}.$session_id as $session_id"
- if self._should_join_sessions
- and "$session_id" not in self._extra_event_properties
- and "$session_id" not in self._column_optimizer.event_columns_to_query
- else ""
- )
- + (f", {self.EVENT_TABLE_ALIAS}.distinct_id as distinct_id" if self._aggregate_users_by_distinct_id else "")
- + (
- " ".join(
- f", {self.EVENT_TABLE_ALIAS}.{column_name} as {column_name}" for column_name in self._extra_fields
- )
- )
- + (self._get_extra_person_columns())
- )
-
- base_query, params = super().get_query_base()
-
- return f"SELECT {_fields} {base_query}", params
-
- def _get_extra_person_columns(self) -> str:
- if self._person_on_events_mode != PersonsOnEventsMode.DISABLED:
- return " ".join(
- ", {extract} as {column_name}".format(
- extract=get_property_string_expr(
- "events",
- column_name,
- var=f"'{column_name}'",
- allow_denormalized_props=False,
- column="person_properties",
- table_alias=self.EVENT_TABLE_ALIAS,
- materialised_table_column="person_properties",
- ),
- column_name=column_name,
- )
- for column_name in self._extra_person_fields
- )
- else:
- return " ".join(
- f", {self.PERSON_TABLE_ALIAS}.{column_name} as {column_name}"
- for column_name in self._extra_person_fields
- )
diff --git a/posthog/queries/trends/trends_event_query_base.py b/posthog/queries/trends/trends_event_query_base.py
deleted file mode 100644
index ec1a58cf84d1..000000000000
--- a/posthog/queries/trends/trends_event_query_base.py
+++ /dev/null
@@ -1,162 +0,0 @@
-from typing import Any
-
-from posthog.schema import PersonsOnEventsMode
-
-from posthog.constants import MONTHLY_ACTIVE, UNIQUE_USERS, WEEKLY_ACTIVE, PropertyOperatorType
-from posthog.models import Entity
-from posthog.models.entity.util import get_entity_filtering_params
-from posthog.models.filters.filter import Filter
-from posthog.models.filters.mixins.utils import cached_property
-from posthog.queries.event_query import EventQuery
-from posthog.queries.person_query import PersonQuery
-from posthog.queries.query_date_range import QueryDateRange
-from posthog.queries.trends.util import COUNT_PER_ACTOR_MATH_FUNCTIONS, get_active_user_params
-from posthog.queries.util import get_person_properties_mode
-
-
-class TrendsEventQueryBase(EventQuery):
- _entity: Entity
- _filter: Filter
-
- def __init__(self, entity: Entity, *args, **kwargs):
- self._entity = entity
- super().__init__(*args, **kwargs)
-
- def get_query_base(self) -> tuple[str, dict[str, Any]]:
- """
- Returns part of the event query with only FROM, JOINs and WHERE clauses.
- """
-
- date_query, date_params = self._get_date_filter()
- self.params.update(date_params)
-
- prop_query, prop_params = self._get_prop_groups(
- self._filter.property_groups.combine_property_group(PropertyOperatorType.AND, self._entity.property_groups),
- person_properties_mode=get_person_properties_mode(self._team),
- person_id_joined_alias=self._person_id_alias,
- )
-
- self.params.update(prop_params)
-
- entity_query, entity_params = self._get_entity_query(deep_filtering=False)
- self.params.update(entity_params)
-
- deep_entity_query, deep_entity_params = self._get_entity_query(deep_filtering=True)
- self.params.update(deep_entity_params)
-
- person_query, person_params = self._get_person_query()
- self.params.update(person_params)
-
- groups_query, groups_params = self._get_groups_query()
- self.params.update(groups_params)
-
- session_query, session_params = self._get_sessions_query()
- self.params.update(session_params)
-
- sample_clause = "SAMPLE %(sampling_factor)s" if self._filter.sampling_factor else ""
- self.params.update({"sampling_factor": self._filter.sampling_factor})
-
- query = f"""
- FROM events {self.EVENT_TABLE_ALIAS}
- {sample_clause}
- {self._get_person_ids_query(relevant_events_conditions=f"{deep_entity_query} {date_query}")}
- {person_query}
- {groups_query}
- {session_query}
- WHERE team_id = %(team_id)s
- {entity_query}
- {date_query}
- {prop_query}
- {self._get_not_null_actor_condition()}
- """
-
- return query, self.params
-
- def _determine_should_join_distinct_ids(self) -> None:
- if self._person_on_events_mode == PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS:
- self._should_join_distinct_ids = False
-
- is_entity_per_user = self._entity.math in (
- UNIQUE_USERS,
- WEEKLY_ACTIVE,
- MONTHLY_ACTIVE,
- *COUNT_PER_ACTOR_MATH_FUNCTIONS.keys(),
- )
- if (
- is_entity_per_user
- and not self._aggregate_users_by_distinct_id
- and self._entity.math_group_type_index is None
- ) or self._column_optimizer.is_using_cohort_propertes:
- self._should_join_distinct_ids = True
-
- def _determine_should_join_persons(self) -> None:
- if self._person_on_events_mode != PersonsOnEventsMode.DISABLED:
- self._should_join_persons = False
- else:
- EventQuery._determine_should_join_persons(self)
-
- def _get_not_null_actor_condition(self) -> str:
- if self._entity.math_group_type_index is None:
- # If aggregating by person, exclude events with null/zero person IDs
- return (
- f"AND notEmpty({self.EVENT_TABLE_ALIAS}.person_id)"
- if self._person_on_events_mode != PersonsOnEventsMode.DISABLED
- else ""
- )
- else:
- # If aggregating by group, exclude events that aren't associated with a group
- return f"""AND "$group_{self._entity.math_group_type_index}" != ''"""
-
- def _get_date_filter(self) -> tuple[str, dict]:
- date_query = ""
- date_params: dict[str, Any] = {}
- query_date_range = QueryDateRange(self._filter, self._team)
- parsed_date_from, date_from_params = query_date_range.date_from
- parsed_date_to, date_to_params = query_date_range.date_to
-
- date_params.update(date_from_params)
- date_params.update(date_to_params)
-
- self.parsed_date_from = parsed_date_from
- self.parsed_date_to = parsed_date_to
-
- if self._entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE]:
- (
- active_user_format_params,
- active_user_query_params,
- ) = get_active_user_params(self._filter, self._entity, self._team_id)
- self.active_user_params = active_user_format_params
- date_params.update(active_user_query_params)
-
- date_query = "{parsed_date_from_prev_range} {parsed_date_to}".format(
- **active_user_format_params, parsed_date_to=parsed_date_to
- )
- else:
- date_query = "{parsed_date_from} {parsed_date_to}".format(
- parsed_date_from=parsed_date_from, parsed_date_to=parsed_date_to
- )
-
- return date_query, date_params
-
- def _get_entity_query(self, *, deep_filtering: bool) -> tuple[str, dict]:
- entity_params, entity_format_params = get_entity_filtering_params(
- allowed_entities=[self._entity],
- team_id=self._team_id,
- table_name=self.EVENT_TABLE_ALIAS,
- person_properties_mode=get_person_properties_mode(self._team),
- hogql_context=self._filter.hogql_context,
- person_id_joined_alias=self._person_id_alias,
- deep_filtering=deep_filtering,
- )
-
- return entity_format_params["entity_query"], entity_params
-
- @cached_property
- def _person_query(self):
- return PersonQuery(
- self._filter,
- self._team_id,
- self._column_optimizer,
- extra_fields=self._extra_person_fields,
- entity=self._entity,
- )
diff --git a/posthog/queries/trends/util.py b/posthog/queries/trends/util.py
index 25f41b2a0481..a51b0ed85f7b 100644
--- a/posthog/queries/trends/util.py
+++ b/posthog/queries/trends/util.py
@@ -19,7 +19,7 @@ from posthog.models.filters.properties_timeline_filter import PropertiesTimeline
from posthog.models.filters.utils import validate_group_type_index
from posthog.models.property.util import get_property_string_expr
from posthog.models.team import Team
-from posthog.queries.util import correct_result_for_sampling, get_earliest_timestamp
+from posthog.queries.util import correct_result_for_sampling
logger = structlog.get_logger(__name__)
@@ -123,12 +123,15 @@ def parse_response(
def get_active_user_params(filter: Filter, entity: Entity, team_id: int) -> tuple[dict[str, Any], dict[str, Any]]:
diff = timedelta(days=7 if entity.math == WEEKLY_ACTIVE else 30)
+ # Imported here to avoid a circular import at module load (timestamp_utils pulls in HogQL).
+ from posthog.hogql_queries.utils.timestamp_utils import get_earliest_timestamp_unfiltered # noqa: PLC0415
+
date_from: datetime.datetime
if filter.date_from:
date_from = filter.date_from
else:
try:
- date_from = get_earliest_timestamp(team_id)
+ date_from = get_earliest_timestamp_unfiltered(Team.objects.get(pk=team_id))
except IndexError:
raise ValidationError("Active User queries require a lower date bound")
date_to = filter.date_to
diff --git a/posthog/queries/util.py b/posthog/queries/util.py
index 33c008057e8f..a66fa274d128 100644
--- a/posthog/queries/util.py
+++ b/posthog/queries/util.py
@@ -1,17 +1,12 @@
import json
-from datetime import UTC, date, datetime, time, timedelta
+from datetime import UTC, datetime
from enum import Enum, auto
from typing import Any, Optional, Union, overload
from zoneinfo import ZoneInfo
-from django.utils import timezone
-
from rest_framework.exceptions import ValidationError
-from posthog.cache_utils import cache_for
-from posthog.models.event import DEFAULT_EARLIEST_TIME_DELTA
from posthog.models.team.team import Team, WeekStartDay
-from posthog.queries.insight import insight_sync_execute
from posthog.schema_enums import PersonsOnEventsMode
@@ -52,12 +47,6 @@ def alias_poe_mode_for_legacy(persons_on_events_mode: PersonsOnEventsMode | None
return persons_on_events_mode
-EARLIEST_TIMESTAMP = "2015-01-01"
-
-GET_EARLIEST_TIMESTAMP_SQL = """
-SELECT timestamp from events WHERE team_id = %(team_id)s AND timestamp > %(earliest_timestamp)s order by timestamp limit 1
-"""
-
TIME_IN_SECONDS: dict[str, Any] = {
"hour": 3600,
"day": 3600 * 24,
@@ -92,26 +81,6 @@ def format_ch_timestamp(timestamp: datetime, convert_to_timezone: Optional[str]
return timestamp.strftime("%Y-%m-%d %H:%M:%S")
-@cache_for(timedelta(seconds=2))
-def get_earliest_timestamp(team_id: int) -> datetime:
- results = insight_sync_execute(
- GET_EARLIEST_TIMESTAMP_SQL,
- {"team_id": team_id, "earliest_timestamp": EARLIEST_TIMESTAMP},
- query_type="get_earliest_timestamp",
- team_id=team_id,
- )
-
- if len(results) > 0:
- earliest = results[0][0]
- # ClickHouse may return a `date` rather than a `datetime` for some teams' data; downstream
- # interval alignment assumes a `datetime` (e.g. `datetime.date.replace` rejects time kwargs).
- if isinstance(earliest, date) and not isinstance(earliest, datetime):
- return datetime.combine(earliest, time.min, tzinfo=UTC)
- return earliest
- else:
- return timezone.now() - DEFAULT_EARLIEST_TIME_DELTA
-
-
def get_start_of_interval_sql(
interval: str,
*,
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 0b71b795281a..256744d35c61 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -1365,21 +1365,41 @@
# name: TestFeatureFlag.test_creating_static_cohort.28
'''
/* user_id:0 request:_snapshot_ */
- SELECT id
- FROM person
- INNER JOIN
- (SELECT person_id
- FROM person_static_cohort
- WHERE team_id = 99999
- AND cohort_id = 99999
- GROUP BY person_id,
- cohort_id,
- team_id) cohort_persons ON cohort_persons.person_id = person.id
- WHERE team_id = 99999
- GROUP BY id
- HAVING max(is_deleted) = 0
- ORDER BY argMax(person.created_at, version) DESC, id DESC
- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1
+ SELECT persons.id AS id
+ FROM
+ (SELECT argMax(toTimeZone(person.created_at, 'UTC'), person.version) AS created_at,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(id,
+ (SELECT where_optimization.id AS id
+ FROM person AS where_optimization
+ WHERE and(equals(where_optimization.team_id, 99999), in(where_optimization.id,
+ (SELECT person_static_cohort.person_id AS person_id
+ FROM person_static_cohort
+ WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
+ WHERE in(persons.id,
+ (SELECT person_static_cohort.person_id AS person_id
+ FROM person_static_cohort
+ WHERE and(equals(person_static_cohort.team_id, 99999), equals(person_static_cohort.cohort_id, 99999))))
+ ORDER BY persons.created_at DESC,
+ persons.id DESC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestFeatureFlag.test_creating_static_cohort.3
diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr
index bdc4f8e03bc5..ecf173495189 100644
--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr
+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr
@@ -1,13 +1,22 @@
# serializer version: 1
# name: TestExternalClicksTableQueryRunner.test_all_time
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestExternalClicksTableQueryRunner.test_all_time.1
diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr
index 503e5a226893..4aac36d9fbf4 100644
--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr
+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr
@@ -1,13 +1,22 @@
# serializer version: 1
# name: TestWebOverviewQueryRunner.test_all_time
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebOverviewQueryRunner.test_all_time.1
diff --git a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
index bde82484fa33..9521cf946fb1 100644
--- a/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
@@ -1,13 +1,22 @@
# serializer version: 1
# name: TestWebStatsTableQueryRunner.test_all_time
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_all_time.1
@@ -154,13 +163,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_avg_time_on_multiple_routes_and_users
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_avg_time_on_multiple_routes_and_users.1
@@ -255,13 +273,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_avg_time_on_page_multiple_users
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_avg_time_on_page_multiple_users.1
@@ -356,13 +383,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_avg_time_on_page_one_user
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_avg_time_on_page_one_user.1
@@ -457,13 +493,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate.1
@@ -548,13 +593,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_one_user
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_one_user.1
@@ -639,13 +693,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_path_cleaning
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_path_cleaning.1
@@ -730,13 +793,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_with_multiple_pathname_filters
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_with_multiple_pathname_filters.1
@@ -821,13 +893,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_with_property
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_with_property.1
@@ -975,13 +1056,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_cohort_test_filters.1
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_cohort_test_filters.2
@@ -1556,13 +1646,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate.1
@@ -1621,13 +1720,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate_one_user
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate_one_user.1
@@ -1686,13 +1794,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate_path_cleaning
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate_path_cleaning.1
@@ -1751,13 +1868,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate_with_property
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate_with_property.1
@@ -1878,13 +2004,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_concatenates_host_and_path_0_Page
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_concatenates_host_and_path_0_Page.1
@@ -1941,13 +2076,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_concatenates_host_and_path_1_InitialPage
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_concatenates_host_and_path_1_InitialPage.1
@@ -2006,13 +2150,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_concatenates_host_and_path_2_ExitPage
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_concatenates_host_and_path_2_ExitPage.1
@@ -2071,13 +2224,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_exit_page_breakdown_counts_correctly
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_exit_page_breakdown_counts_correctly.1
@@ -2136,13 +2298,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_false_returns_path_only_0_Page
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_false_returns_path_only_0_Page.1
@@ -2199,13 +2370,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_false_returns_path_only_1_InitialPage
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_false_returns_path_only_1_InitialPage.1
@@ -2263,13 +2443,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_false_returns_path_only_2_ExitPage
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_false_returns_path_only_2_ExitPage.1
@@ -2327,13 +2516,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_initial_page_breakdown_with_bounce_rate
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_initial_page_breakdown_with_bounce_rate.1
@@ -2393,13 +2591,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_page_breakdown_groups_same_paths_on_different_hosts_separately
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_page_breakdown_groups_same_paths_on_different_hosts_separately.1
@@ -2456,17 +2663,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_include_host_page_breakdown_groups_same_paths_on_different_hosts_separately.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_include_host_page_breakdown_groups_same_paths_on_different_hosts_separately.3
- '''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
@@ -2623,13 +2819,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_is_not_set_filter
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_is_not_set_filter.1
@@ -2686,13 +2891,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_language_filter
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_language_filter.1
@@ -2759,13 +2973,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_limit
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_limit.1
@@ -2822,17 +3045,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_limit.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_limit.3
- '''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
@@ -2937,13 +3149,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_no_session_id
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_no_session_id.1
@@ -3001,17 +3222,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_no_session_id.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_no_session_id.3
- '''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
@@ -3063,18 +3273,7 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_no_session_id.4
- '''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_no_session_id.5
+# name: TestWebStatsTableQueryRunner.test_no_session_id.3
'''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
@@ -3128,13 +3327,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_null_in_utm_tags
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_null_in_utm_tags.1
@@ -3191,13 +3399,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_null_prev_pageview_duration_excluded_from_p90
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_null_prev_pageview_duration_excluded_from_p90.1
@@ -3292,13 +3509,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters.1
@@ -3355,13 +3581,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_applied_in_order
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_applied_in_order.1
@@ -3418,13 +3653,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_cleanable_path_property
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_cleanable_path_property.1
@@ -3482,13 +3726,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_cleaned_path_property
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_cleaned_path_property.1
@@ -3546,17 +3799,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_cleaned_path_property.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_cleaned_path_property.3
- '''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
@@ -3610,13 +3852,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_multiple_capture_groups
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_filters_with_multiple_capture_groups.1
@@ -3673,13 +3924,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_with_order_field_and_baseline_urls
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_path_cleaning_with_order_field_and_baseline_urls.1
@@ -3736,13 +3996,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_same_user_multiple_sessions
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_same_user_multiple_sessions.1
@@ -3799,17 +4068,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_same_user_multiple_sessions.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_same_user_multiple_sessions.3
- '''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
@@ -3860,18 +4118,7 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_same_user_multiple_sessions.4
- '''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_same_user_multiple_sessions.5
+# name: TestWebStatsTableQueryRunner.test_same_user_multiple_sessions.3
'''
SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
@@ -3953,13 +4200,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_bounce_rate
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_bounce_rate.1
@@ -4045,17 +4301,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_bounce_rate.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_sorting_by_bounce_rate.3
- '''
SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
tuple(counts.views, counts.previous_views) AS `context.columns.views`,
@@ -4379,13 +4624,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_views
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_views.1
@@ -4442,17 +4696,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_views.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_sorting_by_views.3
- '''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
@@ -4505,13 +4748,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_visitors
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_visitors.1
@@ -4568,17 +4820,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_sorting_by_visitors.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_sorting_by_visitors.3
- '''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
@@ -4631,13 +4872,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_source_medium_campaign
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_source_medium_campaign.1
@@ -4698,13 +4948,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_time_on_page_caps_at_24_hours
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_time_on_page_caps_at_24_hours.1
@@ -4850,13 +5109,22 @@
# ---
# name: TestWebStatsTableQueryRunner.test_timezone_filter_with_invalid_timezone_offset
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('2015-01-01 00:00:00.000000', 6, 'UTC')))
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_timezone_filter_with_invalid_timezone_offset.1
@@ -4912,17 +5180,6 @@
# ---
# name: TestWebStatsTableQueryRunner.test_timezone_filter_with_invalid_timezone_offset.2
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_timezone_filter_with_invalid_timezone_offset.3
- '''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
@@ -4972,18 +5229,7 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_timezone_filter_with_invalid_timezone_offset.4
- '''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
-# name: TestWebStatsTableQueryRunner.test_timezone_filter_with_invalid_timezone_offset.5
+# name: TestWebStatsTableQueryRunner.test_timezone_filter_with_invalid_timezone_offset.3
'''
SELECT breakdown_value AS `context.columns.breakdown_value`,
tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
diff --git a/products/web_analytics/backend/max_tools.py b/products/web_analytics/backend/max_tools.py
index 42ef82d4ef51..ad2d73c86791 100644
--- a/products/web_analytics/backend/max_tools.py
+++ b/products/web_analytics/backend/max_tools.py
@@ -7,7 +7,7 @@ from typing import Any, Literal
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field
-from posthog.schema import WebAnalyticsAssistantFilters
+from posthog.schema import PropertyType, PropertyValuesQuery, WebAnalyticsAssistantFilters
from posthog.hogql import ast
from posthog.hogql.ast import Constant
@@ -18,9 +18,11 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Product, tags_context
from posthog.dags.common.owners import JobOwners
+from posthog.hogql_queries.property_values_query_runner import PropertyValuesQueryRunner
+from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import Team, User
from posthog.models.health_issue import HealthIssue
-from posthog.queries.property_values import get_person_property_values_for_key, get_property_values_for_key
+from posthog.queries.property_values import get_person_property_values_for_key
from posthog.rbac.user_access_control import AccessControlLevel
from posthog.scopes import APIScopeObject
from posthog.sync import database_sync_to_async, database_sync_to_async_pool
@@ -118,14 +120,22 @@ class WebAnalyticsFilterOptionsToolkit(TaxonomyAgentToolkit):
)
elif property_type in ("event", "session"):
with tags_context(product=Product.MAX_AI, team_id=self._team.pk, org_id=self._team.organization_id):
- values = await database_sync_to_async(get_property_values_for_key)(
- property_name, self._team, event_names=None, value=None
- )
+ values = await database_sync_to_async(self._retrieve_event_property_values)(property_name)
else:
return TaxonomyErrorMessages.property_not_found(property_name, property_type)
return self._format_property_values(property_name, values, sample_count=len(values))
+ def _retrieve_event_property_values(self, property_name: str) -> list:
+ # Web analytics event and session property values both live on events.properties, so they
+ # share the EVENT path of PropertyValuesQueryRunner (there is no SESSION property type).
+ runner = PropertyValuesQueryRunner(
+ team=self._team,
+ query=PropertyValuesQuery(property_type=PropertyType.EVENT, property_key=property_name),
+ )
+ response = runner.run(ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ return [item.name for item in getattr(response, "results", []) or []]
+
class WebAnalyticsFilterNode(TaxonomyAgentNode[TaxonomyAgentState, TaxonomyAgentState[WebAnalyticsAssistantFilters]]):
def __init__(
diff --git a/products/web_analytics/backend/test/test_max_tools.py b/products/web_analytics/backend/test/test_max_tools.py
index 14dfffa4de9f..1c4fae9d623d 100644
--- a/products/web_analytics/backend/test/test_max_tools.py
+++ b/products/web_analytics/backend/test/test_max_tools.py
@@ -1,4 +1,4 @@
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
from posthog.schema import (
CompareFilter,
@@ -24,6 +24,23 @@ class TestWebAnalyticsFilterOptionsToolkit(APIBaseTest):
assert "ask_user_for_help" in tool_names
+class TestWebAnalyticsPropertyValues(ClickhouseDestroyTablesMixin, APIBaseTest):
+ def test_retrieve_event_property_values_returns_distinct_values(self):
+ for browser in ["Chrome", "Chrome", "Firefox"]:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="d1",
+ properties={"$browser": browser},
+ )
+ flush_persons_and_events()
+
+ toolkit = WebAnalyticsFilterOptionsToolkit(self.team, self.user)
+ values = toolkit._retrieve_event_property_values("$browser")
+
+ assert set(values) == {"Chrome", "Firefox"}
+
+
class TestWebAnalyticsAssistantFilters(APIBaseTest):
def test_filters_validation(self):
filters = WebAnalyticsAssistantFilters(