factcat 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
factcat/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Factcat - product analytics on the event model already in your warehouse.
2
+
3
+ A **fact** table is what you build; **cat** is how you read a file. Factcat
4
+ reads your fact tables where they sit, and never copies them anywhere.
5
+
6
+ from factcat import RetentionSpec, retention_sql
7
+
8
+ spec = RetentionSpec(
9
+ table="payments",
10
+ entity="subscription_id", # not the user
11
+ entity_time="sub_start",
12
+ event_time="paid_at",
13
+ period_days=35, # not a calendar bucket
14
+ n_periods=2,
15
+ retained="status = 'collected' AND within_period_offset <= 5",
16
+ )
17
+ print(retention_sql(spec, dialect="snowflake"))
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from .dialects import SUPPORTED, period_grid
23
+ from .funnel import build_sql as funnel_sql
24
+ from .retention import build_sql as retention_sql
25
+ from .spec import FunnelSpec, RetentionSpec
26
+
27
+ __all__ = [
28
+ "FunnelSpec",
29
+ "RetentionSpec",
30
+ "SUPPORTED",
31
+ "funnel_sql",
32
+ "period_grid",
33
+ "retention_sql",
34
+ ]
factcat/_emit.py ADDED
@@ -0,0 +1,61 @@
1
+ """Shared SQL emission helpers.
2
+
3
+ The strategy: build one query in DuckDB dialect, transpile it with sqlglot, and
4
+ splice in the one construct that does not transpile (the integer series). See
5
+ ``dialects.py`` for why that construct is the only per-warehouse code here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sqlglot
11
+
12
+ from .dialects import period_grid
13
+
14
+ # The relation name the retention query joins against for its period grid. It is
15
+ # never defined as a CTE in the pre-transpile SQL - sqlglot simply renders it as
16
+ # an identifier - and the real CTE is prepended afterwards.
17
+ GRID_RELATION = "factcat_period_grid"
18
+
19
+
20
+ def day_diff(start: str, end: str) -> str:
21
+ """Whole days between two instants, in DuckDB dialect for later transpilation."""
22
+ return f"date_diff('day', {start}, {end})"
23
+
24
+
25
+ def floor_div(numerator: str, divisor: int) -> str:
26
+ """Integer division spelled portably.
27
+
28
+ DuckDB's ``/`` is float division, and a float period index will not join
29
+ against the integer period grid. ``//`` does not transpile cleanly, so this
30
+ goes through FLOOR and an explicit cast.
31
+ """
32
+ return f"CAST(FLOOR(({numerator}) * 1.0 / {divisor}) AS BIGINT)"
33
+
34
+
35
+ def transpile(sql: str, dialect: str) -> str:
36
+ """Transpile DuckDB-dialect SQL to ``dialect``."""
37
+ if dialect == "duckdb":
38
+ return sql
39
+ return sqlglot.transpile(sql, read="duckdb", write=dialect, pretty=True)[0]
40
+
41
+
42
+ def transpile_with_grid(sql: str, dialect: str, n_periods: int) -> str:
43
+ """Transpile ``sql`` and prepend the dialect-native period grid as a CTE.
44
+
45
+ ``sql`` must reference :data:`GRID_RELATION` and must already begin with a
46
+ ``WITH`` clause, which every query in this package does.
47
+
48
+ Raises:
49
+ RuntimeError: if the transpiled SQL does not start with ``WITH``. That
50
+ would mean the grid CTE could not be attached, leaving a query that
51
+ references an undefined relation - a failure worth making loud
52
+ rather than emitting SQL that dies at the warehouse.
53
+ """
54
+ out = transpile(sql, dialect).lstrip()
55
+ if not out.upper().startswith("WITH "):
56
+ raise RuntimeError(
57
+ "expected the transpiled query to open with a WITH clause so the "
58
+ f"period grid could be prepended, got: {out[:60]!r}"
59
+ )
60
+ grid = period_grid(n_periods, dialect)
61
+ return f"WITH {GRID_RELATION} AS (\n{grid}\n),\n{out[len('WITH '):]}"
factcat/dialects.py ADDED
@@ -0,0 +1,68 @@
1
+ """Per-dialect SQL that cannot be transpiled.
2
+
3
+ sqlglot handles almost everything: date arithmetic, casting, string functions,
4
+ window functions. Measured across the retention query, exactly one construct
5
+ does not survive transpilation cleanly - **generating a series of integers**.
6
+
7
+ duckdb UNNEST(GENERATE_SERIES(0, n))
8
+ snowflake renders as a double FLATTEN over ARRAY_GENERATE_RANGE
9
+ redshift fails outright: "Unsupported EXPLODE() function"
10
+
11
+ So the period grid is written by hand per dialect, and that is the entire
12
+ per-warehouse surface area of this engine. Everything else is one emitter.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ SUPPORTED: tuple[str, ...] = (
18
+ "duckdb",
19
+ "postgres",
20
+ "bigquery",
21
+ "snowflake",
22
+ "databricks",
23
+ "spark",
24
+ "trino",
25
+ "presto",
26
+ "clickhouse",
27
+ "redshift",
28
+ )
29
+
30
+
31
+ def _union_all_grid(n: int) -> str:
32
+ """The universal fallback: an explicit union of integers.
33
+
34
+ Verbose, but valid in every SQL dialect ever written. Used for Redshift,
35
+ which has no row generator reachable without a system table.
36
+ """
37
+ return " UNION ALL ".join(f"SELECT {i} AS period_index" for i in range(n + 1))
38
+
39
+
40
+ def period_grid(n_periods: int, dialect: str) -> str:
41
+ """SQL returning one row per period index, 0..n_periods inclusive.
42
+
43
+ The result must expose a single column named ``period_index``.
44
+ """
45
+ if n_periods < 0:
46
+ raise ValueError("n_periods must be >= 0")
47
+ n = n_periods
48
+
49
+ if dialect == "duckdb":
50
+ return f"SELECT UNNEST(GENERATE_SERIES(0, {n})) AS period_index"
51
+ if dialect == "postgres":
52
+ return f"SELECT GENERATE_SERIES(0, {n}) AS period_index"
53
+ if dialect == "bigquery":
54
+ return f"SELECT period_index FROM UNNEST(GENERATE_ARRAY(0, {n})) AS period_index"
55
+ if dialect == "snowflake":
56
+ return (
57
+ "SELECT SEQ4() AS period_index "
58
+ f"FROM TABLE(GENERATOR(ROWCOUNT => {n + 1}))"
59
+ )
60
+ if dialect in ("databricks", "spark"):
61
+ return f"SELECT EXPLODE(SEQUENCE(0, {n})) AS period_index"
62
+ if dialect in ("trino", "presto"):
63
+ return f"SELECT period_index FROM UNNEST(SEQUENCE(0, {n})) AS t(period_index)"
64
+ if dialect == "clickhouse":
65
+ return f"SELECT arrayJoin(range(0, {n + 1})) AS period_index"
66
+
67
+ # Redshift and anything unrecognised. Correct everywhere, ugly above ~200.
68
+ return _union_all_grid(n)
factcat/funnel.py ADDED
@@ -0,0 +1,103 @@
1
+ """Ordered funnel SQL generation.
2
+
3
+ Same principle as retention: the entity is a parameter, the step predicates are
4
+ arbitrary SQL, and the completion window is measured from the first step rather
5
+ than from the previous one. Each step takes the **earliest** qualifying event at
6
+ or after the previous step, which is the semantics every funnel tool implements
7
+ and few document.
8
+
9
+ Internal join keys are prefixed ``fc_`` so a source column called ``entity_id``
10
+ cannot make the join ambiguous. Step predicates reference source columns
11
+ directly and unqualified, as the caller wrote them.
12
+
13
+ No period grid is needed here, so this transpiles straight through sqlglot.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from ._emit import day_diff, transpile
19
+ from .spec import FunnelSpec
20
+
21
+
22
+ def _quote(label: str) -> str:
23
+ """Render a label as a SQL string literal."""
24
+ return "'" + label.replace("'", "''") + "'"
25
+
26
+
27
+ def build_sql(spec: FunnelSpec, dialect: str = "duckdb") -> str:
28
+ """Render ``spec`` as SQL for ``dialect``.
29
+
30
+ The result has one row per step: index, label, entities reaching that step,
31
+ and the percentage of the first step's entities that got there.
32
+ """
33
+ where = f"WHERE {spec.where}" if spec.where else ""
34
+ labels = spec.labels()
35
+
36
+ ctes: list[str] = [
37
+ f"""src AS (
38
+ SELECT * FROM {spec.table} {where}
39
+ )""",
40
+ f"""base AS (
41
+ SELECT
42
+ src.*,
43
+ {spec.entity} AS fc_entity,
44
+ {spec.event_time} AS fc_event_ts
45
+ FROM src
46
+ )""",
47
+ f"""step_0 AS (
48
+ SELECT
49
+ fc_entity AS fc_entity,
50
+ MIN(fc_event_ts) AS fc_reached_at,
51
+ MIN(fc_event_ts) AS fc_first_at
52
+ FROM base
53
+ WHERE ({spec.steps[0]})
54
+ GROUP BY 1
55
+ )""",
56
+ ]
57
+
58
+ for i, predicate in enumerate(spec.steps[1:], start=1):
59
+ window = ""
60
+ if spec.within_days is not None:
61
+ elapsed = day_diff("p.fc_first_at", "b.fc_event_ts")
62
+ window = f"AND {elapsed} <= {spec.within_days}"
63
+ ctes.append(
64
+ f"""step_{i} AS (
65
+ SELECT
66
+ p.fc_entity,
67
+ MIN(b.fc_event_ts) AS fc_reached_at,
68
+ p.fc_first_at
69
+ FROM step_{i - 1} p
70
+ JOIN base b ON b.fc_entity = p.fc_entity
71
+ WHERE b.fc_event_ts >= p.fc_reached_at
72
+ AND ({predicate})
73
+ {window}
74
+ GROUP BY p.fc_entity, p.fc_first_at
75
+ )"""
76
+ )
77
+
78
+ counts = "\n UNION ALL\n ".join(
79
+ f"SELECT {i} AS step_index, {_quote(labels[i])} AS step_label, "
80
+ f"COUNT(*) AS entities FROM step_{i}"
81
+ for i in range(len(spec.steps))
82
+ )
83
+ ctes.append(
84
+ f"""counts AS (
85
+ {counts}
86
+ )"""
87
+ )
88
+
89
+ # Joined outside the f-string: a backslash in an f-string expression is only
90
+ # legal from Python 3.12 (PEP 701), and this package supports 3.10.
91
+ cte_sql = ",\n ".join(ctes)
92
+ sql = f"""
93
+ WITH {cte_sql}
94
+ SELECT
95
+ c.step_index,
96
+ c.step_label,
97
+ c.entities,
98
+ ROUND(100.0 * c.entities / NULLIF(t.total, 0), 2) AS pct_of_first
99
+ FROM counts c
100
+ CROSS JOIN (SELECT entities AS total FROM counts WHERE step_index = 0) t
101
+ ORDER BY 1
102
+ """
103
+ return transpile(sql, dialect)
factcat/retention.py ADDED
@@ -0,0 +1,109 @@
1
+ """Retention SQL generation.
2
+
3
+ Every product analytics tool, warehouse-native ones included, hard-codes three
4
+ things:
5
+
6
+ entity = user
7
+ period = a calendar bucket (day / week / month)
8
+ retained = did any event
9
+
10
+ Real retention definitions violate all three. This module fixes none of them in
11
+ place, so a definition like
12
+
13
+ "the subscription is retained in a 35-day billing period if payment is
14
+ collected within 5 days of the period opening"
15
+
16
+ is expressed directly rather than approximated.
17
+
18
+ Internal join keys are prefixed ``fc_`` so that a caller whose source table
19
+ happens to contain a column called ``entity_id`` or ``cohort`` does not collide
20
+ with the generated SQL. The three derived columns a predicate may reference -
21
+ ``offset_days``, ``period_index`` and ``within_period_offset`` - are deliberately
22
+ unprefixed, because they are the public API of the ``retained`` expression.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from ._emit import GRID_RELATION, day_diff, floor_div, transpile_with_grid
28
+ from .spec import RetentionSpec
29
+
30
+
31
+ def build_sql(spec: RetentionSpec, dialect: str = "duckdb") -> str:
32
+ """Render ``spec`` as SQL for ``dialect``.
33
+
34
+ The result has one row per (cohort, period_index) with the cohort size, the
35
+ number of retained entities, and the percentage.
36
+ """
37
+ where = f"WHERE {spec.where}" if spec.where else ""
38
+
39
+ offset = day_diff("c.cohort_ts", "b.fc_event_ts")
40
+ period_index = floor_div(offset, spec.period_days)
41
+ within = f"{offset} - ({period_index}) * {spec.period_days}"
42
+
43
+ sql = f"""
44
+ WITH src AS (
45
+ SELECT * FROM {spec.table} {where}
46
+ ),
47
+ base AS (
48
+ SELECT
49
+ src.*,
50
+ {spec.entity} AS fc_entity,
51
+ {spec.entity_time} AS fc_entity_ts,
52
+ {spec.event_time} AS fc_event_ts
53
+ FROM src
54
+ ),
55
+ entities AS (
56
+ SELECT
57
+ fc_entity,
58
+ MIN(fc_entity_ts) AS cohort_ts
59
+ FROM base
60
+ GROUP BY 1
61
+ ),
62
+ -- `cohort_ts` is exposed under that exact name because `spec.cohort_bucket`
63
+ -- is caller-supplied SQL that references it.
64
+ cohorts AS (
65
+ SELECT
66
+ fc_entity,
67
+ cohort_ts,
68
+ {spec.cohort_bucket} AS fc_cohort
69
+ FROM entities
70
+ ),
71
+ observations AS (
72
+ SELECT
73
+ b.*,
74
+ c.fc_cohort,
75
+ {offset} AS offset_days,
76
+ {period_index} AS period_index,
77
+ {within} AS within_period_offset
78
+ FROM base b
79
+ JOIN cohorts c ON b.fc_entity = c.fc_entity
80
+ ),
81
+ retained_periods AS (
82
+ SELECT DISTINCT fc_entity, period_index
83
+ FROM observations
84
+ WHERE period_index BETWEEN 0 AND {spec.n_periods}
85
+ AND ({spec.retained})
86
+ ),
87
+ grid AS (
88
+ SELECT c.fc_cohort, c.fc_entity, p.period_index
89
+ FROM cohorts c
90
+ CROSS JOIN {GRID_RELATION} p
91
+ )
92
+ SELECT
93
+ g.fc_cohort AS cohort,
94
+ g.period_index,
95
+ COUNT(DISTINCT g.fc_entity) AS cohort_size,
96
+ COUNT(DISTINCT r.fc_entity) AS retained_entities,
97
+ ROUND(
98
+ 100.0 * COUNT(DISTINCT r.fc_entity)
99
+ / NULLIF(COUNT(DISTINCT g.fc_entity), 0),
100
+ 2
101
+ ) AS retention_pct
102
+ FROM grid g
103
+ LEFT JOIN retained_periods r
104
+ ON r.fc_entity = g.fc_entity
105
+ AND r.period_index = g.period_index
106
+ GROUP BY 1, 2
107
+ ORDER BY 1, 2
108
+ """
109
+ return transpile_with_grid(sql, dialect, spec.n_periods)
factcat/spec.py ADDED
@@ -0,0 +1,102 @@
1
+ """Analysis definitions.
2
+
3
+ Every field that other product analytics tools hard-code is a parameter here.
4
+ That is the whole point of the library, so the dataclasses are the design
5
+ document as much as the code is.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class RetentionSpec:
15
+ """A retention definition.
16
+
17
+ Attributes:
18
+ table: source relation. Typically a dbt mart, not a raw event stream.
19
+ entity: the grain retention is measured at. **Not** assumed to be the
20
+ user: a subscription, a household, a device, a seat or an
21
+ account are all valid, and they give different answers on the
22
+ same data.
23
+ entity_time: expression giving the entity's cohort entry instant.
24
+ event_time: expression giving the instant of an observation.
25
+ period_days: period length in days. Arbitrary. 35 is a 30-day billing cycle
26
+ plus a 5-day dunning window, and no calendar bucket expresses it.
27
+ n_periods: how many periods to project.
28
+ retained: arbitrary SQL boolean deciding whether a row counts as retention
29
+ for its period. May reference any source column plus the derived
30
+ columns below.
31
+ cohort_bucket: expression bucketing entities into cohorts.
32
+ where: optional filter applied to the source relation.
33
+
34
+ Derived columns available to ``retained``:
35
+ ``offset_days``
36
+ whole days from the entity's cohort entry.
37
+ ``period_index``
38
+ which period the observation falls in, counting from zero.
39
+ ``within_period_offset``
40
+ whole days since this period opened. A 5-day dunning window is
41
+ ``within_period_offset <= 5``.
42
+ """
43
+
44
+ table: str
45
+ entity: str
46
+ entity_time: str
47
+ event_time: str
48
+ period_days: int
49
+ n_periods: int
50
+ retained: str
51
+ cohort_bucket: str = "date_trunc('month', cohort_ts)"
52
+ where: str | None = None
53
+
54
+ def __post_init__(self) -> None:
55
+ if self.period_days < 1:
56
+ raise ValueError("period_days must be >= 1")
57
+ if self.n_periods < 1:
58
+ raise ValueError("n_periods must be >= 1")
59
+ if not self.retained.strip():
60
+ raise ValueError("retained must be a SQL boolean expression")
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class FunnelSpec:
65
+ """An ordered funnel definition.
66
+
67
+ Steps are matched in order and each step must occur at or after the previous
68
+ one, taking the **earliest** qualifying event at every stage. As with
69
+ retention, the entity is yours to choose - a funnel over subscriptions and a
70
+ funnel over users are different questions about the same table.
71
+
72
+ Attributes:
73
+ table: source relation.
74
+ entity: the grain the funnel is counted at.
75
+ event_time: expression giving the instant of an observation.
76
+ steps: ordered SQL boolean expressions, one per step. At least two.
77
+ step_labels: optional display labels, defaulting to ``step_0``, ``step_1``...
78
+ within_days: optional completion window, measured from the first step. None
79
+ means unbounded.
80
+ where: optional filter applied to the source relation.
81
+ """
82
+
83
+ table: str
84
+ entity: str
85
+ event_time: str
86
+ steps: tuple[str, ...]
87
+ step_labels: tuple[str, ...] | None = None
88
+ within_days: int | None = None
89
+ where: str | None = None
90
+
91
+ def __post_init__(self) -> None:
92
+ if len(self.steps) < 2:
93
+ raise ValueError("a funnel needs at least two steps")
94
+ if self.step_labels is not None and len(self.step_labels) != len(self.steps):
95
+ raise ValueError("step_labels must match steps in length")
96
+ if self.within_days is not None and self.within_days < 0:
97
+ raise ValueError("within_days must be >= 0")
98
+
99
+ def labels(self) -> tuple[str, ...]:
100
+ if self.step_labels is not None:
101
+ return self.step_labels
102
+ return tuple(f"step_{i}" for i in range(len(self.steps)))
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.5
2
+ Name: factcat
3
+ Version: 0.1.0
4
+ Summary: Product analytics on the event model already in your warehouse
5
+ Project-URL: Homepage, https://github.com/gordonkjlee/factcat
6
+ Project-URL: Source, https://github.com/gordonkjlee/factcat
7
+ Author: Gordon Lee
8
+ License: MIT
9
+ Keywords: analytics,dbt,funnel,retention,sql,warehouse
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Database
13
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: sqlglot>=25.0.0
16
+ Provides-Extra: dev
17
+ Requires-Dist: duckdb>=1.0.0; extra == 'dev'
18
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # factcat
22
+
23
+ Product analytics on the event model already in your warehouse. Your grain, your periods,
24
+ your definitions.
25
+
26
+ Every other product analytics tool hard-codes `entity = user`, `period = a calendar bucket`,
27
+ and `retained = did any event`. Real definitions violate all three:
28
+
29
+ ```python
30
+ from factcat import RetentionSpec, retention_sql
31
+
32
+ spec = RetentionSpec(
33
+ table="analytics.fct_subscription_payments",
34
+ entity="subscription_id", # not the user
35
+ entity_time="sub_start",
36
+ event_time="paid_at",
37
+ period_days=35, # a billing cycle plus dunning, not a calendar bucket
38
+ n_periods=12,
39
+ retained="status = 'collected' AND within_period_offset <= 5",
40
+ )
41
+
42
+ print(retention_sql(spec, dialect="snowflake"))
43
+ ```
44
+
45
+ `retained` is arbitrary SQL over any column in your table, plus the derived columns
46
+ `offset_days`, `period_index` and `within_period_offset`.
47
+
48
+ Generates SQL and queries in place. No SDK, no ingestion, no copy of your data. Supports
49
+ DuckDB, Postgres, BigQuery, Snowflake, Databricks, Spark, Trino, Presto, ClickHouse and
50
+ Redshift.
51
+
52
+ Full documentation: https://github.com/gordonkjlee/factcat
@@ -0,0 +1,9 @@
1
+ factcat/__init__.py,sha256=ZxW9kmocx_wY8y4hzaE9920SOh_j7DDT_Chf7a0uS2I,1009
2
+ factcat/_emit.py,sha256=0ctyoxNN-ABTyH5HTUMzTV17MIaOrnqlZhVwrAzR4JY,2402
3
+ factcat/dialects.py,sha256=oJ39o__vrhLEvzIQAulp4pQGF9jiiOOnf_CnKBXTjt4,2396
4
+ factcat/funnel.py,sha256=7GV-OhDic9Bqa-xCc-wbtjFiJ01GfYzFv8IDwMCZKYA,3254
5
+ factcat/retention.py,sha256=moX-CLHLAPRiwT_eq3sERwMCsUkS3L7Z7mO6XkzX6mo,3463
6
+ factcat/spec.py,sha256=K0fJ4RYnKX5d84pyTgl-VF75K37N7wMcyjS9d6Lffkw,4147
7
+ factcat-0.1.0.dist-info/METADATA,sha256=ygZ8YlQ3HnGWsT2TsAJQa25B0YW_ueBuVABzGlm8OAk,1867
8
+ factcat-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
9
+ factcat-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any