Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Исправь ошибки и напиши команду для утсановки всех библиотек // app.js const express =…

  1. User

    Исправь ошибки и напиши команду для утсановки всех библиотек // app.js const express = require('express'); const bodyParser = require('body-parser'); const fs = require('fs'); const path = require('path'); const { GPU } = require('gpu.js'); const { v4: uuidv4 } = require('uuid'); // Для генерации уникальных ID

    // Инициализация GPU.js const gpu = new GPU();

    // Класс Table для управления таблицами с колончатым хранением и GPU-поиском class Table { constructor(name, schema) { this.name = name; this.schema = schema; // Например: { id: 'number', name: 'string' } // Инициализация колонок this.columns = {}; for (let field in schema) { if (schema[field] === 'number') { this.columns[field] = []; } else { this.columns[field] = []; } } }

    // Метод для вставки записи insert(record) { if (record.id === undefined || record.id === null) { throw new Error('Поле "id" обязательно для вставки записи.'); } const id = record.id; const ids = this.columns['id']; if (ids.includes(id)) { throw new Error(Запись с id=${id} уже существует.); } for (let field in this.schema) { this.columns[field].push( record[field] !== undefined ? record[field] : this.schema[field] === 'number' ? 0 : '' ); } }

    // Метод для удаления записи по id delete(id) { const ids = this.columns['id']; const index = ids.indexOf(id); if (index !== -1) { for (let field in this.columns) { this.columns[field].splice(index, 1); } return true; } return false; }

    // Метод для обновления записи по id update(id, newRecord) { const ids = this.columns['id']; const index = ids.indexOf(id); if (index !== -1) { for (let field in newRecord) { if (this.schema[field]) { this.columns[field][index] = newRecord[field]; } } return true; } return false; }

    // Метод для получения записи по id с использованием GPU getGPU(id) { if (this.schema['id'] !== 'number') { throw new Error('GPU-поиск поддерживается только для числовых id.'); }

    const recordLength = this.columns['id'].length;
    const ids = this.columns['id'];
    
    // Создаем TypedArray для id, если они числа
    const idArray = new Float32Array(ids);
    
    // Создаем GPU Kernel для поиска индекса
    const findIndexGPU = gpu.createKernel(function (idArray, targetId) {
      let index = -1;
      for (let i = 0; i < this.constants.size; i++) {
        if (idArray[i] === targetId) {
          index = i;
          break;
        }
      }
      return index;
    })
      .setOutput([1])
      .setConstants({ size: recordLength });
    
    const index = findIndexGPU(idArray, id)[0];
    
    if (index === -1) return null;
    
    // Получение всей записи
    const record = {};
    for (let field in this.columns) {
      record[field] = this.columns[field][index];
    }
    return record;
    

    }

    get(id) { return this.getGPU(id); }

    getAll() { const recordLength = this.columns['id'].length; const records = []; for (let i = 0; i < recordLength; i++) { const record = {}; for (let field in this.columns) { record[field] = this.columns[field][i]; } records.push(record); } return records; }

    // Добавление новой колонки addColumn(columnName, columnType) { if (this.schema[columnName]) { throw new Error(Колонка "${columnName}" уже существует.); } if (!['number', 'string'].includes(columnType.toLowerCase())) { throw new Error('Поддерживаются только типы "number" и "string".'); } this.schema[columnName] = columnType.toLowerCase(); // Инициализируем новую колонку this.columns[columnName] = this.columns['id'].map(() => columnType.toLowerCase() === 'number' ? 0 : '' ); }

    // Удаление колонки deleteColumn(columnName) { if (!this.schema[columnName]) { throw new Error(Колонка "${columnName}" не найдена.); } if (columnName === 'id') { throw new Error('Невозможно удалить обязательную колонку "id".'); } delete this.schema[columnName]; delete this.columns[columnName]; } }

    // Класс Database для управления всеми таблицами с автоматическим сохранением class Database { constructor(filePath) { this.filePath = filePath; this.tables = new Map(); }

    createTable(tableName, schema) { if (this.tables.has(tableName)) { throw new Error(Таблица "${tableName}" уже существует.); } const table = new Table(tableName, schema); this.tables.set(tableName, table); this.saveToFile(); // Сохранение после создания таблицы }

    dropTable(tableName) { if (this.tables.delete(tableName)) { this.saveToFile(); // Сохранение после удаления таблицы return true; } return false; }

    insert(tableName, record) { const table = this.tables.get(tableName); if (!table) { throw new Error(Таблица "${tableName}" не найдена.); } table.insert(record); this.saveToFile(); // Сохранение после вставки }

    delete(tableName, id) { const table = this.tables.get(tableName); if (!table) { throw new Error(Таблица "${tableName}" не найдена.); } const success = table.delete(id); if (success) this.saveToFile(); // Сохранение после удаления return success; }

    update(tableName, id, newRecord) { const table = this.tables.get(tableName); if (!table) { throw new Error(Таблица "${tableName}" не найдена.); } const success = table.update(id, newRecord); if (success) this.saveToFile(); // Сохранение после обновления return success; }

    get(tableName, id) { const table = this.tables.get(tableName); if (!table) { throw new Error(Таблица "${tableName}" не найдена.); } return table.get(id); }

    getAll(tableName) { const table = this.tables.get(tableName); if (!table) { throw new Error(Таблица "${tableName}" не найдена.); } return table.getAll(); }

    getTables() { return Array.from(this.tables.keys()); }

    getTableSchema(tableName) { const table = this.tables.get(tableName); if (!table) { throw new Error(Таблица "${tableName}" не найдена.); } return table.schema; }

    addColumn(tableName, columnName, columnType) { const table = this.tables.get(tableName); if (!table) { throw new Error(Таблица "${tableName}" не найдена.); } table.addColumn(columnName, columnType); this.saveToFile(); // Сохранение после добавления колонки }

    deleteColumn(tableName, columnName) { const table = this.tables.get(tableName); if (!table) { throw new Error(Таблица "${tableName}" не найдена.); } table.deleteColumn(columnName); this.saveToFile(); // Сохранение после удаления колонки }

    // Сохранение базы данных в файл saveToFile() { const data = {}; this.tables.forEach((table, name) => { data[name] = { schema: table.schema, columns: table.columns, }; }); fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf8'); console.log(Данные сохранены в ${this.filePath}); }

    // Загрузка базы данных из файла loadFromFile() { if (fs.existsSync(this.filePath)) { const rawData = fs.readFileSync(this.filePath, 'utf8'); const data = JSON.parse(rawData); for (const tableName in data) { const tableData = data[tableName]; const table = new Table(tableName, tableData.schema); for (let field in tableData.columns) { table.columns[field] = tableData.columns[field]; } this.tables.set(tableName, table); } console.log(Данные загружены из ${this.filePath}); } else { console.log(Файл ${this.filePath} не найден. Начинается с пустой базы данных.); } } }

    // Инициализация приложения const app = express(); const PORT = 3000; const DATA_FILE = path.join(__dirname, 'database.json');

    // Инициализация базы данных const db = new Database(DATA_FILE); db.loadFromFile();

    // Настройка промежуточного ПО app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(express.static(path.join(__dirname, 'public')));

    // Использование EJS для шаблонов (устанавливаем ejs в качестве view engine) app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views'));

    // Установка папки для публичных файлов app.use('/public', express.static(path.join(__dirname, 'public')));

    // Функция для рендеринга HTML страниц с использованием EJS function renderPage(res, template, data = {}) { res.render(template, data); }

    // Главная страница - список таблиц app.get('/', (req, res) => { const tables = db.getTables(); renderPage(res, 'index', { tables }); });

    // Страница создания новой таблицы app.get('/create-table', (req, res) => { renderPage(res, 'create-table'); });

    // Обработка создания новой таблицы app.post('/create-table', (req, res) => { const { tableName, fields } = req.body; try { // Парсинг полей (например, "id:number,name:string,age:number") const schema = {}; fields.split(',').forEach(field => { const [name, type] = field.trim().split(':'); if (!name || !type) { throw new Error('Некорректный формат полей. Используйте формат "имя:тип", разделённый запятыми.'); } if (!['number', 'string'].includes(type.toLowerCase())) { throw new Error('Поддерживаются только типы "number" и "string".'); } schema[name] = type.toLowerCase(); }); if (!schema.id) { throw new Error('Необходимо указать поле "id:number" в качестве уникального идентификатора.'); } db.createTable(tableName, schema); res.json({ success: true, message: Таблица "${tableName}" успешно создана. }); } catch (error) { res.json({ success: false, message: error.message }); } });

    // Страница управления структурой таблицы app.get('/table/:tableName/manage-schema', (req, res) => { const tableName = req.params.tableName; try { const schema = db.getTableSchema(tableName); renderPage(res, 'manage-schema', { tableName, schema }); } catch (error) { res.status(400).send(Ошибка: ${error.message}); } });

    // Обработка добавления новой колонки app.post('/table/:tableName/add-column', (req, res) => { const tableName = req.params.tableName; const { columnName, columnType } = req.body; try { db.addColumn(tableName, columnName, columnType); res.json({ success: true, message: Колонка "${columnName}" успешно добавлена. }); } catch (error) { res.json({ success: false, message: error.message }); } });

    // Обработка удаления колонки app.post('/table/:tableName/delete-column', (req, res) => { const tableName = req.params.tableName; const { columnName } = req.body; try { db.deleteColumn(tableName, columnName); res.json({ success: true, message: Колонка "${columnName}" успешно удалена. }); } catch (error) { res.json({ success: false, message: error.message }); } });

    // API для получения данных таблицы с поддержкой поиска, сортировки и пагинации app.get('/api/table/:tableName', (req, res) => { const tableName = req.params.tableName; const { search, sortField, sortOrder, page, limit } = req.query; try { let records = db.getAll(tableName); const schema = db.getTableSchema(tableName);

    // Поиск
    if (search) {
      const searchLower = search.toLowerCase();
      records = records.filter(record =>
        Object.values(record).some(value =>
          String(value).toLowerCase().includes(searchLower)
        )
      );
    }
    
    // Сортировка
    if (sortField) {
      records.sort((a, b) => {
        if (a[sortField] < b[sortField]) return sortOrder === 'asc' ? -1 : 1;
        if (a[sortField] > b[sortField]) return sortOrder === 'asc' ? 1 : -1;
        return 0;
      });
    }
    
    // Пагинация
    const total = records.length;
    const currentPage = parseInt(page) || 1;
    const perPage = parseInt(limit) || 10;
    const totalPages = Math.ceil(total / perPage);
    const paginatedRecords = records.slice(
      (currentPage - 1) * perPage,
      currentPage * perPage
    );
    
    res.json({
      success: true,
      data: paginatedRecords,
      pagination: {
        total,
        currentPage,
        totalPages,
        perPage,
      },
    });
    

    } catch (error) { res.json({ success: false, message: error.message }); } });

    // Страница отображения таблицы и её записей app.get('/table/:tableName', (req, res) => { const tableName = req.params.tableName; try { const schema = db.getTableSchema(tableName); renderPage(res, 'table', { tableName, schema }); } catch (error) { res.status(400).send(Ошибка: ${error.message}); } });

    // API для добавления новой записи app.post('/api/table/:tableName/add', (req, res) => { const tableName = req.params.tableName; const record = req.body; try { const schema = db.getTableSchema(tableName); // Генерация уникального ID, если id поле типов number if (schema.id === 'number') { record.id = Date.now(); // Простой способ генерации уникального числа } else { record.id = uuidv4(); // Используем UUID для строковых ID }

    // Преобразование типов полей
    for (const field in record) {
      if (schema[field] === 'number') {
        record[field] = Number(record[field]);
        if (isNaN(record[field])) {
          throw new Error(`Поле "${field}" должно быть числом.`);
        }
      }
    }
    
    db.insert(tableName, record);
    res.json({ success: true, message: 'Запись успешно добавлена.' });
    

    } catch (error) { res.json({ success: false, message: error.message }); } });

    // API для редактирования записи app.post('/api/table/:tableName/edit/:id', (req, res) => { const tableName = req.params.tableName; const id = req.params.id; const newRecord = req.body; try { const schema = db.getTableSchema(tableName);

    // Преобразование типов полей
    for (const field in newRecord) {
      if (schema[field] === 'number') {
        newRecord[field] = Number(newRecord[field]);
        if (isNaN(newRecord[field])) {
          throw new Error(`Поле "${field}" должно быть числом.`);
        }
      }
    }
    
    const success = db.update(tableName, schema.id === 'number' ? Number(id) : id, newRecord);
    if (!success) {
      throw new Error(`Запись с id=${id} не найдена.`);
    }
    res.json({ success: true, message: 'Запись успешно обновлена.' });
    

    } catch (error) { res.json({ success: false, message: error.message }); } });

    // API для удаления записи app.post('/api/table/:tableName/delete/:id', (req, res) => { const tableName = req.params.tableName; const id = req.params.id; try { const schema = db.getTableSchema(tableName); const success = db.delete(tableName, schema.id === 'number' ? Number(id) : id); if (!success) { throw new Error(Запись с id=${id} не найдена.); } res.json({ success: true, message: 'Запись успешно удалена.' }); } catch (error) { res.json({ success: false, message: error.message }); } });

    // Обработка удаления таблицы app.post('/api/drop-table/:tableName', (req, res) => { const tableName = req.params.tableName; try { db.dropTable(tableName); res.json({ success: true, message: Таблица "${tableName}" успешно удалена. }); } catch (error) { res.json({ success: false, message: error.message }); } });

    // Запуск сервера const server = app.listen(PORT, () => { console.log(Сервер запущен на http://localhost:${PORT}); });

    // Обработка завершения работы для сохранения данных process.on('SIGINT', () => { console.log('\nЗавершение работы...'); db.saveToFile(); server.close(() => { console.log('Сервер остановлен.'); process.exit(0); }); });

  2. Assistant

    Ваш код в целом выглядит хорошо, однако есть несколько моментов, которые можно улучшить:

    1. Упрощение конструктора класса Table:

      В конструкторе класса Table у вас есть проверка типа поля, но в обоих случаях инициализируются пустые массивы. Это условие можно убрать, так как действие одинаково независимо от типа.

    2. Оптимизация использования express.static:

      Вы дважды используете express.static для папки public. Это избыточно и может привести к путанице. Рекомендуется оставить только один из них.

    3. Современные версии Express:

      Начиная с версии 4.16, body-parser уже встроен в Express. Однако использование его как отдельного пакета всё ещё допустимо.

    4. Обработка типов ID:

      Убедитесь, что конвертация id в число происходит корректно там, где это необходимо.

    Ниже представлен исправленный код с учетом вышеуказанных замечаний:

    // app.js
    const express = require('express');
    const bodyParser = require('body-parser');
    const fs = require('fs');
    const path = require('path');
    const { GPU } = require('gpu.js');
    const { v4: uuidv4 } = require('uuid'); // Для генерации уникальных ID
    
    // Инициализация GPU.js
    const gpu = new GPU();
    
    // Класс Table для управления таблицами с колончатым хранением и GPU-поиском
    class Table {
      constructor(name, schema) {
        this.name = name;
        this.schema = schema; // Например: { id: 'number', name: 'string' }
        // Инициализация колонок
        this.columns = {};
        for (let field in schema) {
          this.columns[field] = [];
        }
      }
    
      // Метод для вставки записи
      insert(record) {
        if (record.id === undefined || record.id === null) {
          throw new Error('Поле "id" обязательно для вставки записи.');
        }
        const id = record.id;
        const ids = this.columns['id'];
        if (ids.includes(id)) {
          throw new Error(`Запись с id=${id} уже существует.`);
        }
        for (let field in this.schema) {
          this.columns[field].push(
            record[field] !== undefined
              ? record[field]
              : this.schema[field] === 'number'
              ? 0
              : ''
          );
        }
      }
    
      // Метод для удаления записи по id
      delete(id) {
        const ids = this.columns['id'];
        const index = ids.indexOf(id);
        if (index !== -1) {
          for (let field in this.columns) {
            this.columns[field].splice(index, 1);
          }
          return true;
        }
        return false;
      }
    
      // Метод для обновления записи по id
      update(id, newRecord) {
        const ids = this.columns['id'];
        const index = ids.indexOf(id);
        if (index !== -1) {
          for (let field in newRecord) {
            if (this.schema[field]) {
              this.columns[field][index] = newRecord[field];
            }
          }
          return true;
        }
        return false;
      }
    
      // Метод для получения записи по id с использованием GPU
      getGPU(id) {
        if (this.schema['id'] !== 'number') {
          throw new Error('GPU-поиск поддерживается только для числовых id.');
        }
    
        const recordLength = this.columns['id'].length;
        const ids = this.columns['id'];
    
        // Создаем TypedArray для id, если они числа
        const idArray = new Float32Array(ids);
    
        // Создаем GPU Kernel для поиска индекса
        const findIndexGPU = gpu.createKernel(function (idArray, targetId) {
          let index = -1;
          for (let i = 0; i < this.constants.size; i++) {
            if (idArray[i] === targetId) {
              index = i;
              break;
            }
          }
          return index;
        })
          .setOutput([1])
          .setConstants({ size: recordLength });
    
        const index = findIndexGPU(idArray, id)[0];
    
        if (index === -1) return null;
    
        // Получение всей записи
        const record = {};
        for (let field in this.columns) {
          record[field] = this.columns[field][index];
        }
        return record;
      }
    
      get(id) {
        return this.getGPU(id);
      }
    
      getAll() {
        const recordLength = this.columns['id'].length;
        const records = [];
        for (let i = 0; i < recordLength; i++) {
          const record = {};
          for (let field in this.columns) {
            record[field] = this.columns[field][i];
          }
          records.push(record);
        }
        return records;
      }
    
      // Добавление новой колонки
      addColumn(columnName, columnType) {
        if (this.schema[columnName]) {
          throw new Error(`Колонка "${columnName}" уже существует.`);
        }
        if (!['number', 'string'].includes(columnType.toLowerCase())) {
          throw new Error('Поддерживаются только типы "number" и "string".');
        }
        this.schema[columnName] = columnType.toLowerCase();
        // Инициализируем новую колонку
        this.columns[columnName] = this.columns['id'].map(() =>
          columnType.toLowerCase() === 'number' ? 0 : ''
        );
      }
    
      // Удаление колонки
      deleteColumn(columnName) {
        if (!this.schema[columnName]) {
          throw new Error(`Колонка "${columnName}" не найдена.`);
        }
        if (columnName === 'id') {
          throw new Error('Невозможно удалить обязательную колонку "id".');
        }
        delete this.schema[columnName];
        delete this.columns[columnName];
      }
    }
    
    // Класс Database для управления всеми таблицами с автоматическим сохранением
    class Database {
      constructor(filePath) {
        this.filePath = filePath;
        this.tables = new Map();
      }
    
      createTable(tableName, schema) {
        if (this.tables.has(tableName)) {
          throw new Error(`Таблица "${tableName}" уже существует.`);
        }
        const table = new Table(tableName, schema);
        this.tables.set(tableName, table);
        this.saveToFile(); // Сохранение после создания таблицы
      }
    
      dropTable(tableName) {
        if (this.tables.delete(tableName)) {
          this.saveToFile(); // Сохранение после удаления таблицы
          return true;
        }
        return false;
      }
    
      insert(tableName, record) {
        const table = this.tables.get(tableName);
        if (!table) {
          throw new Error(`Таблица "${tableName}" не найдена.`);
        }
        table.insert(record);
        this.saveToFile(); // Сохранение после вставки
      }
    
      delete(tableName, id) {
        const table = this.tables.get(tableName);
        if (!table) {
          throw new Error(`Таблица "${tableName}" не найдена.`);
        }
        const success = table.delete(id);
        if (success) this.saveToFile(); // Сохранение после удаления
        return success;
      }
    
      update(tableName, id, newRecord) {
        const table = this.tables.get(tableName);
        if (!table) {
          throw new Error(`Таблица "${tableName}" не найдена.`);
        }
        const success = table.update(id, newRecord);
        if (success) this.saveToFile(); // Сохранение после обновления
        return success;
      }
    
      get(tableName, id) {
        const table = this.tables.get(tableName);
        if (!table) {
          throw new Error(`Таблица "${tableName}" не найдена.`);
        }
        return table.get(id);
      }
    
      getAll(tableName) {
        const table = this.tables.get(tableName);
        if (!table) {
          throw new Error(`Таблица "${tableName}" не найдена.`);
        }
        return table.getAll();
      }
    
      getTables() {
        return Array.from(this.tables.keys());
      }
    
      getTableSchema(tableName) {
        const table = this.tables.get(tableName);
        if (!table) {
          throw new Error(`Таблица "${tableName}" не найдена.`);
        }
        return table.schema;
      }
    
      addColumn(tableName, columnName, columnType) {
        const table = this.tables.get(tableName);
        if (!table) {
          throw new Error(`Таблица "${tableName}" не найдена.`);
        }
        table.addColumn(columnName, columnType);
        this.saveToFile(); // Сохранение после добавления колонки
      }
    
      deleteColumn(tableName, columnName) {
        const table = this.tables.get(tableName);
        if (!table) {
          throw new Error(`Таблица "${tableName}" не найдена.`);
        }
        table.deleteColumn(columnName);
        this.saveToFile(); // Сохранение после удаления колонки
      }
    
      // Сохранение базы данных в файл
      saveToFile() {
        const data = {};
        this.tables.forEach((table, name) => {
          data[name] = {
            schema: table.schema,
            columns: table.columns,
          };
        });
        fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf8');
        console.log(`Данные сохранены в ${this.filePath}`);
      }
    
      // Загрузка базы данных из файла
      loadFromFile() {
        if (fs.existsSync(this.filePath)) {
          const rawData = fs.readFileSync(this.filePath, 'utf8');
          const data = JSON.parse(rawData);
          for (const tableName in data) {
            const tableData = data[tableName];
            const table = new Table(tableName, tableData.schema);
            for (let field in tableData.columns) {
              table.columns[field] = tableData.columns[field];
            }
            this.tables.set(tableName, table);
          }
          console.log(`Данные загружены из ${this.filePath}`);
        } else {
          console.log(`Файл ${this.filePath} не найден. Начинается с пустой базы данных.`);
        }
      }
    }
    
    // Инициализация приложения
    const app = express();
    const PORT = 3000;
    const DATA_FILE = path.join(__dirname, 'database.json');
    
    // Инициализация базы данных
    const db = new Database(DATA_FILE);
    db.loadFromFile();
    
    // Настройка промежуточного ПО
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(express.static(path.join(__dirname, 'public')));
    
    // Использование EJS для шаблонов (устанавливаем ejs в качестве view engine)
    app.set('view engine', 'ejs');
    app.set('views', path.join(__dirname, 'views'));
    
    // Функция для рендеринга HTML страниц с использованием EJS
    function renderPage(res, template, data = {}) {
      res.render(template, data);
    }
    
    // Главная страница - список таблиц
    app.get('/', (req, res) => {
      const tables = db.getTables();
      renderPage(res, 'index', { tables });
    });
    
    // Страница создания новой таблицы
    app.get('/create-table', (req, res) => {
      renderPage(res, 'create-table');
    });
    
    // Обработка создания новой таблицы
    app.post('/create-table', (req, res) => {
      const { tableName, fields } = req.body;
      try {
        // Парсинг полей (например, "id:number,name:string,age:number")
        const schema = {};
        fields.split(',').forEach(field => {
          const [name, type] = field.trim().split(':');
          if (!name || !type) {
            throw new Error('Некорректный формат полей. Используйте формат "имя:тип", разделённый запятыми.');
          }
          if (!['number', 'string'].includes(type.toLowerCase())) {
            throw new Error('Поддерживаются только типы "number" и "string".');
          }
          schema[name] = type.toLowerCase();
        });
        if (!schema.id) {
          throw new Error('Необходимо указать поле "id:number" в качестве уникального идентификатора.');
        }
        db.createTable(tableName, schema);
        res.json({ success: true, message: `Таблица "${tableName}" успешно создана.` });
      } catch (error) {
        res.json({ success: false, message: error.message });
      }
    });
    
    // Страница управления структурой таблицы
    app.get('/table/:tableName/manage-schema', (req, res) => {
      const tableName = req.params.tableName;
      try {
        const schema = db.getTableSchema(tableName);
        renderPage(res, 'manage-schema', { tableName, schema });
      } catch (error) {
        res.status(400).send(`Ошибка: ${error.message}`);
      }
    });
    
    // Обработка добавления новой колонки
    app.post('/table/:tableName/add-column', (req, res) => {
      const tableName = req.params.tableName;
      const { columnName, columnType } = req.body;
      try {
        db.addColumn(tableName, columnName, columnType);
        res.json({ success: true, message: `Колонка "${columnName}" успешно добавлена.` });
      } catch (error) {
        res.json({ success: false, message: error.message });
      }
    });
    
    // Обработка удаления колонки
    app.post('/table/:tableName/delete-column', (req, res) => {
      const tableName = req.params.tableName;
      const { columnName } = req.body;
      try {
        db.deleteColumn(tableName, columnName);
        res.json({ success: true, message: `Колонка "${columnName}" успешно удалена.` });
      } catch (error) {
        res.json({ success: false, message: error.message });
      }
    });
    
    // API для получения данных таблицы с поддержкой поиска, сортировки и пагинации
    app.get('/api/table/:tableName', (req, res) => {
      const tableName = req.params.tableName;
      const { search, sortField, sortOrder, page, limit } = req.query;
      try {
        let records = db.getAll(tableName);
        const schema = db.getTableSchema(tableName);
    
        // Поиск
        if (search) {
          const searchLower = search.toLowerCase();
          records = records.filter(record =>
            Object.values(record).some(value =>
              String(value).toLowerCase().includes(searchLower)
            )
          );
        }
    
        // Сортировка
        if (sortField) {
          records.sort((a, b) => {
            if (a[sortField] < b[sortField]) return sortOrder === 'asc' ? -1 : 1;
            if (a[sortField] > b[sortField]) return sortOrder === 'asc' ? 1 : -1;
            return 0;
          });
        }
    
        // Пагинация
        const total = records.length;
        const currentPage = parseInt(page) || 1;
        const perPage = parseInt(limit) || 10;
        const totalPages = Math.ceil(total / perPage);
        const paginatedRecords = records.slice(
          (currentPage - 1) * perPage,
          currentPage * perPage
        );
    
        res.json({
          success: true,
          data: paginatedRecords,
          pagination: {
            total,
            currentPage,
            totalPages,
            perPage,
          },
        });
      } catch (error) {
        res.json({ success: false, message: error.message });
      }
    });
    
    // Страница отображения таблицы и её записей
    app.get('/table/:tableName', (req, res) => {
      const tableName = req.params.tableName;
      try {
        const schema = db.getTableSchema(tableName);
        renderPage(res, 'table', { tableName, schema });
      } catch (error) {
        res.status(400).send(`Ошибка: ${error.message}`);
      }
    });
    
    // API для добавления новой записи
    app.post('/api/table/:tableName/add', (req, res) => {
      const tableName = req.params.tableName;
      const record = req.body;
      try {
        const schema = db.getTableSchema(tableName);
        // Генерация уникального ID, если id поле типов number
        if (schema.id === 'number') {
          record.id = Date.now(); // Простой способ генерации уникального числа
        } else {
          record.id = uuidv4(); // Используем UUID для строковых ID
        }
    
        // Преобразование типов полей
        for (const field in record) {
          if (schema[field] === 'number') {
            record[field] = Number(record[field]);
            if (isNaN(record[field])) {
              throw new Error(`Поле "${field}" должно быть числом.`);
            }
          }
        }
    
        db.insert(tableName, record);
        res.json({ success: true, message: 'Запись успешно добавлена.' });
      } catch (error) {
        res.json({ success: false, message: error.message });
      }
    });
    
    // API для редактирования записи
    app.post('/api/table/:tableName/edit/:id', (req, res) => {
      const tableName = req.params.tableName;
      const id = req.params.id;
      const newRecord = req.body;
      try {
        const schema = db.getTableSchema(tableName);
    
        // Преобразование типов полей
        for (const field in newRecord) {
          if (schema[field] === 'number') {
            newRecord[field] = Number(newRecord[field]);
            if (isNaN(newRecord[field])) {
              throw new Error(`Поле "${field}" должно быть числом.`);
            }
          }
        }
    
        const success = db.update(tableName, schema.id === 'number' ? Number(id) : id, newRecord);
        if (!success) {
          throw new Error(`Запись с id=${id} не найдена.`);
        }
        res.json({ success: true, message: 'Запись успешно обновлена.' });
      } catch (error) {
        res.json({ success: false, message: error.message });
      }
    });
    
    // API для удаления записи
    app.post('/api/table/:tableName/delete/:id', (req, res) => {
      const tableName = req.params.tableName;
      const id = req.params.id;
      try {
        const schema = db.getTableSchema(tableName);
        const success = db.delete(tableName, schema.id === 'number' ? Number(id) : id);
        if (!success) {
          throw new Error(`Запись с id=${id} не найдена.`);
        }
        res.json({ success: true, message: 'Запись успешно удалена.' });
      } catch (error) {
        res.json({ success: false, message: error.message });
      }
    });
    
    // Обработка удаления таблицы
    app.post('/api/drop-table/:tableName', (req, res) => {
      const tableName = req.params.tableName;
      try {
        db.dropTable(tableName);
        res.json({ success: true, message: `Таблица "${tableName}" успешно удалена.` });
      } catch (error) {
        res.json({ success: false, message: error.message });
      }
    });
    
    // Запуск сервера
    const server = app.listen(PORT, () => {
      console.log(`Сервер запущен на http://localhost:${PORT}`);
    });
    
    // Обработка завершения работы для сохранения данных
    process.on('SIGINT', () => {
      console.log('\nЗавершение работы...');
      db.saveToFile();
      server.close(() => {
        console.log('Сервер остановлен.');
        process.exit(0);
      });
    });
    

    Команда для установки всех необходимых библиотек

    В вашем проекте используются следующие зависимости:

    • express — веб-фреймворк для Node.js
    • body-parser — middleware для разбора тела запросов
    • gpu.js — библиотека для использования GPU в JavaScript
    • uuid — генерация уникальных идентификаторов
    • ejs — шаблонизатор для генерации HTML

    Чтобы установить все эти библиотеки, выполните следующую команду в корневой директории вашего проекта:

    npm install express body-parser gpu.js uuid ejs
    

    Дополнительные рекомендации

    1. Инициализация package.json:

      Если вы еще не инициализировали package.json в вашем проекте, рекомендуется это сделать. Это позволит управлять зависимостями и скриптами проекта.

      npm init -y
      
    2. Использование npm start:

      Добавьте скрипт запуска сервера в ваш package.json для удобства. Например:

      "scripts": {
        "start": "node app.js"
      }
      

      После этого вы сможете запускать сервер командой:

      npm start
      
    3. Установка nodemon для разработки:

      nodemon автоматически перезапускает сервер при изменении файлов, что удобно во время разработки.

      Установка глобально:

      npm install -g nodemon
      

      Или как зависимость для разработки:

      npm install --save-dev nodemon
      

      Затем обновите скрипт в package.json:

      "scripts": {
        "start": "nodemon app.js"
      }
      
    4. Структура проекта:

      Убедитесь, что у вас есть папки views и public в корневой директории проекта, так как они используются в коде для хранения шаблонов EJS и статических файлов соответственно.

    5. Проверка работы приложения:

      После установки всех зависимостей и настройки проекта, запустите сервер:

      npm start
      

      Откройте браузер и перейдите по адресу http://localhost:3000, чтобы убедиться, что приложение работает корректно.

    Если возникнут дополнительные вопросы или ошибки при запуске, пожалуйста, предоставьте подробную информацию, чтобы можно было помочь более конкретно.