86 lines
2.7 KiB
TypeScript
86 lines
2.7 KiB
TypeScript
import { createClient } from '@clickhouse/client';
|
|
import config from '../config';
|
|
|
|
// Create ClickHouse client with error handling
|
|
const createClickHouseClient = () => {
|
|
try {
|
|
return createClient({
|
|
host: `http://${config.clickhouse.host}:${config.clickhouse.port}`,
|
|
username: config.clickhouse.user,
|
|
password: config.clickhouse.password,
|
|
database: config.clickhouse.database,
|
|
});
|
|
} catch (error) {
|
|
console.error('Error creating ClickHouse client:', error);
|
|
// Return a mock client for development that logs operations instead of executing them
|
|
return {
|
|
query: async ({ query, values }: { query: string; values?: any[] }) => {
|
|
console.log('ClickHouse query (mock):', query, values);
|
|
return { rows: [] };
|
|
},
|
|
close: async () => {
|
|
console.log('ClickHouse connection closed (mock)');
|
|
}
|
|
};
|
|
}
|
|
};
|
|
|
|
const clickhouse = createClickHouseClient();
|
|
|
|
// Initialize ClickHouse database and tables
|
|
export const initClickHouse = async () => {
|
|
try {
|
|
// Create database if not exists
|
|
await clickhouse.query({
|
|
query: `CREATE DATABASE IF NOT EXISTS ${config.clickhouse.database}`,
|
|
});
|
|
|
|
// Create tables for tracking events
|
|
await clickhouse.query({
|
|
query: `
|
|
CREATE TABLE IF NOT EXISTS ${config.clickhouse.database}.view_events (
|
|
user_id String,
|
|
content_id String,
|
|
timestamp DateTime DEFAULT now(),
|
|
ip String,
|
|
user_agent String
|
|
) ENGINE = MergeTree()
|
|
PARTITION BY toYYYYMM(timestamp)
|
|
ORDER BY (user_id, content_id, timestamp)
|
|
`,
|
|
});
|
|
|
|
await clickhouse.query({
|
|
query: `
|
|
CREATE TABLE IF NOT EXISTS ${config.clickhouse.database}.like_events (
|
|
user_id String,
|
|
content_id String,
|
|
timestamp DateTime DEFAULT now(),
|
|
action Enum('like' = 1, 'unlike' = 2)
|
|
) ENGINE = MergeTree()
|
|
PARTITION BY toYYYYMM(timestamp)
|
|
ORDER BY (user_id, content_id, timestamp)
|
|
`,
|
|
});
|
|
|
|
await clickhouse.query({
|
|
query: `
|
|
CREATE TABLE IF NOT EXISTS ${config.clickhouse.database}.follower_events (
|
|
follower_id String,
|
|
followed_id String,
|
|
timestamp DateTime DEFAULT now(),
|
|
action Enum('follow' = 1, 'unfollow' = 2)
|
|
) ENGINE = MergeTree()
|
|
PARTITION BY toYYYYMM(timestamp)
|
|
ORDER BY (follower_id, followed_id, timestamp)
|
|
`,
|
|
});
|
|
|
|
console.log('ClickHouse database and tables initialized');
|
|
} catch (error) {
|
|
console.error('Error initializing ClickHouse:', error);
|
|
console.log('Continuing with limited functionality...');
|
|
}
|
|
};
|
|
|
|
export default clickhouse;
|