OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
self-hosting: openpanel export replaces export-for-cloud.sh
Carl-Gerhard Lindesvärde68c83febeb6
diff --git a/self-hosting/cli/src/commands/export.ts b/self-hosting/cli/src/commands/export.tsnew file mode 100644index 000000000..4841601ea--- /dev/null+++ b/self-hosting/cli/src/commands/export.ts@@ -0,0 +1,146 @@+import { resolve } from 'node:path';+import { log as clackLog } from '@clack/prompts';+import {+ type Auth,+ type ClickHouse,+ createClient,+ dockerPrefix,+ findContainers,+ holdsEvents,+ probeAll,+} from '../export/clickhouse';+import {+ DEFAULT_ROWS_PER_FILE,+ DEFAULT_TABLES,+ runExport,+} from '../export/export';+import { run } from '../run';+import { bold, dim, green, log } from '../ui';++export interface ExportFlags {+ container?: string;+ out: string;+ projectId?: string;+ from?: string;+ to?: string;+ tables?: string;+ rowsPerFile?: string;+ db: string;+ list: boolean;+ noGzip: boolean;+}++const splitList = (value: string | undefined): string[] =>+ (value ?? '')+ .split(/[\s,]+/)+ .map((item) => item.trim())+ .filter(Boolean);++// Credentials are rarely needed (the default container has none), and arriving+// by env keeps them out of shell history.+const authFromEnv = (): Auth => ({+ host: process.env.CH_HOST,+ user: process.env.CH_USER,+ password: process.env.CH_PASSWORD,+});++const printCandidates = async (db: string, auth: Auth) => {+ const rows = await probeAll(db, auth);+ if (rows.length === 0) {+ log('No running containers. Is Docker running, and do you need sudo?');+ return;+ }+ log(bold(`Running containers, and whether they hold '${db}.events':\n`));+ for (const row of rows) {+ const mark = row.hasEvents ? green('yes') : dim('-');+ log(` ${row.id.padEnd(14)} ${row.name.padEnd(42)} ${mark}`);+ }+ log('\nThen run: openpanel export --container <CONTAINER ID>');+};++const resolveClient = async (+ flags: ExportFlags,+ auth: Auth+): Promise<ClickHouse> => {+ if (flags.container) {+ if (!(await holdsEvents(flags.container, flags.db, auth))) {+ throw new Error(+ `Container '${flags.container}' has no '${flags.db}.events' table. Wrong container, or wrong --db? Try \`openpanel export --list\`.`+ );+ }+ return createClient(dockerPrefix(flags.container), flags.db, auth);+ }++ const matches = await findContainers(flags.db, auth);+ const [only] = matches;+ if (matches.length === 1 && only) {+ clackLog.info(`ClickHouse container: ${only.name} (${only.id})`);+ return createClient(dockerPrefix(only.id), flags.db, auth);+ }+ if (matches.length > 1) {+ const names = matches+ .map((match) => ` ${match.id} ${match.name}`)+ .join('\n');+ throw new Error(+ `Found ${matches.length} containers with '${flags.db}.events':\n${names}\nPick one with --container <CONTAINER ID>`+ );+ }+ if ((await run(['clickhouse-client', '--version'])).code === 0) {+ clackLog.info('Using clickhouse-client from PATH');+ return createClient(['clickhouse-client'], flags.db, auth);+ }+ throw new Error(+ `No container holds '${flags.db}.events'. Run \`openpanel export --list\`, then pass --container.`+ );+};++export const exportData = async (flags: ExportFlags): Promise<number> => {+ const auth = authFromEnv();+ if (flags.list) {+ await printCandidates(flags.db, auth);+ return 0;+ }++ const client = await resolveClient(flags, auth);+ const out = resolve(flags.out);+ const projectIds = splitList(flags.projectId);+ const tables = splitList(flags.tables);++ log(`Exporting to ${out}`);+ log(+ dim(+ `projects: ${projectIds.join(',') || '<all>'} range: ${flags.from ?? '<start>'} .. ${flags.to ?? '<now>'}\n`+ )+ );++ const result = await runExport(+ client,+ {+ out,+ database: flags.db,+ tables: tables.length > 0 ? tables : [...DEFAULT_TABLES],+ projectIds,+ from: flags.from,+ to: flags.to,+ rowsPerFile: Number(flags.rowsPerFile ?? DEFAULT_ROWS_PER_FILE),+ gzip: !flags.noGzip,+ },+ {+ onTable: (table) => log(bold(table)),+ onDay: (day, rows) => log(` ${day} ${String(rows).padStart(8)} rows`),+ onSkip: (table) => log(dim(`${table} — table does not exist, skipping`)),+ }+ );++ log(green('\nDone.'));+ log(`Projects found: ${result.projectIds}`);+ for (const { table, rows, files } of result.summaries) {+ log(+ ` ${table.padEnd(18)} ${String(rows).padStart(10)} rows in ${files} file(s)`+ );+ }+ log(+ `\nShip it with:\n tar czf op-export.tar.gz -C "${resolve(out, '..')}" "${out.split('/').pop()}"`+ );+ return 0;+};diff --git a/self-hosting/cli/src/export/clickhouse.ts b/self-hosting/cli/src/export/clickhouse.tsnew file mode 100644index 000000000..2c9e064cc--- /dev/null+++ b/self-hosting/cli/src/export/clickhouse.ts@@ -0,0 +1,152 @@+import { type ChildProcess, spawn } from 'node:child_process';+import type { Readable } from 'node:stream';+import { run } from '../run';++export interface Auth {+ host?: string;+ user?: string;+ password?: string;+}++// The two ways export talks to ClickHouse: one-shot queries, and a streamed+// result that is piped to disk without buffering a whole day in memory.+export interface ClickHouse {+ query: (sql: string) => Promise<string>;+ stream: (sql: string) => { output: Readable; done: Promise<void> };+}++export interface Candidate {+ id: string;+ name: string;+ image: string;+}++const authArgs = (auth: Auth): string[] => [+ ...(auth.host ? [`--host=${auth.host}`] : []),+ ...(auth.user ? [`--user=${auth.user}`] : []),+ ...(auth.password ? [`--password=${auth.password}`] : []),+];++const finish = (child: ChildProcess, label: string): Promise<void> =>+ new Promise((resolve, reject) => {+ child.on('error', reject);+ child.on('close', (code) =>+ code === 0 ? resolve() : reject(new Error(`${label} exited with ${code}`))+ );+ });++// `prefix` is the command that reaches a clickhouse-client: either+// `docker exec -i <container> clickhouse-client` or a local binary.+export const createClient = (+ prefix: string[],+ database: string,+ auth: Auth+): ClickHouse => {+ const [binary = '', ...base] = prefix;+ // `--max_execution_time=0`: a day of events can outlast the default limit.+ const args = (sql: string) => [+ ...base,+ `--database=${database}`,+ '--max_execution_time=0',+ ...authArgs(auth),+ `--query=${sql}`,+ ];+ return {+ query: async (sql) => {+ const { code, stdout } = await run([binary, ...args(sql)]);+ if (code !== 0) {+ throw new Error(`ClickHouse query failed: ${sql.slice(0, 80)}`);+ }+ return stdout.trim();+ },+ stream: (sql) => {+ // stdin is closed on purpose: `docker exec -i` would otherwise read ours.+ const child = spawn(binary, args(sql), {+ stdio: ['ignore', 'pipe', 'inherit'],+ });+ return {+ output: child.stdout as Readable,+ done: finish(child, 'clickhouse-client'),+ };+ },+ };+};++const listContainers = async (): Promise<Candidate[]> => {+ const { stdout } = await run([+ 'docker',+ 'ps',+ '--format',+ '{{.ID}}\t{{.Names}}\t{{.Image}}',+ ]);+ return stdout+ .split('\n')+ .filter(Boolean)+ .map((line) => {+ const [id = '', name = '', image = ''] = line.split('\t');+ return { id, name, image };+ });+};++const looksLikeClickHouse = ({ name, image }: Candidate) =>+ /clickhouse/i.test(image) || /clickhouse|op-ch/i.test(name);++const PROBE_SQL = (database: string) =>+ `SELECT count() FROM system.tables WHERE database = '${database}' AND name = 'events'`;++export const holdsEvents = async (+ containerId: string,+ database: string,+ auth: Auth+): Promise<boolean> => {+ const { code, stdout } = await run([+ 'docker',+ 'exec',+ containerId,+ 'clickhouse-client',+ ...authArgs(auth),+ '--query',+ PROBE_SQL(database),+ ]);+ return code === 0 && stdout.trim() === '1';+};++export const probeAll = async (database: string, auth: Auth) => {+ const containers = await listContainers();+ return Promise.all(+ containers.map(async (container) => ({+ ...container,+ hasEvents: await holdsEvents(container.id, database, auth),+ }))+ );+};++// Container names are not portable (compose, Coolify and Dokploy all differ), so+// a candidate only counts if it really holds the events table. Name-matched+// containers are tried first, then every container, in case an image was rebranded.+export const findContainers = async (+ database: string,+ auth: Auth+): Promise<Candidate[]> => {+ const all = await listContainers();+ for (const scope of [all.filter(looksLikeClickHouse), all]) {+ const matches: Candidate[] = [];+ for (const candidate of scope) {+ if (await holdsEvents(candidate.id, database, auth)) {+ matches.push(candidate);+ }+ }+ if (matches.length > 0) {+ return matches;+ }+ }+ return [];+};++export const dockerPrefix = (containerId: string): string[] => [+ 'docker',+ 'exec',+ '-i',+ containerId,+ 'clickhouse-client',+];diff --git a/self-hosting/cli/src/export/export.ts b/self-hosting/cli/src/export/export.tsnew file mode 100644index 000000000..3af473b55--- /dev/null+++ b/self-hosting/cli/src/export/export.ts@@ -0,0 +1,281 @@+import { createWriteStream } from 'node:fs';+import { appendFile, mkdir, rm, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { Transform } from 'node:stream';+import { pipeline } from 'node:stream/promises';+import { createGzip } from 'node:zlib';+import type { ClickHouse } from './clickhouse';++export const DEFAULT_TABLES = [+ 'events',+ 'sessions',+ 'profiles',+ 'groups',+] as const;+export const DEFAULT_ROWS_PER_FILE = 100_000;++const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;+const PROJECT_ID = /^[A-Za-z0-9_-]+$/;+const TIMESTAMP = /^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?)?$/;+const NEWLINE = 0x0a;++export interface ExportOptions {+ out: string;+ database: string;+ tables: string[];+ projectIds: string[];+ from?: string;+ to?: string;+ rowsPerFile: number;+ gzip: boolean;+}++export interface TableSummary {+ table: string;+ rows: number;+ files: number;+}++export interface ExportProgress {+ onTable: (table: string) => void;+ onDay: (day: string, rows: number) => void;+ onSkip: (table: string) => void;+}++// Everything here ends up inside SQL, so it is checked rather than escaped.+export const validateOptions = (options: ExportOptions): void => {+ const bad = (what: string, value: string) => {+ throw new Error(`Invalid ${what}: "${value}"`);+ };+ if (!IDENTIFIER.test(options.database)) {+ bad('--db', options.database);+ }+ for (const table of options.tables) {+ if (!IDENTIFIER.test(table)) {+ bad('table name', table);+ }+ }+ for (const id of options.projectIds) {+ if (!PROJECT_ID.test(id)) {+ bad('project id', id);+ }+ }+ for (const [flag, value] of [+ ['--from', options.from],+ ['--to', options.to],+ ] as const) {+ if (value && !TIMESTAMP.test(value)) {+ bad(`${flag} (use "YYYY-MM-DD" or "YYYY-MM-DD HH:MM[:SS]")`, value);+ }+ }+ if (!Number.isInteger(options.rowsPerFile) || options.rowsPerFile < 1) {+ bad('--rows-per-file', String(options.rowsPerFile));+ }+};++// `country` is a LowCardinality(FixedString(2)) that JSON-encodes empty values+// as NULs; normalise them so the JSONL stays clean.+const COUNTRY_FIX =+ "* EXCEPT (country), replaceAll(toString(country), '\\0', '') AS country";++interface TableRules {+ select: string;+ from: (table: string) => string;+ extra: string;+ order: string;+ dateColumn: string;+}++// sessions / profiles / groups are Replacing- or CollapsingMergeTree tables, so+// they need FINAL (and a sign/deleted filter) to yield one current row each.+export const rulesFor = (table: string): TableRules => ({+ select: table === 'events' || table === 'sessions' ? COUNTRY_FIX : '*',+ from: (name) =>+ ['sessions', 'profiles', 'groups'].includes(name) ? `${name} FINAL` : name,+ extra:+ table === 'sessions'+ ? 'AND sign > 0'+ : table === 'groups'+ ? 'AND deleted = 0'+ : '',+ // Deterministic tiebreaker so LIMIT/OFFSET paging never skips or repeats a row.+ order:+ table === 'session_replay_chunks'+ ? 'started_at, session_id, chunk_index'+ : 'created_at, id',+ dateColumn: table === 'session_replay_chunks' ? 'started_at' : 'created_at',+});++const whereClause = (options: ExportOptions, rules: TableRules): string => {+ const project =+ options.projectIds.length > 0+ ? `project_id IN ('${options.projectIds.join("','")}')`+ : '1';+ const range = [+ options.from+ ? ` AND ${rules.dateColumn} >= toDateTime64('${options.from}', 3)`+ : '',+ options.to+ ? ` AND ${rules.dateColumn} < toDateTime64('${options.to}', 3)`+ : '',+ ].join('');+ return `WHERE ${project} ${rules.extra}${range}`;+};++const countNewlines = (counter: { lines: number }) =>+ new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ for (const byte of chunk) {+ if (byte === NEWLINE) {+ counter.lines++;+ }+ }+ callback(null, chunk);+ },+ });++// Counts what actually landed rather than what the counting pass predicted: on a+// live system they differ, and a stale estimate would make the verifier cry wolf.+// A failed write removes its file, since the importer reads the directory, not+// the manifest, and would treat a truncated file as complete.+const writeQuery = async (+ client: ClickHouse,+ sql: string,+ file: string,+ gzip: boolean+): Promise<number> => {+ const counter = { lines: 0 };+ const { output, done } = client.stream(sql);+ try {+ await Promise.all([+ pipeline(+ output,+ countNewlines(counter),+ ...(gzip ? [createGzip()] : []),+ createWriteStream(file)+ ),+ done,+ ]);+ } catch (error) {+ await rm(file, { force: true });+ throw error;+ }+ return counter.lines;+};++const exportTable = async (+ client: ClickHouse,+ options: ExportOptions,+ table: string,+ manifest: string,+ progress: ExportProgress+): Promise<TableSummary> => {+ const rules = rulesFor(table);+ const from = rules.from(table);+ const where = whereClause(options, rules);+ const tableDir = join(options.out, table);+ await mkdir(tableDir, { recursive: true });++ // One pass to learn each day's row count, then page through the days.+ // Day-sized windows keep OFFSET tiny, so paging stays cheap.+ const days = await client.query(+ `SELECT toDate(${rules.dateColumn}) AS d, toDate(${rules.dateColumn}) + 1 AS d_next, count() AS c+ FROM ${from} ${where} GROUP BY d HAVING c > 0 ORDER BY d`+ );++ let rows = 0;+ let files = 0;+ for (const line of days.split('\n').filter(Boolean)) {+ const [day = '', nextDay = '', dayRowsText = '0'] = line.split('\t');+ const dayRows = Number(dayRowsText);+ let dayWritten = 0;+ for (+ let offset = 0, part = 0;+ offset < dayRows;+ offset += options.rowsPerFile, part+++ ) {+ const name = `${table}-${day}-${String(part).padStart(4, '0')}.jsonl${options.gzip ? '.gz' : ''}`;+ const written = await writeQuery(+ client,+ `SELECT ${rules.select}+ FROM ${from}+ ${where}+ AND ${rules.dateColumn} >= toDateTime64('${day}', 3)+ AND ${rules.dateColumn} < toDateTime64('${nextDay}', 3)+ ORDER BY ${rules.order}+ LIMIT ${options.rowsPerFile} OFFSET ${offset}+ FORMAT JSONEachRow`,+ join(tableDir, name),+ options.gzip+ );+ await appendFile(+ manifest,+ `${JSON.stringify({ table, file: name, day, rows: written })}\n`+ );+ dayWritten += written;+ files++;+ }+ rows += dayWritten;+ progress.onDay(day, dayWritten);+ }+ return { table, rows, files };+};++export const runExport = async (+ client: ClickHouse,+ options: ExportOptions,+ progress: ExportProgress+) => {+ validateOptions(options);+ await client.query('SELECT 1');+ await mkdir(options.out, { recursive: true });+ const manifest = join(options.out, 'manifest.jsonl');+ await writeFile(manifest, '');++ const clickhouseVersion = await client.query('SELECT version()');+ const summaries: TableSummary[] = [];+ for (const table of options.tables) {+ const exists = await client.query(+ `SELECT count() FROM system.tables WHERE database = '${options.database}' AND name = '${table}'`+ );+ if (exists === '0') {+ progress.onSkip(table);+ continue;+ }+ progress.onTable(table);+ summaries.push(+ await exportTable(client, options, table, manifest, progress)+ );+ }++ const projectFilter =+ options.projectIds.length > 0+ ? `project_id IN ('${options.projectIds.join("','")}')`+ : '1';+ const projectIds = await client+ .query(+ `SELECT groupUniqArray(project_id) FROM events WHERE ${projectFilter}`+ )+ .catch(() => '');++ await writeFile(+ join(options.out, '_meta.json'),+ `${JSON.stringify(+ {+ exported_at: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),+ clickhouse_version: clickhouseVersion,+ database: options.database,+ project_id_filter: options.projectIds.join(','),+ from: options.from ?? '',+ to: options.to ?? '',+ project_ids_in_events: projectIds,+ tables: Object.fromEntries(+ summaries.map(({ table, rows, files }) => [table, { rows, files }])+ ),+ },+ null,+ 2+ )}\n`+ );+ return { clickhouseVersion, projectIds, summaries, manifest };+};diff --git a/self-hosting/cli/src/main.ts b/self-hosting/cli/src/main.tsindex c547d6c86..7d21932f1 100644--- a/self-hosting/cli/src/main.ts+++ b/self-hosting/cli/src/main.ts@@ -3,10 +3,11 @@ import { join, resolve } from 'node:path';import { parseArgs } from 'node:util';import { compose, isComposeCommand } from './commands/compose';import { doctor } from './commands/doctor';+import { exportData } from './commands/export';import { init } from './commands/init';import { upgrade } from './commands/upgrade';import { isInstallDir } from './install';-import { log } from './ui';+import { log, red } from './ui';import { VERSION } from './version';const DEFAULT_DIR = join(homedir(), 'openpanel');@@ -18,6 +19,7 @@ Usage: openpanel <command> [options]Commands:init Interactive setup (--yes --domain <url> to skip prompts)upgrade [--yes] Update the CLI, repair the install, pull images, restart+ export [--out <dir>] Dump ClickHouse data as JSONL (e.g. to move to Cloud)doctor [--fix] [--check] Check the host and your install; --fix repairs itup | down | restart Start, stop, or recreate the stacklogs [service] Follow logs@@ -51,6 +53,16 @@ const main = async (): Promise<number> => {yes: { type: 'boolean', short: 'y', default: false },force: { type: 'boolean', default: false },'no-self-update': { type: 'boolean', default: false },+ container: { type: 'string' },+ out: { type: 'string' },+ 'project-id': { type: 'string' },+ from: { type: 'string' },+ to: { type: 'string' },+ tables: { type: 'string' },+ 'rows-per-file': { type: 'string' },+ db: { type: 'string' },+ list: { type: 'boolean', default: false },+ 'no-gzip': { type: 'boolean', default: false },domain: { type: 'string' },proxy: { type: 'string' },workers: { type: 'string' },@@ -93,6 +105,20 @@ const main = async (): Promise<number> => {emailSender: values['email-sender'],});}+ if (command === 'export') {+ return exportData({+ container: values.container,+ out: values.out ?? './op-export',+ projectId: values['project-id'],+ from: values.from,+ to: values.to,+ tables: values.tables,+ rowsPerFile: values['rows-per-file'],+ db: values.db ?? 'openpanel',+ list: values.list,+ noGzip: values['no-gzip'],+ });+ }if (command === 'upgrade') {return upgrade({dir,@@ -111,4 +137,10 @@ const main = async (): Promise<number> => {return 1;};-process.exit(await main());+try {+ process.exit(await main());+} catch (error) {+ // Expected failures (bad flag, no container) are a message, not a stack trace.+ console.error(`${red('error')} ${(error as Error).message}`);+ process.exit(1);+}diff --git a/self-hosting/cli/test/export.test.ts b/self-hosting/cli/test/export.test.tsnew file mode 100644index 000000000..0aa557016--- /dev/null+++ b/self-hosting/cli/test/export.test.ts@@ -0,0 +1,220 @@+import { afterEach, describe, expect, test } from 'bun:test';+import {+ existsSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Readable } from 'node:stream';+import { gunzipSync } from 'node:zlib';+import type { ClickHouse } from '../src/export/clickhouse';+import {+ type ExportOptions,+ runExport,+ validateOptions,+} from '../src/export/export';++const tempDirs: string[] = [];+afterEach(() => {+ for (const dir of tempDirs.splice(0)) {+ rmSync(dir, { recursive: true, force: true });+ }+});++const outDir = () => {+ const dir = mkdtempSync(join(tmpdir(), 'op-export-'));+ tempDirs.push(dir);+ return dir;+};++const options = (+ out: string,+ overrides: Partial<ExportOptions> = {}+): ExportOptions => ({+ out,+ database: 'openpanel',+ tables: ['events'],+ projectIds: [],+ rowsPerFile: 2,+ gzip: true,+ ...overrides,+});++const ignore = () => undefined;+const NO_PROGRESS = { onTable: ignore, onDay: ignore, onSkip: ignore };++// Answers the queries export issues and serves rows for the paged SELECTs.+const fakeClickHouse = (+ rows: string[],+ failStream = false+): { client: ClickHouse; sql: string[] } => {+ const sql: string[] = [];+ const client: ClickHouse = {+ query: async (query) => {+ sql.push(query);+ if (query.includes('system.tables')) {+ return '1';+ }+ if (query.includes('GROUP BY d')) {+ return `2026-08-17\t2026-08-18\t${rows.length}`;+ }+ if (query.includes('version()')) {+ return '26.1';+ }+ if (query.includes('groupUniqArray')) {+ return "['demo']";+ }+ return '1';+ },+ stream: (query) => {+ sql.push(query);+ const offset = Number(/OFFSET (\d+)/.exec(query)?.[1]);+ const page = rows+ .slice(offset, offset + 2)+ .map((row) => `${row}\n`)+ .join('');+ const output = Readable.from([page]);+ const done = failStream+ ? Promise.reject(new Error('clickhouse-client exited with 1'))+ : Promise.resolve();+ done.catch(ignore);+ return { output, done };+ },+ };+ return { client, sql };+};++describe('runExport', () => {+ test('pages a day into files of rowsPerFile and records what landed', async () => {+ const out = outDir();+ const { client } = fakeClickHouse([+ '{"id":"1"}',+ '{"id":"2"}',+ '{"id":"3"}',+ ]);++ const result = await runExport(client, options(out), NO_PROGRESS);++ expect(result.summaries).toEqual([{ table: 'events', rows: 3, files: 2 }]);+ expect(readdirSync(join(out, 'events')).sort()).toEqual([+ 'events-2026-08-17-0000.jsonl.gz',+ 'events-2026-08-17-0001.jsonl.gz',+ ]);+ const first = gunzipSync(+ readFileSync(join(out, 'events/events-2026-08-17-0000.jsonl.gz'))+ ).toString();+ expect(first).toBe('{"id":"1"}\n{"id":"2"}\n');++ const manifest = readFileSync(join(out, 'manifest.jsonl'), 'utf8')+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));+ expect(manifest).toEqual([+ {+ table: 'events',+ file: 'events-2026-08-17-0000.jsonl.gz',+ day: '2026-08-17',+ rows: 2,+ },+ {+ table: 'events',+ file: 'events-2026-08-17-0001.jsonl.gz',+ day: '2026-08-17',+ rows: 1,+ },+ ]);+ expect(+ JSON.parse(readFileSync(join(out, '_meta.json'), 'utf8')).tables+ ).toEqual({ events: { rows: 3, files: 2 } });+ });++ test('writes plain .jsonl with --no-gzip', async () => {+ const out = outDir();+ const { client } = fakeClickHouse(['{"id":"1"}']);+ await runExport(client, options(out, { gzip: false }), NO_PROGRESS);+ expect(readdirSync(join(out, 'events'))).toEqual([+ 'events-2026-08-17-0000.jsonl',+ ]);+ });++ test('sessions use FINAL and a sign filter, groups a deleted filter', async () => {+ const { client, sql } = fakeClickHouse(['{"id":"1"}']);+ await runExport(+ client,+ options(outDir(), { tables: ['sessions', 'groups'] }),+ NO_PROGRESS+ );++ expect(+ sql.some(+ (query) =>+ query.includes('FROM sessions FINAL') &&+ query.includes('AND sign > 0')+ )+ ).toBe(true);+ expect(+ sql.some(+ (query) =>+ query.includes('FROM groups FINAL') &&+ query.includes('AND deleted = 0')+ )+ ).toBe(true);+ });++ test('filters reach the query', async () => {+ const { client, sql } = fakeClickHouse(['{"id":"1"}']);+ await runExport(+ client,+ options(outDir(), {+ projectIds: ['a', 'b'],+ from: '2026-08-01',+ to: '2026-09-01 12:00',+ }),+ NO_PROGRESS+ );++ const paged = sql.find((query) => query.includes('OFFSET')) as string;+ expect(paged).toContain("project_id IN ('a','b')");+ expect(paged).toContain("created_at >= toDateTime64('2026-08-01', 3)");+ expect(paged).toContain("created_at < toDateTime64('2026-09-01 12:00', 3)");+ });++ test('a failed query removes its partial file instead of leaving it for the importer', async () => {+ const out = outDir();+ const { client } = fakeClickHouse(['{"id":"1"}'], true);++ await expect(runExport(client, options(out), NO_PROGRESS)).rejects.toThrow(+ 'exited with 1'+ );+ expect(+ existsSync(join(out, 'events/events-2026-08-17-0000.jsonl.gz'))+ ).toBe(false);+ });+});++describe('validateOptions', () => {+ const base = options('/tmp/x');++ test.each([+ ['project id', { projectIds: ["a') OR 1=1 --"] }],+ ['table name', { tables: ['events; DROP TABLE events'] }],+ ['--db', { database: 'open panel' }],+ ['--from', { from: "2026-08-01' OR 1=1" }],+ ['--rows-per-file', { rowsPerFile: 0 }],+ ])('rejects a bad %s', (_label, override) => {+ expect(() => validateOptions({ ...base, ...override })).toThrow('Invalid');+ });++ test('accepts dates with and without a time', () => {+ expect(() =>+ validateOptions({+ ...base,+ from: '2026-08-01',+ to: '2026-08-16 12:00:30',+ })+ ).not.toThrow();+ });+});diff --git a/self-hosting/cli/test/init.test.ts b/self-hosting/cli/test/init.test.tsindex f8f47415f..48a8b3a27 100644--- a/self-hosting/cli/test/init.test.ts+++ b/self-hosting/cli/test/init.test.ts@@ -13,6 +13,8 @@ import {} from '../src/init/generate';import { loadInstall, writeFiles } from '../src/install';+// Compose interpolation syntax, spelled so the linter does not mistake it for a typo'd template.+const DOLLAR = '$';const DOMAIN = 'https://analytics.example.com';const secrets = generateSecrets();@@ -88,7 +90,7 @@ describe('init output', () => {test('worker count is an overridable compose variable', async () => {const compose = composeOf(await generate({ workers: 3 }));expect(compose.services['op-worker'].deploy.replicas).toBe(- '${OP_WORKER_REPLICAS:-3}'+ `${DOLLAR}{OP_WORKER_REPLICAS:-3}`);});