/
varsl
/
HTML-CSS
Обзор
Документация
Войти
/
varsl
/
HTML-CSS
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
backend/database/init.js
154 строки
6 KB
varsl
Добавление файлов БД
21 дек 2025, 23:50
21 дек 2025, 23:50
90d5c7b
Код
Авторство
О чём код?
const sqlite3 = require('sqlite3').verbose(); const path = require('path'); const fs = require('fs'); const { dbPath } = require('../config'); // Ensure database directory exists const dbDir = path.dirname(dbPath); if (!fs.existsSync(dbDir)) { fs.mkdirSync(dbDir, { recursive: true }); } // Read schema const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8'); // Initialize database const db = new sqlite3.Database(dbPath, (err) => { if (err) { console.error('Error opening database:', err); process.exit(1); } console.log('Connected to SQLite database'); // Execute schema db.exec(schema, (err) => { if (err) { console.error('Error executing schema:', err); } else { console.log('Database schema initialized successfully'); // Insert sample animals if table is empty db.get('SELECT COUNT(*) as count FROM animals', (err, row) => { if (!err && row.count === 0) { insertSampleAnimals(); } else { console.log(`Animals table has ${row?.count || 0} records`); db.close(); } }); } }); }); function insertSampleAnimals() { const animals = [ { animal_id: 'lion', name: 'Лев', scientific_name: 'Panthera leo', type: 'mammal', habitat: 'Саванна', diet: 'Хищник', description: 'Крупная кошка, известная как "царь зверей". Социальные животные, живут в прайдах.', size: 'Длина: 1.7-2.5м, Вес: 150-250кг', lifespan: '10-14 лет в дикой природе', conservation_status: 'Уязвимый вид', image_url: 'lion.jpg', sound_url: 'lion.mp3', video_url: 'lion-video.mp4', fun_fact: 'Львы могут спать до 20 часов в сутки.', feeding_time: '14:00', show_schedule: 'Шоу хищников: 12:00, 16:00' }, { animal_id: 'elephant', name: 'Африканский слон', scientific_name: 'Loxodonta africana', type: 'mammal', habitat: 'Саванна, лес', diet: 'Травоядное', description: 'Крупнейшее наземное животное. Обладает отличной памятью и сложной социальной структурой.', size: 'Высота: 3-4м, Вес: 4-7 тонн', lifespan: '60-70 лет', conservation_status: 'Находится под угрозой', image_url: 'elephant.jpg', sound_url: 'elephant.mp3', video_url: 'elephant-video.mp4', fun_fact: 'Хобот слона содержит около 150 000 мышц.', feeding_time: '12:00, 16:00', show_schedule: 'Демонстрация слонов: 11:00, 15:00' }, { animal_id: 'panda', name: 'Большая панда', scientific_name: 'Ailuropoda melanoleuca', type: 'mammal', habitat: 'Бамбуковые леса', diet: 'Травоядное (99% бамбук)', description: 'Символ Китая и охраны природы. Проводят большую часть дня за едой.', size: 'Длина: 1.2-1.9м, Вес: 75-135кг', lifespan: '20 лет в неволе', conservation_status: 'Уязвимый вид', image_url: 'panda.jpg', sound_url: 'panda.mp3', video_url: 'panda-video.mp4', fun_fact: 'Новорожденная панда весит всего 100 грамм.', feeding_time: '11:00, 15:00', show_schedule: 'Кормление панд: 11:30, 15:30' }, { animal_id: 'tiger', name: 'Амурский тигр', scientific_name: 'Panthera tigris altaica', type: 'mammal', habitat: 'Тайга', diet: 'Хищник', description: 'Самый крупный представитель семейства кошачьих. Отличный охотник и пловец.', size: 'Длина: 2.7-3.3м, Вес: 180-300кг', lifespan: '15-20 лет', conservation_status: 'Находящийся под угрозой', image_url: 'tiger.jpg', sound_url: 'tiger.mp3', video_url: 'tiger-video.mp4', fun_fact: 'Узор полосок у каждого тигра уникален, как отпечатки пальцев у человека.', feeding_time: '13:00', show_schedule: 'Тигриное шоу: 13:30' } ]; const stmt = db.prepare(` INSERT INTO animals ( animal_id, name, scientific_name, type, habitat, diet, description, size, lifespan, conservation_status, image_url, sound_url, video_url, fun_fact, feeding_time, show_schedule ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `); animals.forEach(animal => { stmt.run([ animal.animal_id, animal.name, animal.scientific_name, animal.type, animal.habitat, animal.diet, animal.description, animal.size, animal.lifespan, animal.conservation_status, animal.image_url, animal.sound_url, animal.video_url, animal.fun_fact, animal.feeding_time, animal.show_schedule ]); }); stmt.finalize(() => { console.log('Sample animals inserted successfully'); db.close(); }); }