Files
tg_tinder_bot/scripts/fixDatabaseStructure.js
2025-09-18 13:46:35 +09:00

171 lines
6.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Скрипт для исправления проблемы с ботом
require('dotenv').config();
const { Pool } = require('pg');
// Получаем данные подключения из .env
console.log('Параметры подключения к БД:');
console.log('DB_USERNAME:', process.env.DB_USERNAME);
console.log('DB_HOST:', process.env.DB_HOST);
console.log('DB_NAME:', process.env.DB_NAME);
console.log('DB_PASSWORD:', process.env.DB_PASSWORD ? '[указан]' : '[не указан]');
console.log('DB_PORT:', process.env.DB_PORT);
// Создаем пул соединений
const pool = new Pool({
user: process.env.DB_USERNAME,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: parseInt(process.env.DB_PORT || '5432')
});
async function fixDatabase() {
try {
console.log('Начинаем исправление базы данных...');
// Проверяем существование таблицы users
const tableResult = await pool.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'users'
);
`);
if (!tableResult.rows[0].exists) {
console.error('Таблица users не найдена!');
return;
}
console.log('✅ Таблица users существует');
// Проверяем и добавляем столбцы state и state_data, если они отсутствуют
console.log('Проверяем наличие столбцов state и state_data...');
const stateColumnResult = await pool.query(`
SELECT EXISTS (
SELECT FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'users'
AND column_name = 'state'
);
`);
const stateDataColumnResult = await pool.query(`
SELECT EXISTS (
SELECT FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'users'
AND column_name = 'state_data'
);
`);
if (!stateColumnResult.rows[0].exists) {
console.log('🔄 Добавляем столбец state...');
await pool.query(`ALTER TABLE users ADD COLUMN state VARCHAR(255) NULL;`);
console.log('✅ Столбец state успешно добавлен');
} else {
console.log('✅ Столбец state уже существует');
}
if (!stateDataColumnResult.rows[0].exists) {
console.log('🔄 Добавляем столбец state_data...');
await pool.query(`ALTER TABLE users ADD COLUMN state_data JSONB DEFAULT '{}'::jsonb;`);
console.log('✅ Столбец state_data успешно добавлен');
} else {
console.log('✅ Столбец state_data уже существует');
}
// Проверка наличия таблиц для уведомлений
console.log('Проверяем наличие таблиц для уведомлений...');
const tablesCheck = await Promise.all([
checkTableExists('notifications'),
checkTableExists('notification_settings'),
checkTableExists('scheduled_notifications')
]);
// Создаем отсутствующие таблицы
if (!tablesCheck[0]) {
console.log('🔄 Создаем таблицу notifications...');
await pool.query(`
CREATE TABLE notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(50) NOT NULL,
content JSONB NOT NULL DEFAULT '{}',
is_read BOOLEAN DEFAULT false,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_notifications_user_id ON notifications(user_id);
CREATE INDEX idx_notifications_type ON notifications(type);
CREATE INDEX idx_notifications_created_at ON notifications(created_at);
`);
console.log('✅ Таблица notifications успешно создана');
}
if (!tablesCheck[1]) {
console.log('🔄 Создаем таблицу notification_settings...');
await pool.query(`
CREATE TABLE notification_settings (
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
new_matches BOOLEAN DEFAULT true,
new_messages BOOLEAN DEFAULT true,
new_likes BOOLEAN DEFAULT true,
reminders BOOLEAN DEFAULT true,
daily_summary BOOLEAN DEFAULT false,
time_preference VARCHAR(20) DEFAULT 'evening',
do_not_disturb BOOLEAN DEFAULT false,
do_not_disturb_start TIME,
do_not_disturb_end TIME,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
`);
console.log('✅ Таблица notification_settings успешно создана');
}
if (!tablesCheck[2]) {
console.log('🔄 Создаем таблицу scheduled_notifications...');
await pool.query(`
CREATE TABLE scheduled_notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(50) NOT NULL,
content JSONB NOT NULL DEFAULT '{}',
scheduled_at TIMESTAMP WITH TIME ZONE NOT NULL,
processed BOOLEAN DEFAULT false,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_scheduled_notifications_user_id ON scheduled_notifications(user_id);
CREATE INDEX idx_scheduled_notifications_scheduled_at ON scheduled_notifications(scheduled_at);
CREATE INDEX idx_scheduled_notifications_processed ON scheduled_notifications(processed);
`);
console.log('✅ Таблица scheduled_notifications успешно создана');
}
console.log('✅ Исправление базы данных завершено успешно');
} catch (error) {
console.error('Ошибка при исправлении базы данных:', error);
} finally {
await pool.end();
}
}
async function checkTableExists(tableName) {
const result = await pool.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = $1
);
`, [tableName]);
const exists = result.rows[0].exists;
console.log(`${exists ? '✅' : '❌'} Таблица ${tableName} ${exists ? 'существует' : 'отсутствует'}`);
return exists;
}
fixDatabase();