Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat: add cloud-specific ClickHouse table and materialized view creation

Bill Yang3fde169bd0d2
diff --git a/server/src/db/clickhouse/clickhouse.ts b/server/src/db/clickhouse/clickhouse.ts
index 4becf42fb..e43acae28 100644
--- a/server/src/db/clickhouse/clickhouse.ts
+++ b/server/src/db/clickhouse/clickhouse.ts
@@ -1,4 +1,5 @@
import { createClient } from "@clickhouse/client";
+import { IS_CLOUD } from "../../lib/const.js";
export const clickhouse = createClient({
url: process.env.CLICKHOUSE_HOST,
@@ -44,6 +45,38 @@ export const initializeClickhouse = async () => {
ORDER BY (site_id, timestamp)
`,
});
+
+ if (IS_CLOUD) {
+ await clickhouse.exec({
+ query: `
+ CREATE TABLE IF NOT EXISTS hourly_events_by_site_mv_target (
+ event_hour DateTime, -- The specific hour
+ site_id UInt16,
+ event_count UInt64 -- The count of events for that site in that hour
+ )
+ ENGINE = SummingMergeTree() -- Sums 'event_count' for rows with the same sorting key
+ PARTITION BY toYYYYMM(event_hour)
+ ORDER BY (event_hour, site_id)
+ TTL event_hour + INTERVAL 60 DAY
+ `,
+ });
+
+ // 2. Create the Materialized View
+ // This MV will populate the 'hourly_events_by_site_mv_target' table.
+ await clickhouse.exec({
+ query: `
+ CREATE MATERIALIZED VIEW IF NOT EXISTS hourly_events_by_site_mv
+ POPULATE
+ TO hourly_events_by_site_mv_target -- Name of the target table
+ AS SELECT
+ toStartOfHour(timestamp) AS event_hour,
+ site_id,
+ count() AS event_count
+ FROM events
+ GROUP BY event_hour, site_id
+ `,
+ });
+ }
};
export default clickhouse;