Files
tourrism_site/database/init-database.js
Andrey K. Choi a461fea9d9 Компактные hero секции и улучшенная инициализация БД
🎨 UI улучшения:
- Уменьшена высота синих панелей с 100vh до 70vh на главной
- Добавлен класс .compact (25vh) для всех остальных страниц
- Улучшена адаптивность для мобильных устройств
- Обновлены все шаблоны с hero секциями

🚀 Инфраструктура:
- Автоматическая инициализация базы данных при деплое
- Улучшены мокапные данные (больше отзывов, бронирований, сообщений)
- Добавлены настройки сайта в базу данных
- Создан скрипт автоматического деплоя deploy.sh

📦 Система сборки:
- Обновлен .gitignore с полным покрытием файлов
- Добавлена папка для загрузок с .gitkeep
- Улучшен README с инструкциями по запуску
- ES модули для инициализации базы данных

🐛 Исправления:
- Совместимость с ES модулями в Node.js
- Правильная обработка ошибок инициализации БД
- Корректные SQL запросы для PostgreSQL
2025-11-29 18:47:42 +09:00

77 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import db from '../src/config/database.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export async function initDatabase() {
try {
console.log('🚀 Starting complete database initialization...');
// Check if database is connected
await db.query('SELECT 1');
console.log('✅ Database connection successful');
// 1. Create schema
console.log('📋 Creating database schema...');
const schemaPath = path.join(__dirname, 'schema.sql');
const schema = fs.readFileSync(schemaPath, 'utf8');
await db.query(schema);
console.log('✅ Database schema created successfully');
// 2. Check if tables are empty (first run)
const checkResult = await db.query('SELECT COUNT(*) FROM admins');
const isEmpty = parseInt(checkResult.rows[0].count) === 0;
if (isEmpty) {
console.log('📝 Database is empty, inserting mock data...');
// Insert mock data
const mockDataPath = path.join(__dirname, 'mock-data.sql');
const mockData = fs.readFileSync(mockDataPath, 'utf8');
await db.query(mockData);
console.log('✅ Mock data inserted successfully');
} else {
console.log(' Database already contains data, skipping mock data insertion');
}
// 3. Run any pending migrations
console.log('🔄 Checking for pending migrations...');
// Check if rating system exists
try {
await db.query('SELECT 1 FROM route_ratings LIMIT 1');
console.log(' Rating system already exists');
} catch (error) {
console.log('📈 Installing rating system...');
const ratingMigrationPath = path.join(__dirname, 'rating-system-migration.sql');
if (fs.existsSync(ratingMigrationPath)) {
const ratingMigration = fs.readFileSync(ratingMigrationPath, 'utf8');
await db.query(ratingMigration);
console.log('✅ Rating system installed successfully');
}
}
console.log('✨ Database initialization completed successfully!');
} catch (error) {
console.error('❌ Database initialization failed:', error);
throw error;
}
}
// Run if called directly
if (process.argv[1] === fileURLToPath(import.meta.url)) {
initDatabase()
.then(() => {
console.log('🎉 All done!');
process.exit(0);
})
.catch((error) => {
console.error('💥 Initialization failed:', error);
process.exit(1);
});
}