ваше сообщение коммита
This commit is contained in:
190
backend/scripts/deploy/create-dle-v2.js
Normal file
190
backend/scripts/deploy/create-dle-v2.js
Normal file
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* Copyright (c) 2024-2025 Тарабанов Александр Викторович
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is proprietary and confidential.
|
||||
* Unauthorized copying, modification, or distribution is prohibited.
|
||||
*
|
||||
* For licensing inquiries: info@hb3-accelerator.com
|
||||
* Website: https://hb3-accelerator.com
|
||||
* GitHub: https://github.com/HB3-ACCELERATOR
|
||||
*/
|
||||
|
||||
// Скрипт для создания современного DLE v2 (единый контракт)
|
||||
const { ethers } = require("hardhat");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
async function main() {
|
||||
// Получаем параметры деплоя из файла
|
||||
const deployParams = getDeployParams();
|
||||
|
||||
console.log("Начинаем создание современного DLE v2...");
|
||||
console.log("Параметры DLE:");
|
||||
console.log(JSON.stringify(deployParams, null, 2));
|
||||
|
||||
// Получаем аккаунт деплоя
|
||||
const [deployer] = await ethers.getSigners();
|
||||
console.log(`Адрес деплоера: ${deployer.address}`);
|
||||
console.log(`Баланс деплоера: ${ethers.formatEther(await deployer.provider.getBalance(deployer.address))} ETH`);
|
||||
|
||||
try {
|
||||
// 1. Создаем единый контракт DLE
|
||||
console.log("\n1. Деплой единого контракта DLE v2...");
|
||||
|
||||
const DLE = await ethers.getContractFactory("DLE");
|
||||
|
||||
// Преобразуем параметры голосования
|
||||
const votingDelay = deployParams.votingDelay || 1;
|
||||
const votingPeriod = deployParams.votingPeriod || 45818; // ~1 неделя
|
||||
const proposalThreshold = deployParams.proposalThreshold || ethers.parseEther("100000");
|
||||
const quorumPercentage = deployParams.quorumPercentage || 4;
|
||||
const minTimelockDelay = (deployParams.minTimelockDelay || 2) * 24 * 60 * 60; // дни в секунды
|
||||
|
||||
const dle = await DLE.deploy(
|
||||
deployParams.name,
|
||||
deployParams.symbol,
|
||||
deployParams.location,
|
||||
deployParams.isicCodes || [],
|
||||
votingDelay,
|
||||
votingPeriod,
|
||||
proposalThreshold,
|
||||
quorumPercentage,
|
||||
minTimelockDelay
|
||||
);
|
||||
|
||||
await dle.waitForDeployment();
|
||||
const dleAddress = await dle.getAddress();
|
||||
console.log(`DLE v2 задеплоен по адресу: ${dleAddress}`);
|
||||
|
||||
// 2. Получаем адрес таймлока
|
||||
const timelockAddress = await dle.getTimelockAddress();
|
||||
console.log(`Таймлок создан по адресу: ${timelockAddress}`);
|
||||
|
||||
// 3. Распределяем начальные токены
|
||||
console.log("\n3. Распределение начальных токенов...");
|
||||
const distributeTx = await dle.distributeInitialTokens(
|
||||
deployParams.partners,
|
||||
deployParams.amounts
|
||||
);
|
||||
await distributeTx.wait();
|
||||
console.log(`Токены распределены между партнерами`);
|
||||
|
||||
// 4. Получаем информацию о DLE
|
||||
const dleInfo = await dle.getDLEInfo();
|
||||
console.log("\n4. Информация о DLE:");
|
||||
console.log(`Название: ${dleInfo.name}`);
|
||||
console.log(`Символ: ${dleInfo.symbol}`);
|
||||
console.log(`Местонахождение: ${dleInfo.location}`);
|
||||
console.log(`Коды деятельности: ${dleInfo.isicCodes.join(', ')}`);
|
||||
console.log(`Дата создания: ${new Date(dleInfo.creationTimestamp * 1000).toISOString()}`);
|
||||
|
||||
// 5. Сохраняем информацию о созданном DLE
|
||||
console.log("\n5. Сохранение информации о DLE v2...");
|
||||
const dleData = {
|
||||
name: deployParams.name,
|
||||
symbol: deployParams.symbol,
|
||||
location: deployParams.location,
|
||||
isicCodes: deployParams.isicCodes || [],
|
||||
dleAddress: dleAddress,
|
||||
timelockAddress: timelockAddress,
|
||||
creationBlock: (await distributeTx.provider.getBlockNumber()),
|
||||
creationTimestamp: (await distributeTx.provider.getBlock()).timestamp,
|
||||
deployedManually: true,
|
||||
version: "v2",
|
||||
governanceSettings: {
|
||||
votingDelay: votingDelay,
|
||||
votingPeriod: votingPeriod,
|
||||
proposalThreshold: proposalThreshold.toString(),
|
||||
quorumPercentage: quorumPercentage,
|
||||
minTimelockDelay: deployParams.minTimelockDelay || 2
|
||||
}
|
||||
};
|
||||
|
||||
const saveResult = saveDLEData(dleData);
|
||||
|
||||
console.log("\nDLE v2 успешно создан!");
|
||||
console.log(`Адрес DLE: ${dleAddress}`);
|
||||
console.log(`Адрес таймлока: ${timelockAddress}`);
|
||||
console.log(`Версия: v2 (единый контракт)`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
dleAddress: dleAddress,
|
||||
timelockAddress: timelockAddress,
|
||||
data: dleData
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error("Ошибка при создании DLE v2:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Получаем параметры деплоя из файла
|
||||
function getDeployParams() {
|
||||
const paramsFile = path.join(__dirname, 'current-params.json');
|
||||
|
||||
if (!fs.existsSync(paramsFile)) {
|
||||
console.error(`Файл параметров не найден: ${paramsFile}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
const params = JSON.parse(fs.readFileSync(paramsFile, 'utf8'));
|
||||
console.log("Параметры загружены из файла");
|
||||
return params;
|
||||
} catch (error) {
|
||||
console.error("Ошибка при чтении файла параметров:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем информацию о созданном DLE
|
||||
function saveDLEData(dleData) {
|
||||
const dlesDir = path.join(__dirname, "../../contracts-data/dles");
|
||||
|
||||
// Проверяем существование директории и создаем при необходимости
|
||||
try {
|
||||
if (!fs.existsSync(dlesDir)) {
|
||||
console.log(`Директория ${dlesDir} не существует, создаю...`);
|
||||
fs.mkdirSync(dlesDir, { recursive: true });
|
||||
console.log(`Директория ${dlesDir} успешно создана`);
|
||||
}
|
||||
|
||||
// Проверяем права на запись, создавая временный файл
|
||||
const testFile = path.join(dlesDir, '.write-test');
|
||||
fs.writeFileSync(testFile, 'test');
|
||||
fs.unlinkSync(testFile);
|
||||
console.log(`Директория ${dlesDir} доступна для записи`);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`Ошибка при проверке директории ${dlesDir}:`, error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Создаем уникальное имя файла
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const fileName = `dle-v2-${timestamp}.json`;
|
||||
const filePath = path.join(dlesDir, fileName);
|
||||
|
||||
try {
|
||||
fs.writeFileSync(filePath, JSON.stringify(dleData, null, 2));
|
||||
console.log(`Информация о DLE сохранена в файл: ${fileName}`);
|
||||
return { success: true, filePath };
|
||||
} catch (error) {
|
||||
console.error(`Ошибка при сохранении файла ${filePath}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Запускаем скрипт
|
||||
main()
|
||||
.then(() => {
|
||||
console.log("Скрипт завершен успешно");
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Скрипт завершен с ошибкой:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
110
backend/scripts/fix-rag-columns.js
Normal file
110
backend/scripts/fix-rag-columns.js
Normal file
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Copyright (c) 2024-2025 Тарабанов Александр Викторович
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is proprietary and confidential.
|
||||
* Unauthorized copying, modification, or distribution is prohibited.
|
||||
*
|
||||
* For licensing inquiries: info@hb3-accelerator.com
|
||||
* Website: https://hb3-accelerator.com
|
||||
* GitHub: https://github.com/HB3-ACCELERATOR
|
||||
*/
|
||||
|
||||
const db = require('../db');
|
||||
|
||||
async function fixRagColumns() {
|
||||
console.log('🔧 Исправление purpose у колонок в RAG таблице...\n');
|
||||
|
||||
try {
|
||||
// Получаем ключ шифрования
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
let encryptionKey = 'default-key';
|
||||
|
||||
try {
|
||||
const keyPath = path.join(__dirname, '../ssl/keys/full_db_encryption.key');
|
||||
if (fs.existsSync(keyPath)) {
|
||||
encryptionKey = fs.readFileSync(keyPath, 'utf8').trim();
|
||||
}
|
||||
} catch (keyError) {
|
||||
console.error('Error reading encryption key:', keyError);
|
||||
}
|
||||
|
||||
// Получаем колонки таблицы RAG (ID 28)
|
||||
const columns = await db.getQuery()(
|
||||
'SELECT id, decrypt_text(name_encrypted, $1) as name FROM user_columns WHERE table_id = 28 ORDER BY id',
|
||||
[encryptionKey]
|
||||
);
|
||||
|
||||
console.log('Найденные колонки в таблице RAG:');
|
||||
columns.rows.forEach(col => {
|
||||
console.log(` ID: ${col.id}, Name: ${col.name}`);
|
||||
});
|
||||
|
||||
// Маппинг названий колонок на purpose
|
||||
const purposeMapping = {
|
||||
'Вопрос': 'question',
|
||||
'Ответ': 'answer',
|
||||
'Контекст теги': 'context',
|
||||
'Продукт теги': 'product',
|
||||
'Клиент теги': 'userTags'
|
||||
};
|
||||
|
||||
// Обновляем каждую колонку
|
||||
for (const col of columns.rows) {
|
||||
const purpose = purposeMapping[col.name];
|
||||
if (purpose) {
|
||||
console.log(`\nОбновляем колонку "${col.name}" (ID: ${col.id}) -> purpose: ${purpose}`);
|
||||
|
||||
// Получаем текущие options
|
||||
const currentOptions = await db.getQuery()(
|
||||
'SELECT options FROM user_columns WHERE id = $1',
|
||||
[col.id]
|
||||
);
|
||||
|
||||
let options = currentOptions.rows[0]?.options || {};
|
||||
options.purpose = purpose;
|
||||
|
||||
// Обновляем колонку
|
||||
await db.getQuery()(
|
||||
'UPDATE user_columns SET options = $1 WHERE id = $2',
|
||||
[JSON.stringify(options), col.id]
|
||||
);
|
||||
|
||||
console.log(` ✅ Обновлено`);
|
||||
} else {
|
||||
console.log(`\n⚠️ Колонка "${col.name}" (ID: ${col.id}) - purpose не определен`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n✅ Исправление завершено!');
|
||||
|
||||
// Проверяем результат
|
||||
console.log('\nПроверка результата:');
|
||||
const updatedColumns = await db.getQuery()(
|
||||
'SELECT id, decrypt_text(name_encrypted, $1) as name, options FROM user_columns WHERE table_id = 28 ORDER BY id',
|
||||
[encryptionKey]
|
||||
);
|
||||
|
||||
updatedColumns.rows.forEach(col => {
|
||||
const options = col.options || {};
|
||||
console.log(` ID: ${col.id}, Name: ${col.name}, Purpose: ${options.purpose || 'undefined'}`);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Ошибка:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Запуск скрипта
|
||||
if (require.main === module) {
|
||||
fixRagColumns().then(() => {
|
||||
console.log('\n🏁 Скрипт завершен');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('💥 Критическая ошибка:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { fixRagColumns };
|
||||
120
backend/scripts/test-ai-queue-docker.js
Normal file
120
backend/scripts/test-ai-queue-docker.js
Normal file
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Copyright (c) 2024-2025 Тарабанов Александр Викторович
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is proprietary and confidential.
|
||||
* Unauthorized copying, modification, or distribution is prohibited.
|
||||
*
|
||||
* For licensing inquiries: info@hb3-accelerator.com
|
||||
* Website: https://hb3-accelerator.com
|
||||
* GitHub: https://github.com/HB3-ACCELERATOR
|
||||
*/
|
||||
|
||||
// Устанавливаем переменные окружения для Docker
|
||||
process.env.OLLAMA_BASE_URL = 'http://ollama:11434';
|
||||
process.env.OLLAMA_MODEL = 'qwen2.5:7b';
|
||||
|
||||
const aiQueueService = require('../services/ai-queue');
|
||||
|
||||
async function testQueueInDocker() {
|
||||
console.log('🐳 Тестирование AI очереди в Docker...\n');
|
||||
|
||||
try {
|
||||
// Проверяем инициализацию
|
||||
console.log('1. Проверка инициализации очереди...');
|
||||
const stats = aiQueueService.getStats();
|
||||
console.log('✅ Очередь инициализирована:', stats.isInitialized);
|
||||
console.log('📊 Статистика:', {
|
||||
totalProcessed: stats.totalProcessed,
|
||||
totalFailed: stats.totalFailed,
|
||||
currentQueueSize: stats.currentQueueSize,
|
||||
runningTasks: stats.runningTasks
|
||||
});
|
||||
|
||||
// Тестируем добавление задач
|
||||
console.log('\n2. Тестирование добавления задач...');
|
||||
|
||||
const testTasks = [
|
||||
{
|
||||
message: 'Привет, как дела?',
|
||||
language: 'ru',
|
||||
type: 'chat',
|
||||
userId: 1,
|
||||
userRole: 'user',
|
||||
requestId: 'docker_test_1'
|
||||
},
|
||||
{
|
||||
message: 'Расскажи о погоде',
|
||||
language: 'ru',
|
||||
type: 'analysis',
|
||||
userId: 1,
|
||||
userRole: 'user',
|
||||
requestId: 'docker_test_2'
|
||||
},
|
||||
{
|
||||
message: 'Срочный вопрос!',
|
||||
language: 'ru',
|
||||
type: 'urgent',
|
||||
userId: 1,
|
||||
userRole: 'admin',
|
||||
requestId: 'docker_test_3'
|
||||
}
|
||||
];
|
||||
|
||||
for (let i = 0; i < testTasks.length; i++) {
|
||||
const task = testTasks[i];
|
||||
console.log(` Добавляем задачу ${i + 1}: "${task.message}"`);
|
||||
|
||||
try {
|
||||
const result = await aiQueueService.addTask(task);
|
||||
console.log(` ✅ Задача добавлена, ID: ${result.taskId}`);
|
||||
} catch (error) {
|
||||
console.log(` ❌ Ошибка добавления задачи: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Ждем обработки
|
||||
console.log('\n3. Ожидание обработки задач...');
|
||||
await new Promise(resolve => setTimeout(resolve, 15000));
|
||||
|
||||
// Проверяем статистику
|
||||
console.log('\n4. Проверка статистики после обработки...');
|
||||
const finalStats = aiQueueService.getStats();
|
||||
console.log('📊 Финальная статистика:', {
|
||||
totalProcessed: finalStats.totalProcessed,
|
||||
totalFailed: finalStats.totalFailed,
|
||||
currentQueueSize: finalStats.currentQueueSize,
|
||||
runningTasks: finalStats.runningTasks,
|
||||
averageProcessingTime: Math.round(finalStats.averageProcessingTime)
|
||||
});
|
||||
|
||||
// Тестируем управление очередью
|
||||
console.log('\n5. Тестирование управления очередью...');
|
||||
|
||||
console.log(' Пауза очереди...');
|
||||
aiQueueService.pause();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
console.log(' Возобновление очереди...');
|
||||
aiQueueService.resume();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
console.log('\n✅ Тестирование завершено!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Ошибка тестирования:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Запуск теста
|
||||
if (require.main === module) {
|
||||
testQueueInDocker().then(() => {
|
||||
console.log('\n🏁 Тест завершен');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('💥 Критическая ошибка:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { testQueueInDocker };
|
||||
116
backend/scripts/test-ai-queue.js
Normal file
116
backend/scripts/test-ai-queue.js
Normal file
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Copyright (c) 2024-2025 Тарабанов Александр Викторович
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is proprietary and confidential.
|
||||
* Unauthorized copying, modification, or distribution is prohibited.
|
||||
*
|
||||
* For licensing inquiries: info@hb3-accelerator.com
|
||||
* Website: https://hb3-accelerator.com
|
||||
* GitHub: https://github.com/HB3-ACCELERATOR
|
||||
*/
|
||||
|
||||
const aiQueueService = require('../services/ai-queue');
|
||||
|
||||
async function testQueue() {
|
||||
console.log('🧪 Тестирование AI очереди...\n');
|
||||
|
||||
try {
|
||||
// Проверяем инициализацию
|
||||
console.log('1. Проверка инициализации очереди...');
|
||||
const stats = aiQueueService.getStats();
|
||||
console.log('✅ Очередь инициализирована:', stats.isInitialized);
|
||||
console.log('📊 Статистика:', {
|
||||
totalProcessed: stats.totalProcessed,
|
||||
totalFailed: stats.totalFailed,
|
||||
currentQueueSize: stats.currentQueueSize,
|
||||
runningTasks: stats.runningTasks
|
||||
});
|
||||
|
||||
// Тестируем добавление задач
|
||||
console.log('\n2. Тестирование добавления задач...');
|
||||
|
||||
const testTasks = [
|
||||
{
|
||||
message: 'Привет, как дела?',
|
||||
language: 'ru',
|
||||
type: 'chat',
|
||||
userId: 1,
|
||||
userRole: 'user',
|
||||
requestId: 'test_1'
|
||||
},
|
||||
{
|
||||
message: 'Расскажи о погоде',
|
||||
language: 'ru',
|
||||
type: 'analysis',
|
||||
userId: 1,
|
||||
userRole: 'user',
|
||||
requestId: 'test_2'
|
||||
},
|
||||
{
|
||||
message: 'Срочный вопрос!',
|
||||
language: 'ru',
|
||||
type: 'urgent',
|
||||
userId: 1,
|
||||
userRole: 'admin',
|
||||
requestId: 'test_3'
|
||||
}
|
||||
];
|
||||
|
||||
for (let i = 0; i < testTasks.length; i++) {
|
||||
const task = testTasks[i];
|
||||
console.log(` Добавляем задачу ${i + 1}: "${task.message}"`);
|
||||
|
||||
try {
|
||||
const result = await aiQueueService.addTask(task);
|
||||
console.log(` ✅ Задача добавлена, ID: ${result.taskId}`);
|
||||
} catch (error) {
|
||||
console.log(` ❌ Ошибка добавления задачи: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Ждем обработки
|
||||
console.log('\n3. Ожидание обработки задач...');
|
||||
await new Promise(resolve => setTimeout(resolve, 10000));
|
||||
|
||||
// Проверяем статистику
|
||||
console.log('\n4. Проверка статистики после обработки...');
|
||||
const finalStats = aiQueueService.getStats();
|
||||
console.log('📊 Финальная статистика:', {
|
||||
totalProcessed: finalStats.totalProcessed,
|
||||
totalFailed: finalStats.totalFailed,
|
||||
currentQueueSize: finalStats.currentQueueSize,
|
||||
runningTasks: finalStats.runningTasks,
|
||||
averageProcessingTime: Math.round(finalStats.averageProcessingTime)
|
||||
});
|
||||
|
||||
// Тестируем управление очередью
|
||||
console.log('\n5. Тестирование управления очередью...');
|
||||
|
||||
console.log(' Пауза очереди...');
|
||||
aiQueueService.pause();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
console.log(' Возобновление очереди...');
|
||||
aiQueueService.resume();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
console.log('\n✅ Тестирование завершено!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Ошибка тестирования:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Запуск теста
|
||||
if (require.main === module) {
|
||||
testQueue().then(() => {
|
||||
console.log('\n🏁 Тест завершен');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('💥 Критическая ошибка:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { testQueue };
|
||||
82
backend/scripts/test-encrypted-tables.js
Normal file
82
backend/scripts/test-encrypted-tables.js
Normal file
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Copyright (c) 2024-2025 Тарабанов Александр Викторович
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is proprietary and confidential.
|
||||
* Unauthorized copying, modification, or distribution is prohibited.
|
||||
*
|
||||
* For licensing inquiries: info@hb3-accelerator.com
|
||||
* Website: https://hb3-accelerator.com
|
||||
* GitHub: https://github.com/HB3-ACCELERATOR
|
||||
*/
|
||||
|
||||
const encryptedDb = require('../services/encryptedDatabaseService');
|
||||
const db = require('../db');
|
||||
|
||||
async function testEncryptedTables() {
|
||||
console.log('🔐 Тестирование зашифрованных таблиц...\n');
|
||||
|
||||
try {
|
||||
// Тестируем таблицу is_rag_source
|
||||
console.log('1. Тестирование таблицы is_rag_source:');
|
||||
const ragSources = await encryptedDb.getData('is_rag_source', {});
|
||||
console.log(' ✅ Данные получены:', ragSources);
|
||||
|
||||
// Тестируем через прямой SQL запрос
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
let encryptionKey = 'default-key';
|
||||
|
||||
try {
|
||||
const keyPath = path.join(__dirname, '../ssl/keys/full_db_encryption.key');
|
||||
if (fs.existsSync(keyPath)) {
|
||||
encryptionKey = fs.readFileSync(keyPath, 'utf8').trim();
|
||||
}
|
||||
} catch (keyError) {
|
||||
console.error('Error reading encryption key:', keyError);
|
||||
}
|
||||
|
||||
const directResult = await db.getQuery()(
|
||||
'SELECT id, decrypt_text(name_encrypted, $1) as name FROM is_rag_source ORDER BY id',
|
||||
[encryptionKey]
|
||||
);
|
||||
console.log(' ✅ Прямой SQL запрос:', directResult.rows);
|
||||
|
||||
// Тестируем другие важные таблицы
|
||||
console.log('\n2. Тестирование других зашифрованных таблиц:');
|
||||
|
||||
// user_tables
|
||||
const userTables = await encryptedDb.getData('user_tables', {}, 5);
|
||||
console.log(' ✅ user_tables (первые 5):', userTables.length, 'записей');
|
||||
|
||||
// user_columns
|
||||
const userColumns = await encryptedDb.getData('user_columns', {}, 5);
|
||||
console.log(' ✅ user_columns (первые 5):', userColumns.length, 'записей');
|
||||
|
||||
// messages
|
||||
const messages = await encryptedDb.getData('messages', {}, 3);
|
||||
console.log(' ✅ messages (первые 3):', messages.length, 'записей');
|
||||
|
||||
// conversations
|
||||
const conversations = await encryptedDb.getData('conversations', {}, 3);
|
||||
console.log(' ✅ conversations (первые 3):', conversations.length, 'записей');
|
||||
|
||||
console.log('\n✅ Все тесты прошли успешно!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Ошибка тестирования:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Запуск теста
|
||||
if (require.main === module) {
|
||||
testEncryptedTables().then(() => {
|
||||
console.log('\n🏁 Тест завершен');
|
||||
process.exit(0);
|
||||
}).catch(error => {
|
||||
console.error('💥 Критическая ошибка:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { testEncryptedTables };
|
||||
Reference in New Issue
Block a user