mainly functional matching
This commit is contained in:
86
scripts/createProfileViewsTable.js
Normal file
86
scripts/createProfileViewsTable.js
Normal file
@@ -0,0 +1,86 @@
|
||||
const { Pool } = require('pg');
|
||||
require('dotenv').config();
|
||||
|
||||
const pool = new Pool({
|
||||
host: process.env.DB_HOST,
|
||||
port: parseInt(process.env.DB_PORT || '5432'),
|
||||
database: process.env.DB_NAME,
|
||||
user: process.env.DB_USERNAME,
|
||||
password: process.env.DB_PASSWORD
|
||||
});
|
||||
|
||||
async function createProfileViewsTable() {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
console.log('Creating profile_views table...');
|
||||
await client.query('BEGIN');
|
||||
|
||||
// Включаем расширение uuid-ossp, если оно еще не включено
|
||||
await client.query(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
|
||||
|
||||
// Создаем таблицу profile_views, если она не существует
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS profile_views (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
viewer_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
viewed_profile_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
view_date TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
view_type VARCHAR(20) NOT NULL DEFAULT 'browse'
|
||||
)
|
||||
`);
|
||||
|
||||
// Создаем уникальный индекс для пары (просмотревший - просмотренный)
|
||||
await client.query(`
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE indexname = 'profile_views_viewer_viewed_idx'
|
||||
) THEN
|
||||
CREATE UNIQUE INDEX profile_views_viewer_viewed_idx
|
||||
ON profile_views (viewer_id, viewed_profile_id);
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
|
||||
// Создаем индекс для быстрого поиска по viewer_id
|
||||
await client.query(`
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE indexname = 'profile_views_viewer_idx'
|
||||
) THEN
|
||||
CREATE INDEX profile_views_viewer_idx
|
||||
ON profile_views (viewer_id);
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
|
||||
// Создаем индекс для быстрого поиска по viewed_profile_id
|
||||
await client.query(`
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_indexes
|
||||
WHERE indexname = 'profile_views_viewed_idx'
|
||||
) THEN
|
||||
CREATE INDEX profile_views_viewed_idx
|
||||
ON profile_views (viewed_profile_id);
|
||||
END IF;
|
||||
END $$;
|
||||
`);
|
||||
|
||||
await client.query('COMMIT');
|
||||
console.log('Table profile_views created successfully');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
console.error('Error creating table:', e);
|
||||
} finally {
|
||||
client.release();
|
||||
await pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
// Запускаем функцию создания таблицы
|
||||
createProfileViewsTable();
|
||||
Reference in New Issue
Block a user