rw create table when start app

This commit is contained in:
2025-03-12 20:52:23 +08:00
parent d9a71976f5
commit 210603b685
9 changed files with 898 additions and 104 deletions

View File

@@ -27,60 +27,5 @@ const createClickHouseClient = () => {
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;