// Класс Table для управления таблицами
class Table {
constructor(name, schema, autoIncrement = false) {
this.name = name;
this.schema = schema; // Объект с типами, например: { id: 'number', name: 'string' }
this.autoIncrement = autoIncrement; // Флаг автоинкремента для 'id'
this.autoIncrementValue = 1; // Начальное значение для автоинкремента
// Инициализация колонок
this.columns = {};
for (let field in schema) {
if (schema[field] === 'number') {
this.columns[field] = []; // Массив чисел
} else {
this.columns[field] = []; // Массив строк
}
}
}
// Метод для вставки записи
insert(record) {
// Если автоинкремент включен, генерируем id
if (this.autoIncrement) {
record.id = this.autoIncrementValue++;
} else {
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) {
if (this.autoIncrement && field === 'id') {
// Уже установили значение id
this.columns[field].push(record[field]);
} else {
this.columns[field].push(
record[field] !== undefined ? record[field] : (this.schema[field] === 'number' ? 0 : '')
);
}
}
}
// Метод для удаления записи по id
deleteRecord(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
updateRecord(id, newRecord) {
const ids = this.columns['id'];
const index = ids.indexOf(id);
if (index !== -1) {
for (let field in newRecord) {
if (this.schema[field]) {
if (field === 'id' && this.autoIncrement) {
// Не разрешаем изменять auto-increment id вручную
continue;
}
this.columns[field][index] = newRecord[field];
}
}
return true;
}
return false;
}
// Метод для получения записи по id с использованием GPU
getGPU(id) {
// Преобразуем колонки в массивы чисел или строк
const recordLength = this.columns['id'].length;
const ids = this.columns['id'];
// Создаем TypedArray для id, если они числа
let idArray;
if (this.schema['id'] === 'number') {
idArray = new Float32Array(ids);
} else {
// Для строк GPU.js не поддерживает, поэтому ограничимся числовым id
throw new Error('GPU-поиск поддерживается только для числовых id.');
}
// Создаем 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;
Assistant
}
getRecord(id) {
return this.getGPU(id);
// Или использовать CPU метод:
// return this.getCPU(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;
}
// Использование CPU для получения записи по id
getCPU(id) {
const index = this.columns['id'].indexOf(id);
if (index === -1) return null;
const record = {};
for (let field in this.columns) {
record[field] = this.columns[field][index];
}
return record;
}
// Добавление новой колонки
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.tables = new Map();
this.filePath = filePath; // Сохраняем путь к файлу
}
createTable(tableName, schema, autoIncrement = false) {
if (this.tables.has(tableName)) {
throw new Error(Таблица "${tableName}" уже существует.);
}
const table = new Table(tableName, schema, autoIncrement);
// Если автоинкремент включен, устанавливаем начальное значение
if (autoIncrement) {
const ids = table.columns['id'];
if (ids.length > 0) {
table.autoIncrementValue = Math.max(...ids) + 1;
} else {
table.autoIncrementValue = 1;
}
}
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(); // Сохранение после вставки записи
}
deleteRecord(tableName, id) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
const result = table.deleteRecord(id);
if (result) {
this.saveToFile(); // Сохранение после удаления записи
}
return result;
}
updateRecord(tableName, id, newRecord) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
const result = table.updateRecord(id, newRecord);
if (result) {
this.saveToFile(); // Сохранение после обновления записи
}
return result;
}
getRecord(tableName, id) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
return table.getRecord(id);
}
getAll(tableName) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
return table.getAll();
}
getTableSchema(tableName) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
return table.schema;
}
getTableAutoIncrement(tableName) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
return table.autoIncrement;
}
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,
autoIncrement: table.autoIncrement,
autoIncrementValue: table.autoIncrementValue
};
});
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, tableData.autoIncrement);
for (let field in tableData.columns) {
table.columns[field] = tableData.columns[field];
}
table.autoIncrementValue = tableData.autoIncrementValue || 1;
this.tables.set(tableName, table);
}
console.log(Данные загружены из ${this.filePath});
} else {
console.log(Файл ${this.filePath} не найден. Начинается с пустой базы данных.);
}
}
// Метод для выполнения SQL-подобной команды
executeSQLCommand(command) {
const parsed = parseSQL(command);
if (!parsed) {
throw new Error('Некорректная команда.');
}
const { type, tableName, fields, values, where, order } = parsed;
switch (type.toUpperCase()) {
case 'SELECT':
return this.selectQuery(tableName, fields, where, order);
case 'INSERT':
return this.insertQuery(tableName, values);
case 'UPDATE':
return this.updateQuery(tableName, fields, where);
case 'DELETE':
return this.deleteQuery(tableName, where);
default:
throw new Error(`Неизвестный тип команды "${type}".`);
}
}
// Методы для поддержки SQL-команд
selectQuery(tableName, selectedFields = ['*'], where = null, order = null) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
let records = table.getAll();
// Применение WHERE
if (where) {
records = records.filter(record => evaluateWhere(record, where));
}
// Применение ORDER BY
if (order) {
const { field, direction } = order;
if (!table.schema[field]) {
throw new Error(`Поле "${field}" не найдено в таблице "${tableName}".`);
}
records.sort((a, b) => {
if (a[field] < b[field]) return direction === 'ASC' ? -1 : 1;
if (a[field] > b[field]) return direction === 'ASC' ? 1 : -1;
return 0;
});
}
// Выбор полей
if (!(selectedFields.length === 1 && selectedFields[0] === '*')) {
records = records.map(record => {
const selected = {};
selectedFields.forEach(field => {
if (!table.schema[field]) {
throw new Error(`Поле "${field}" не найдено в таблице "${tableName}".`);
}
selected[field] = record[field];
});
return selected;
});
}
return records;
}
insertQuery(tableName, record) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
// Проверка на наличие обязательных полей
for (let field in table.schema) {
if (table.schema[field] === 'number' && (record[field] === undefined || record[field] === null)) {
if (field === 'id' && table.autoIncrement) continue; // Автоинкремент
throw new Error(`Необходимо предоставить значение для поля "${field}".`);
}
}
table.insert(record);
this.saveToFile();
// Возвращаем вставленную запись
const insertedId = table.autoIncrement ? table.autoIncrementValue - 1 : record.id;
const insertedRecord = table.getRecord(insertedId);
return insertedRecord;
}
updateQuery(tableName, updateFields, where = null) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
let records = table.getAll();
// Применение WHERE
if (where) {
records = records.filter(record => evaluateWhere(record, where));
}
records.forEach(record => {
table.updateRecord(record.id, updateFields);
});
this.saveToFile();
return { updated: records.length };
}
deleteQuery(tableName, where = null) {
const table = this.tables.get(tableName);
if (!table) {
throw new Error(Таблица "${tableName}" не найдена.);
}
let records = table.getAll();
// Применение WHERE
if (where) {
records = records.filter(record => evaluateWhere(record, where));
}
records.forEach(record => {
table.deleteRecord(record.id);
});
this.saveToFile();
return { deleted: records.length };
match = command.match(deleteRegex);
if (match) {
const tableName = match[1];
const where = match[2] ? parseWhere(match[2]) : null;
return { type: 'DELETE', tableName, where };
}
return null;
}
function parseWhere(whereClause) {
// Поддержка простых условий вида "field operator value"
const operators = ['>=', '<=', '!=', '=', '>', '<'];
for (let op of operators) {
const parts = whereClause.split(op);
if (parts.length === 2) {
const field = parts[0].trim();
let value = parts[1].trim();
if (value.startsWith('"') && value.endsWith('"')) {
value = value.slice(1, -1);
}
if (value.startsWith("'") && value.endsWith("'")) {
value = value.slice(1, -1);
}
if (!isNaN(Number(value))) {
value = Number(value);
}
return { field, operator: op, value };
}
}
return null;
}
function evaluateWhere(record, where) {
const { field, operator, value } = where;
const recordValue = record[field];
switch (operator) {
case '=':
return recordValue === value;
case '!=':
return recordValue !== value;
case '>':
return recordValue > value;
case '<':
return recordValue < value;
case '>=':
return recordValue >= value;
case '<=':
return recordValue <= value;
default:
return false;
}
}
// Страница создания новой таблицы
app.get('/create-table', (req, res) => {
const content = `
Создать Новую Таблицу
Название Таблицы
Поля таблицы
Выберите тип
Number
String
×
Добавить Колонку
Минимум одно поле должно быть "id: number".
Автоинкремент для поля "id"
Создать Таблицу
Отмена
// Обработка создания новой таблицы
app.post('/create-table', (req, res) => {
const { tableName, autoIncrement } = req.body;
// Получение массивов имен и типов колонок
let columnNames = req.body.columnNames;
let columnTypes = req.body.columnTypes;
// Обеспечение того, что columnNames и columnTypes являются массивами
if (!Array.isArray(columnNames)) {
columnNames = [columnNames];
}
if (!Array.isArray(columnTypes)) {
columnTypes = [columnTypes];
}
try {
// Парсинг колонок
const schema = {};
for (let i = 0; i < columnNames.length; i++) {
const name = columnNames[i].trim();
const type = columnTypes[i].trim().toLowerCase();
if (!name) {
throw new Error(`Имя колонки в строке ${i + 1} не может быть пустым.`);
}
if (!['number', 'string'].includes(type)) {
throw new Error(`Некорректный тип колонки "${name}" в строке ${i + 1}. Допустимые типы: number, string.`);
}
if (schema[name]) {
throw new Error(`Дублирующееся имя колонки: "${name}" в строке ${i + 1}.`);
}
schema[name] = type;
}
// Проверка наличия обязательной колонки 'id'
if (!schema.id) {
throw new Error('Необходимо указать колонку "id: number" в качестве уникального идентификатора.');
}
if (schema.id !== 'number') {
throw new Error('Колонка "id" должна быть типа "number".');
}
// Проверка на уникальность имен колонок
const uniqueColumns = new Set(Object.keys(schema));
if (uniqueColumns.size !== Object.keys(schema).length) {
throw new Error('Имена колонок должны быть уникальными.');
}
// Проверка автоинкремента: если включен, убедимся, что 'id' присутствует и числовой
const isAutoIncrement = autoIncrement === 'on';
db.createTable(tableName, schema, isAutoIncrement);
res.redirect('/');
// Страница добавления новой записи
app.get('/table/:tableName/add', (req, res) => {
const tableName = req.params.tableName;
try {
const schema = db.getTableSchema(tableName);
const autoIncrement = db.getTableAutoIncrement(tableName);
let formFields = '';
for (let field in schema) {
if (field === 'id' && autoIncrement) {
// Если автоинкремент, не отображаем поле id
continue;
}
formFields += <div class="form-group"> <label for="${field}">${field} (${schema[field]})</label> ${schema[field] === 'number' ?:} </div> ;
}
const content = <h1>Добавить Запись в Таблицу: ${tableName}</h1> <form action="/table/${encodeURIComponent(tableName)}/add" method="POST"> ${formFields} <button type="submit" class="btn btn-primary">Добавить Запись</button> <a href="/table/${encodeURIComponent(tableName)}" class="btn btn-secondary">Отмена</a> </form> ;
renderPage(res, Добавить Запись в ${tableName}, content);
} catch (error) {
const content = <div class="alert alert-danger" role="alert"> <h4 class="alert-heading">Ошибка</h4> <p>${error.message}</p> <hr> <a href="/" class="btn btn-primary">Назад</a> </div> ;
renderPage(res, 'Ошибка', content);
}
});
// Обработка добавления новой записи
app.post('/table/:tableName/add', (req, res) => {
const tableName = req.params.tableName;
const record = req.body;
try {
const schema = db.getTableSchema(tableName);
const autoIncrement = db.getTableAutoIncrement(tableName);
// Если автоинкремент для 'id', удаляем ручной ввод 'id' (если он был)
if (autoIncrement && record.id !== undefined) {
delete record.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.redirect(`/table/${encodeURIComponent(tableName)}`);
// Если автоинкремент для 'id', удаляем ручной ввод 'id' (если он был)
if (autoIncrement && newRecord.id !== undefined) {
delete newRecord.id;
}
// Преобразование типов полей
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.updateRecord(tableName, Number(id), newRecord);
if (!success) {
throw new Error(`Запись с id=${id} не найдена.`);
}
res.redirect(`/table/${encodeURIComponent(tableName)}`);
// Вспомогательная функция для экранирования HTML
function escapeHTML(str) {
if (typeof str !== 'string') return str;
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// -----------------------------------------------------------------------------------
// API-интерфейс (если требуется, можно оставить или удалить)
// -----------------------------------------------------------------------------------
// Здесь вы можете добавить или удалить API-интерфейс, предоставленный ранее.
// Для краткости, пример не включен, но его можно интегрировать аналогично предыдущим изменениям.
// -----------------------------------------------------------------------------------
// Завершение работы и сохранение данных
// -----------------------------------------------------------------------------------
// Запуск сервера
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);
});
});
Конечно! Улучшение интерфейса вашего веб-приложения может значительно повысить удобство использования и визуальную привлекательность. Рассмотрим шаги по улучшению интерфейса вашего приложения, добавив тени, анимации и различные визуальные эффекты.
1. Структурирование CSS
Для лучшей организации стилей рекомендуется переместить пользовательские стили в отдельный файл CSS. Это упростит управление стилями и обеспечит чистоту кода.
Шаги:
Создайте папку public/css (если она еще не существует).
Создайте файл styles.css внутри папки public/css.
2. Подключение Пользовательского CSS
Обновим функцию renderPage, чтобы подключить новый файл стилей и добавить необходимые библиотеки для анимаций, такие как Animate.css.
// Вставьте это в функцию renderPage внутри тега <head>
<link rel="stylesheet" href="/css/styles.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
3. Добавление Иконок
Использование иконок улучшит визуальную составляющую и повысит удобство интерфейса. Рекомендуется воспользоваться Font Awesome.
Шаги:
Добавьте ссылку на Font Awesome в <head> вашей HTML-страницы:
Адаптивность: Интерфейс адаптируется к различным размерам экрана, обеспечивая удобство использования на мобильных устройствах.
11. Дополнительные Рекомендации
Темы Bootstrap: Рассмотрите возможность использования альтернативных тем для Bootstrap, таких как Bootswatch, чтобы быстро изменить стиль вашего приложения.
Переход на Bootstrap 5: Если вы готовы обновить версию Bootstrap, Bootstrap 5 предлагает дополнительные компоненты и улучшенные стили, а также убрал зависимости от jQuery, что может упростить вашу кодовую базу.
Использование SASS: Для более продвинутого управления стилями можно интегрировать SASS в ваш проект, что позволит использовать переменные, миксины и другие возможности препроцессора.
Оптимизация Скорости Загрузки: Убедитесь, что вы используете минифицированные версии CSS и JS библиотек для ускорения загрузки страниц.
Заключение
Внедрение вышеописанных изменений значительно улучшит внешний вид вашего приложения, делая его более профессиональным и приятным для пользователей. Не забывайте тестировать интерфейс на различных устройствах и браузерах, чтобы обеспечить его корректную работу везде.
Если у вас возникнут дополнительные вопросы или потребуется помощь с конкретными аспектами, не стесняйтесь обращаться!