Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(TESTFIX-001): Make the V1 test suite green on this box: isolated test databases

ralph24d8e1452bd9
diff --git a/packages/core/test/exports-map.test.ts b/packages/core/test/exports-map.test.ts
index 98d20f0ca..bea97a753 100644
--- a/packages/core/test/exports-map.test.ts
+++ b/packages/core/test/exports-map.test.ts
@@ -13,6 +13,8 @@ test('a non-exported internal path does not resolve', async () => {
});
test('preload pins infrastructure at local addresses', () => {
- expect(process.env.CLICKHOUSE_URL).toBe('http://localhost:8123/openpanel');
+ expect(process.env.CLICKHOUSE_URL).toBe(
+ 'http://localhost:8123/openpanel_test'
+ );
expect(process.env.SELF_HOSTED).toBe('true');
});
diff --git a/packages/core/test/preload.ts b/packages/core/test/preload.ts
index e6fca3f3e..19c709739 100644
--- a/packages/core/test/preload.ts
+++ b/packages/core/test/preload.ts
@@ -4,11 +4,13 @@
// `globalSetup` — so everything here must be idempotent and cheap.
//
// The pins below are a safety property, not a convenience: they are the
-// successor to vitest.shared.ts's "always point at local Docker — never
-// production, regardless of .env". A test must not be able to reach a real
-// database because someone's .env happened to be loaded.
+// successor to vitest.shared.ts's "always point at local, ISOLATED test
+// databases — never production, and never the application's own". A test must
+// not be able to reach a real database because someone's .env happened to be
+// loaded. Kept in step with test/databases.ts by hand — core does not import
+// from the V1 root test directory.
process.env.DATABASE_URL =
- 'postgresql://postgres:postgres@localhost:5432/postgres?schema=public';
-process.env.CLICKHOUSE_URL = 'http://localhost:8123/openpanel';
+ 'postgresql://postgres:postgres@localhost:5432/openpanel_test?schema=public';
+process.env.CLICKHOUSE_URL = 'http://localhost:8123/openpanel_test';
process.env.REDIS_URL = 'redis://localhost:6379';
process.env.SELF_HOSTED = 'true';
diff --git a/test/bootstrap-databases.ts b/test/bootstrap-databases.ts
new file mode 100644
index 000000000..bdbbeeabd
--- /dev/null
+++ b/test/bootstrap-databases.ts
@@ -0,0 +1,112 @@
+/**
+ * Creates and migrates the suite's isolated databases (see ./databases).
+ *
+ * Called from globalSetup before any fixture loads. Every step is idempotent,
+ * so a warm box pays only the cost of the checks.
+ */
+
+import { execFileSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import * as path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createClient } from '../packages/db/src/clickhouse/client';
+import { PrismaClient } from '../packages/db/src/generated/prisma/client';
+import {
+ clickhouseUrl,
+ POSTGRES_MAINTENANCE_URL,
+ TEST_CLICKHOUSE_DATABASE,
+ TEST_CLICKHOUSE_URL,
+ TEST_DATABASE_URL,
+ TEST_POSTGRES_DATABASE,
+} from './databases';
+
+const testDir = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(testDir, '..');
+const prismaBin = path.join(repoRoot, 'packages/db/node_modules/.bin/prisma');
+const prismaSchema = path.join(repoRoot, 'packages/db/prisma/schema.prisma');
+const clickhouseSchema = path.join(testDir, 'clickhouse-schema.sql');
+
+/** Always present; only used as a foothold for `CREATE DATABASE`. */
+const CLICKHOUSE_DEFAULT_DATABASE = 'default';
+
+// Every statement in clickhouse-schema.sql is terminated by a line holding
+// nothing but ';'.
+const STATEMENT_SEPARATOR = '\n;';
+const COMMENT_PREFIX = '--';
+
+async function ensurePostgresDatabase() {
+ const maintenance = new PrismaClient({
+ datasources: { db: { url: POSTGRES_MAINTENANCE_URL } },
+ });
+ try {
+ const existing = await maintenance.$queryRawUnsafe<unknown[]>(
+ 'SELECT 1 FROM pg_database WHERE datname = $1',
+ TEST_POSTGRES_DATABASE
+ );
+ if (existing.length === 0) {
+ // Identifier, not a value — it cannot be parameterised. The name is a
+ // module constant, never user input.
+ await maintenance.$executeRawUnsafe(
+ `CREATE DATABASE "${TEST_POSTGRES_DATABASE}"`
+ );
+ }
+ } finally {
+ await maintenance.$disconnect();
+ }
+}
+
+function migratePostgresSchema() {
+ execFileSync(prismaBin, ['migrate', 'deploy', '--schema', prismaSchema], {
+ cwd: repoRoot,
+ // Both: schema.prisma's datasource declares `directUrl`, and the repo's
+ // .env leaves DATABASE_URL_DIRECT as an unexpanded shell reference that
+ // the Prisma CLI's own dotenv loader cannot resolve.
+ env: {
+ ...process.env,
+ DATABASE_URL: TEST_DATABASE_URL,
+ DATABASE_URL_DIRECT: TEST_DATABASE_URL,
+ },
+ stdio: 'pipe',
+ });
+}
+
+function readClickhouseStatements() {
+ return readFileSync(clickhouseSchema, 'utf8')
+ .split('\n')
+ .filter((line) => !line.startsWith(COMMENT_PREFIX))
+ .join('\n')
+ .split(STATEMENT_SEPARATOR)
+ .map((statement) => statement.trim())
+ .filter((statement) => statement.length > 0);
+}
+
+async function ensureClickhouseDatabase() {
+ const server = createClient({
+ url: clickhouseUrl(CLICKHOUSE_DEFAULT_DATABASE),
+ });
+ try {
+ await server.command({
+ query: `CREATE DATABASE IF NOT EXISTS ${TEST_CLICKHOUSE_DATABASE}`,
+ });
+ } finally {
+ await server.close();
+ }
+}
+
+async function migrateClickhouseSchema() {
+ const client = createClient({ url: TEST_CLICKHOUSE_URL });
+ try {
+ for (const query of readClickhouseStatements()) {
+ await client.command({ query });
+ }
+ } finally {
+ await client.close();
+ }
+}
+
+export async function bootstrapTestDatabases() {
+ await ensurePostgresDatabase();
+ migratePostgresSchema();
+ await ensureClickhouseDatabase();
+ await migrateClickhouseSchema();
+}
diff --git a/test/clickhouse-schema.sql b/test/clickhouse-schema.sql
new file mode 100644
index 000000000..e3238c4f8
--- /dev/null
+++ b/test/clickhouse-schema.sql
@@ -0,0 +1,507 @@
+-- ClickHouse schema for the ISOLATED test database (see test/databases.ts).
+--
+-- Captured from the schema the V1 code-migrations produce, with every
+-- statement made idempotent so test/bootstrap-databases.ts can replay it on
+-- every run. Statements are separated by a line containing a single ';'.
+--
+-- Base tables come first; the materialized views SELECT from them.
+--
+-- Deliberately omitted: the `epv_keys` projection migration 19 adds to
+-- event_property_values_mv. It lives on the view's implicit `.inner_id.<uuid>`
+-- storage table, so it cannot be named in portable DDL, and it changes only
+-- how a query is read, never what it returns.
+--
+-- This is a TEST-ONLY artifact. It is not a migration and nothing outside
+-- test/ reads it — packages/db/code-migrations remains the source of truth
+-- for real databases.
+
+CREATE TABLE IF NOT EXISTS cohort_members
+(
+ `project_id` String CODEC(ZSTD(3)),
+ `cohort_id` String CODEC(ZSTD(3)),
+ `profile_id` String CODEC(ZSTD(3)),
+ `matched_at` DateTime DEFAULT now(),
+ `matching_properties` Map(String, String) CODEC(ZSTD(3)),
+ `version` UInt64 DEFAULT 1,
+ INDEX idx_profile profile_id TYPE bloom_filter GRANULARITY 1,
+ INDEX idx_cohort cohort_id TYPE bloom_filter GRANULARITY 1
+)
+ENGINE = ReplacingMergeTree(version)
+PARTITION BY toYYYYMM(matched_at)
+ORDER BY (project_id, cohort_id, profile_id)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS cohort_metadata
+(
+ `project_id` String,
+ `cohort_id` String,
+ `member_count` UInt64,
+ `last_computed_at` DateTime,
+ `sample_profiles` Array(String),
+ `version` UInt64 DEFAULT 1
+)
+ENGINE = ReplacingMergeTree(version)
+ORDER BY (project_id, cohort_id)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS events
+(
+ `id` UUID DEFAULT generateUUIDv4(),
+ `name` LowCardinality(String),
+ `sdk_name` LowCardinality(String),
+ `sdk_version` LowCardinality(String),
+ `device_id` String CODEC(ZSTD(3)),
+ `profile_id` String CODEC(ZSTD(3)),
+ `project_id` String CODEC(ZSTD(3)),
+ `session_id` String CODEC(LZ4),
+ `groups` Array(String) DEFAULT [] CODEC(ZSTD(3)),
+ `path` String CODEC(ZSTD(3)),
+ `origin` String CODEC(ZSTD(3)),
+ `referrer` String CODEC(ZSTD(3)),
+ `referrer_name` String CODEC(ZSTD(3)),
+ `referrer_type` LowCardinality(String),
+ `revenue` UInt64,
+ `duration` UInt64 CODEC(Delta(4), LZ4),
+ `properties` Map(String, String) CODEC(ZSTD(3)),
+ `created_at` DateTime64(3) CODEC(DoubleDelta, ZSTD(3)),
+ `country` LowCardinality(FixedString(2)),
+ `city` String,
+ `region` LowCardinality(String),
+ `longitude` Nullable(Float32) CODEC(Gorilla(4), LZ4),
+ `latitude` Nullable(Float32) CODEC(Gorilla(4), LZ4),
+ `os` LowCardinality(String),
+ `os_version` LowCardinality(String),
+ `browser` LowCardinality(String),
+ `browser_version` LowCardinality(String),
+ `device` LowCardinality(String),
+ `brand` LowCardinality(String),
+ `model` LowCardinality(String),
+ `imported_at` Nullable(DateTime) CODEC(Delta(4), LZ4),
+ `inserted_at` DateTime64(3) DEFAULT created_at,
+ INDEX idx_name name TYPE bloom_filter GRANULARITY 1,
+ INDEX idx_properties_bounce properties['__bounce'] TYPE set(3) GRANULARITY 1,
+ INDEX idx_origin origin TYPE bloom_filter(0.05) GRANULARITY 1,
+ INDEX idx_path path TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_profile_id profile_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_inserted_at inserted_at TYPE minmax GRANULARITY 1
+)
+ENGINE = MergeTree
+PARTITION BY toYYYYMM(created_at)
+ORDER BY (project_id, toDate(created_at), created_at, name)
+SETTINGS index_granularity = 8192, enable_block_offset_column = 1, enable_block_number_column = 1
+;
+
+CREATE TABLE IF NOT EXISTS events_bots
+(
+ `id` UUID DEFAULT generateUUIDv4(),
+ `project_id` String,
+ `name` String,
+ `type` String,
+ `path` String,
+ `created_at` DateTime64(3)
+)
+ENGINE = MergeTree
+ORDER BY (project_id, created_at)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS events_imports
+(
+ `id` UUID DEFAULT generateUUIDv4(),
+ `name` LowCardinality(String),
+ `sdk_name` LowCardinality(String),
+ `sdk_version` LowCardinality(String),
+ `device_id` String CODEC(ZSTD(3)),
+ `profile_id` String CODEC(ZSTD(3)),
+ `project_id` String CODEC(ZSTD(3)),
+ `session_id` String CODEC(LZ4),
+ `path` String CODEC(ZSTD(3)),
+ `origin` String CODEC(ZSTD(3)),
+ `referrer` String CODEC(ZSTD(3)),
+ `referrer_name` String CODEC(ZSTD(3)),
+ `referrer_type` LowCardinality(String),
+ `duration` UInt64 CODEC(Delta(4), LZ4),
+ `properties` Map(String, String) CODEC(ZSTD(3)),
+ `created_at` DateTime64(3) CODEC(DoubleDelta, ZSTD(3)),
+ `country` LowCardinality(FixedString(2)),
+ `city` String,
+ `region` LowCardinality(String),
+ `longitude` Nullable(Float32) CODEC(Gorilla(4), LZ4),
+ `latitude` Nullable(Float32) CODEC(Gorilla(4), LZ4),
+ `os` LowCardinality(String),
+ `os_version` LowCardinality(String),
+ `browser` LowCardinality(String),
+ `browser_version` LowCardinality(String),
+ `device` LowCardinality(String),
+ `brand` LowCardinality(String),
+ `model` LowCardinality(String),
+ `imported_at` Nullable(DateTime) CODEC(Delta(4), LZ4),
+ `import_id` String CODEC(ZSTD(3)),
+ `import_status` LowCardinality(String) DEFAULT 'pending',
+ `imported_at_meta` DateTime DEFAULT now()
+)
+ENGINE = MergeTree
+PARTITION BY toYYYYMM(imported_at_meta)
+ORDER BY (import_id, created_at)
+TTL imported_at_meta + toIntervalDay(7)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS groups
+(
+ `id` String,
+ `project_id` String,
+ `type` String,
+ `name` String,
+ `properties` Map(String, String),
+ `created_at` DateTime,
+ `version` UInt64,
+ `deleted` UInt8 DEFAULT 0
+)
+ENGINE = ReplacingMergeTree(version, deleted)
+ORDER BY (project_id, id)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS gsc_daily
+(
+ `project_id` String CODEC(ZSTD(3)),
+ `date` Date CODEC(Delta(2), LZ4),
+ `clicks` UInt32 CODEC(Delta(4), LZ4),
+ `impressions` UInt32 CODEC(Delta(4), LZ4),
+ `ctr` Float32 CODEC(Gorilla(4), LZ4),
+ `position` Float32 CODEC(Gorilla(4), LZ4),
+ `synced_at` DateTime DEFAULT now() CODEC(Delta(4), LZ4)
+)
+ENGINE = ReplacingMergeTree(synced_at)
+PARTITION BY toYYYYMM(date)
+ORDER BY (project_id, date)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS gsc_pages_daily
+(
+ `project_id` String CODEC(ZSTD(3)),
+ `date` Date CODEC(Delta(2), LZ4),
+ `page` String CODEC(ZSTD(3)),
+ `clicks` UInt32 CODEC(Delta(4), LZ4),
+ `impressions` UInt32 CODEC(Delta(4), LZ4),
+ `ctr` Float32 CODEC(Gorilla(4), LZ4),
+ `position` Float32 CODEC(Gorilla(4), LZ4),
+ `synced_at` DateTime DEFAULT now() CODEC(Delta(4), LZ4)
+)
+ENGINE = ReplacingMergeTree(synced_at)
+PARTITION BY toYYYYMM(date)
+ORDER BY (project_id, date, page)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS gsc_queries_daily
+(
+ `project_id` String CODEC(ZSTD(3)),
+ `date` Date CODEC(Delta(2), LZ4),
+ `query` String CODEC(ZSTD(3)),
+ `clicks` UInt32 CODEC(Delta(4), LZ4),
+ `impressions` UInt32 CODEC(Delta(4), LZ4),
+ `ctr` Float32 CODEC(Gorilla(4), LZ4),
+ `position` Float32 CODEC(Gorilla(4), LZ4),
+ `synced_at` DateTime DEFAULT now() CODEC(Delta(4), LZ4)
+)
+ENGINE = ReplacingMergeTree(synced_at)
+PARTITION BY toYYYYMM(date)
+ORDER BY (project_id, date, query)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS profile_aliases
+(
+ `project_id` String,
+ `profile_id` String,
+ `alias` String,
+ `created_at` DateTime
+)
+ENGINE = MergeTree
+ORDER BY (project_id, profile_id, alias, created_at)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS profiles
+(
+ `id` String CODEC(ZSTD(3)),
+ `is_external` Bool,
+ `first_name` String CODEC(ZSTD(3)),
+ `last_name` String CODEC(ZSTD(3)),
+ `email` String CODEC(ZSTD(3)),
+ `avatar` String CODEC(ZSTD(3)),
+ `properties` Map(String, String) CODEC(ZSTD(3)),
+ `project_id` String CODEC(ZSTD(3)),
+ `groups` Array(String) DEFAULT [] CODEC(ZSTD(3)),
+ `created_at` DateTime64(3) CODEC(Delta(4), LZ4),
+ `last_seen_at` DateTime64(3) CODEC(Delta(4), LZ4),
+ INDEX idx_first_name first_name TYPE bloom_filter GRANULARITY 1,
+ INDEX idx_last_name last_name TYPE bloom_filter GRANULARITY 1,
+ INDEX idx_email email TYPE bloom_filter GRANULARITY 1
+)
+ENGINE = ReplacingMergeTree(last_seen_at)
+PARTITION BY toYYYYMM(created_at)
+ORDER BY (project_id, id)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS self_hosting
+(
+ `created_at` Date,
+ `domain` String,
+ `count` UInt64
+)
+ENGINE = MergeTree
+PARTITION BY toYYYYMM(created_at)
+ORDER BY (domain, created_at)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS session_replay_chunks
+(
+ `project_id` String CODEC(ZSTD(3)),
+ `session_id` String CODEC(ZSTD(3)),
+ `chunk_index` UInt16,
+ `started_at` DateTime64(3) CODEC(DoubleDelta, ZSTD(3)),
+ `ended_at` DateTime64(3) CODEC(DoubleDelta, ZSTD(3)),
+ `events_count` UInt16,
+ `is_full_snapshot` Bool,
+ `payload` String CODEC(ZSTD(6))
+)
+ENGINE = MergeTree
+PARTITION BY toYYYYMMDD(started_at)
+ORDER BY (project_id, session_id, started_at, chunk_index)
+TTL started_at + toIntervalDay(30)
+SETTINGS index_granularity = 8192
+;
+
+CREATE TABLE IF NOT EXISTS sessions
+(
+ `id` String,
+ `project_id` String CODEC(ZSTD(3)),
+ `profile_id` String CODEC(ZSTD(3)),
+ `device_id` String CODEC(ZSTD(3)),
+ `groups` Array(String) DEFAULT [] CODEC(ZSTD(3)),
+ `created_at` DateTime64(3) CODEC(DoubleDelta, ZSTD(3)),
+ `ended_at` DateTime64(3) CODEC(DoubleDelta, ZSTD(3)),
+ `is_bounce` Bool,
+ `entry_origin` LowCardinality(String),
+ `entry_path` String CODEC(ZSTD(3)),
+ `exit_origin` LowCardinality(String),
+ `exit_path` String CODEC(ZSTD(3)),
+ `screen_view_count` Int32,
+ `revenue` Float64,
+ `event_count` Int32,
+ `duration` UInt32,
+ `country` LowCardinality(FixedString(2)),
+ `region` LowCardinality(String),
+ `city` String,
+ `longitude` Nullable(Float32) CODEC(Gorilla(4), LZ4),
+ `latitude` Nullable(Float32) CODEC(Gorilla(4), LZ4),
+ `device` LowCardinality(String),
+ `brand` LowCardinality(String),
+ `model` LowCardinality(String),
+ `browser` LowCardinality(String),
+ `browser_version` LowCardinality(String),
+ `os` LowCardinality(String),
+ `os_version` LowCardinality(String),
+ `utm_medium` String CODEC(ZSTD(3)),
+ `utm_source` String CODEC(ZSTD(3)),
+ `utm_campaign` String CODEC(ZSTD(3)),
+ `utm_content` String CODEC(ZSTD(3)),
+ `utm_term` String CODEC(ZSTD(3)),
+ `referrer` String CODEC(ZSTD(3)),
+ `referrer_name` String CODEC(ZSTD(3)),
+ `referrer_type` LowCardinality(String),
+ `sign` Int8,
+ `version` UInt64
+)
+ENGINE = VersionedCollapsingMergeTree(sign, version)
+PARTITION BY toYYYYMM(created_at)
+ORDER BY (project_id, toDate(created_at), created_at)
+SETTINGS index_granularity = 8192
+;
+
+CREATE MATERIALIZED VIEW IF NOT EXISTS cohort_events_mv
+(
+ `project_id` String,
+ `name` LowCardinality(String),
+ `created_at` Date,
+ `profile_id` String,
+ `event_count` UInt64
+)
+ENGINE = AggregatingMergeTree
+ORDER BY (project_id, name, created_at, profile_id)
+SETTINGS index_granularity = 8192
+AS SELECT
+ project_id,
+ name,
+ toDate(created_at) AS created_at,
+ profile_id,
+ count() AS event_count
+FROM events
+WHERE profile_id != device_id
+GROUP BY
+ project_id,
+ name,
+ created_at,
+ profile_id
+;
+
+CREATE MATERIALIZED VIEW IF NOT EXISTS dau_mv
+(
+ `date` Date,
+ `profile_id` AggregateFunction(uniq, String),
+ `project_id` String
+)
+ENGINE = AggregatingMergeTree
+PARTITION BY toYYYYMMDD(date)
+ORDER BY (project_id, date)
+SETTINGS index_granularity = 8192
+AS SELECT
+ toDate(created_at) AS date,
+ uniqState(profile_id) AS profile_id,
+ project_id
+FROM events
+GROUP BY
+ date,
+ project_id
+;
+
+CREATE MATERIALIZED VIEW IF NOT EXISTS distinct_event_names_mv
+(
+ `project_id` String,
+ `name` LowCardinality(String),
+ `created_at` DateTime64(3),
+ `event_count` UInt64
+)
+ENGINE = AggregatingMergeTree
+ORDER BY (project_id, name, created_at)
+SETTINGS index_granularity = 8192
+AS SELECT
+ project_id,
+ name,
+ max(created_at) AS created_at,
+ count() AS event_count
+FROM events
+GROUP BY
+ project_id,
+ name
+;
+
+CREATE MATERIALIZED VIEW IF NOT EXISTS event_profile_summary_mv
+(
+ `project_id` String,
+ `profile_id` String,
+ `name` LowCardinality(String),
+ `event_date` DateTime,
+ `event_count` AggregateFunction(count),
+ `first_event_time` AggregateFunction(min, DateTime64(3)),
+ `last_event_time` AggregateFunction(max, DateTime64(3)),
+ `total_duration` AggregateFunction(sum, UInt64)
+)
+ENGINE = AggregatingMergeTree
+PARTITION BY toYYYYMM(event_date)
+ORDER BY (project_id, name, event_date, profile_id)
+SETTINGS index_granularity = 8192
+AS SELECT
+ project_id,
+ profile_id,
+ name,
+ toStartOfDay(created_at) AS event_date,
+ countState() AS event_count,
+ minState(created_at) AS first_event_time,
+ maxState(created_at) AS last_event_time,
+ sumState(duration) AS total_duration
+FROM events
+WHERE profile_id != device_id
+GROUP BY
+ project_id,
+ profile_id,
+ name,
+ event_date
+;
+
+CREATE MATERIALIZED VIEW IF NOT EXISTS event_property_profile_summary_mv
+(
+ `project_id` String,
+ `profile_id` String,
+ `name` LowCardinality(String),
+ `property_key` String,
+ `property_value` String,
+ `event_date` DateTime,
+ `event_count` AggregateFunction(count),
+ `first_event_time` AggregateFunction(min, DateTime64(3)),
+ `last_event_time` AggregateFunction(max, DateTime64(3))
+)
+ENGINE = AggregatingMergeTree
+PARTITION BY toYYYYMM(event_date)
+ORDER BY (project_id, name, property_key, property_value, event_date, profile_id)
+SETTINGS index_granularity = 8192
+AS SELECT
+ project_id,
+ profile_id,
+ name,
+ property_key,
+ property_value,
+ toStartOfDay(created_at) AS event_date,
+ countState() AS event_count,
+ minState(created_at) AS first_event_time,
+ maxState(created_at) AS last_event_time
+FROM events
+ARRAY JOIN
+ mapKeys(properties) AS property_key,
+ mapValues(properties) AS property_value
+WHERE (profile_id != device_id) AND (property_key != '') AND (property_value != '')
+GROUP BY
+ project_id,
+ profile_id,
+ name,
+ property_key,
+ property_value,
+ event_date
+;
+
+CREATE MATERIALIZED VIEW IF NOT EXISTS event_property_values_mv
+(
+ `project_id` String,
+ `name` LowCardinality(String),
+ `property_key` String,
+ `property_value` String,
+ `created_at` DateTime64(3)
+)
+ENGINE = AggregatingMergeTree
+ORDER BY (project_id, name, property_key, property_value)
+SETTINGS index_granularity = 8192
+AS SELECT
+ project_id,
+ name,
+ key_value.keys AS property_key,
+ key_value.values AS property_value,
+ created_at
+FROM
+(
+ SELECT
+ project_id,
+ name,
+ untuple(arrayJoin(properties)) AS key_value,
+ max(created_at) AS created_at
+ FROM events
+ GROUP BY
+ project_id,
+ name,
+ key_value
+)
+WHERE (property_value != '') AND (property_key != '') AND (property_key NOT IN ('__duration_from', '__properties_from'))
+GROUP BY
+ project_id,
+ name,
+ property_key,
+ property_value,
+ created_at
+;
diff --git a/test/databases.ts b/test/databases.ts
new file mode 100644
index 000000000..d3a4bb5e7
--- /dev/null
+++ b/test/databases.ts
@@ -0,0 +1,42 @@
+/**
+ * Connection details for the suite's ISOLATED databases.
+ *
+ * Tests get their own Postgres and ClickHouse databases, never the ones the
+ * application uses. On this box the application databases hold a copy of
+ * production, which breaks tests twice over: fixture teardown issues
+ * `DELETE FROM events WHERE project_id = ...`, which mutates the dataset the
+ * migration goldens are diffed against, and a lightweight delete against a
+ * 318M-row table does not finish inside a test timeout.
+ *
+ * Every test connection string is derived from here — vitest.shared.ts pins
+ * the worker env at these values and test/bootstrap-databases.ts creates and
+ * migrates them. Nothing in test/ may hard-code a database name.
+ */
+
+const POSTGRES_ORIGIN = 'postgresql://postgres:postgres@localhost:5432';
+const CLICKHOUSE_ORIGIN = 'http://localhost:8123';
+
+export const TEST_POSTGRES_DATABASE = 'openpanel_test';
+export const TEST_CLICKHOUSE_DATABASE = 'openpanel_test';
+
+/** `CREATE DATABASE` cannot be issued from inside the database it creates. */
+export const POSTGRES_MAINTENANCE_DATABASE = 'postgres';
+
+export const postgresUrl = (database: string) =>
+ `${POSTGRES_ORIGIN}/${database}?schema=public`;
+
+export const clickhouseUrl = (database: string) =>
+ `${CLICKHOUSE_ORIGIN}/${database}`;
+
+export const TEST_DATABASE_URL = postgresUrl(TEST_POSTGRES_DATABASE);
+export const POSTGRES_MAINTENANCE_URL = postgresUrl(
+ POSTGRES_MAINTENANCE_DATABASE
+);
+export const TEST_CLICKHOUSE_URL = clickhouseUrl(TEST_CLICKHOUSE_DATABASE);
+
+/**
+ * Redis is deliberately NOT isolated — unchanged from the previous pin. It
+ * holds no prod copy and no golden, so it carries neither hazard this module
+ * exists to remove.
+ */
+export const TEST_REDIS_URL = 'redis://localhost:6379';
diff --git a/test/fixtures.ts b/test/fixtures.ts
index 3cf300d97..481e2128d 100644
--- a/test/fixtures.ts
+++ b/test/fixtures.ts
@@ -24,13 +24,12 @@
import { createClient } from '../packages/db/src/clickhouse/client';
import { PrismaClient } from '../packages/db/src/generated/prisma/client';
+import { TEST_CLICKHOUSE_URL, TEST_DATABASE_URL } from './databases';
// Lazily create a Prisma client so DATABASE_URL is read at call time,
// not at module-import time (globalSetup runs before env is configured).
function getDb() {
- const url =
- process.env.DATABASE_URL ??
- 'postgresql://postgres:postgres@localhost:5432/postgres?schema=public';
+ const url = process.env.DATABASE_URL ?? TEST_DATABASE_URL;
return new PrismaClient({ datasources: { db: { url } } });
}
@@ -72,7 +71,7 @@ export const FIXTURE = {
type ChClient = ReturnType<typeof createClient>;
function getClient() {
- const url = process.env.CLICKHOUSE_URL ?? 'http://localhost:8123';
+ const url = process.env.CLICKHOUSE_URL ?? TEST_CLICKHOUSE_URL;
return createClient({ url });
}
@@ -183,7 +182,7 @@ async function insertFixtures(client: ChClient, projectId: string) {
const now = new Date();
await client.insert({
- table: 'openpanel.profiles',
+ table: 'profiles',
values: [
{
id: FIXTURE.profiles.alice,
@@ -234,7 +233,7 @@ async function insertFixtures(client: ChClient, projectId: string) {
// Charlie: session_start → screen_view → page_view → purchase → session_end (5 days ago, spaced 5 min apart)
// Events are spaced so windowFunnel strict_increase mode works correctly.
await client.insert({
- table: 'openpanel.events',
+ table: 'events',
values: [
buildEvent(
now,
@@ -329,7 +328,7 @@ async function insertFixtures(client: ChClient, projectId: string) {
});
await client.insert({
- table: 'openpanel.sessions',
+ table: 'sessions',
values: [
buildSession(
now,
@@ -376,16 +375,16 @@ async function insertFixtures(client: ChClient, projectId: string) {
async function deleteFixtures(client: ChClient, projectId: string) {
await Promise.all([
client.command({
- query: `DELETE FROM openpanel.profiles WHERE project_id = '${projectId}'`,
+ query: `DELETE FROM profiles WHERE project_id = '${projectId}'`,
}),
client.command({
- query: `DELETE FROM openpanel.events WHERE project_id = '${projectId}'`,
+ query: `DELETE FROM events WHERE project_id = '${projectId}'`,
}),
client.command({
- query: `DELETE FROM openpanel.sessions WHERE project_id = '${projectId}'`,
+ query: `DELETE FROM sessions WHERE project_id = '${projectId}'`,
}),
client.command({
- query: `ALTER TABLE openpanel.distinct_event_names_mv DELETE WHERE project_id = '${projectId}'`,
+ query: `ALTER TABLE distinct_event_names_mv DELETE WHERE project_id = '${projectId}'`,
}),
]);
}
diff --git a/test/global-setup.ts b/test/global-setup.ts
index 595d7bf79..c12768a76 100644
--- a/test/global-setup.ts
+++ b/test/global-setup.ts
@@ -1,3 +1,5 @@
+import { bootstrapTestDatabases } from './bootstrap-databases';
+import { TEST_CLICKHOUSE_URL, TEST_DATABASE_URL } from './databases';
import {
setupFixtures,
setupPostgresFixtures,
@@ -10,21 +12,21 @@ export const TEST_PROJECT_ID = 'integration-test';
export const TEST_ORG_ID = 'integration-org';
// globalSetup runs in the parent process before vitest workers start,
-// so vitest's `env` config is not applied — set defaults explicitly.
-function setEnvDefaults() {
- process.env.DATABASE_URL ??=
- 'postgresql://postgres:postgres@localhost:5432/postgres?schema=public';
- process.env.CLICKHOUSE_URL ??= 'http://localhost:8123/openpanel';
+// so vitest's `env` config is not applied — set the same pins explicitly.
+function pinTestDatabases() {
+ process.env.DATABASE_URL = TEST_DATABASE_URL;
+ process.env.CLICKHOUSE_URL = TEST_CLICKHOUSE_URL;
}
export async function setup() {
- setEnvDefaults();
+ pinTestDatabases();
+ await bootstrapTestDatabases();
await setupPostgresFixtures(TEST_PROJECT_ID, TEST_ORG_ID);
await setupFixtures(TEST_PROJECT_ID);
}
export async function teardown() {
- setEnvDefaults();
+ pinTestDatabases();
await teardownFixtures(TEST_PROJECT_ID);
await teardownPostgresFixtures(TEST_PROJECT_ID, TEST_ORG_ID);
}
diff --git a/test/retention-fixtures.ts b/test/retention-fixtures.ts
index 6579fb2ff..6dc28d412 100644
--- a/test/retention-fixtures.ts
+++ b/test/retention-fixtures.ts
@@ -34,6 +34,7 @@
*/
import { createClient } from '../packages/db/src/clickhouse/client';
+import { TEST_CLICKHOUSE_URL } from './databases';
// ---------------------------------------------------------------------------
// Well-known ids + absolute dates
@@ -116,7 +117,7 @@ export const RETENTION_BLUEPRINT = {
type ChClient = ReturnType<typeof createClient>;
function getClient(): ChClient {
- const url = process.env.CLICKHOUSE_URL ?? 'http://localhost:8123';
+ const url = process.env.CLICKHOUSE_URL ?? TEST_CLICKHOUSE_URL;
return createClient({ url });
}
@@ -213,15 +214,15 @@ function buildCohortMembers(projectId: string) {
async function deleteFixtures(client: ChClient, projectId: string) {
await Promise.all([
client.command({
- query: `DELETE FROM openpanel.events WHERE project_id = '${projectId}'`,
+ query: `DELETE FROM events WHERE project_id = '${projectId}'`,
}),
// Materialized views are NOT touched by DELETE FROM events; mutate them too
// so reruns stay clean.
client.command({
- query: `ALTER TABLE openpanel.cohort_events_mv DELETE WHERE project_id = '${projectId}'`,
+ query: `ALTER TABLE cohort_events_mv DELETE WHERE project_id = '${projectId}'`,
}),
client.command({
- query: `DELETE FROM openpanel.cohort_members WHERE project_id = '${projectId}'`,
+ query: `DELETE FROM cohort_members WHERE project_id = '${projectId}'`,
}),
]);
}
@@ -231,12 +232,12 @@ export async function setupRetentionFixtures(projectId: string): Promise<void> {
try {
await deleteFixtures(client, projectId);
await client.insert({
- table: 'openpanel.events',
+ table: 'events',
values: buildEvents(projectId),
format: 'JSONEachRow',
});
await client.insert({
- table: 'openpanel.cohort_members',
+ table: 'cohort_members',
values: buildCohortMembers(projectId),
format: 'JSONEachRow',
});
diff --git a/vitest.shared.ts b/vitest.shared.ts
index c44c4dc6a..f16743a34 100644
--- a/vitest.shared.ts
+++ b/vitest.shared.ts
@@ -1,5 +1,10 @@
import * as path from 'node:path';
import { defineConfig } from 'vitest/config';
+import {
+ TEST_CLICKHOUSE_URL,
+ TEST_DATABASE_URL,
+ TEST_REDIS_URL,
+} from './test/databases';
// Absolute path to the root test-setup — used as setupFiles so every package
// gets connection-pool cleanup without needing a per-package file.
@@ -19,10 +24,12 @@ export const getSharedVitestConfig = ({
test: {
setupFiles: [rootTestSetup(dirname)],
env: {
- // Always point at local Docker — never production, regardless of .env
- DATABASE_URL: 'postgresql://postgres:postgres@localhost:5432/postgres?schema=public',
- CLICKHOUSE_URL: 'http://localhost:8123/openpanel',
- REDIS_URL: 'redis://localhost:6379',
+ // Always point at the local, ISOLATED test databases — never
+ // production, and never the application's own databases, regardless
+ // of .env. See test/databases.ts.
+ DATABASE_URL: TEST_DATABASE_URL,
+ CLICKHOUSE_URL: TEST_CLICKHOUSE_URL,
+ REDIS_URL: TEST_REDIS_URL,
SELF_HOSTED: 'true',
},
include: ['**/*.test.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],