搜索
首页web前端js教程从 VSCode 扩展管理 TOML 配置 - DBChat 第 8 部分

Shrijith Venkatrama,Hexmos 的创始人,正在构建 LiveAPI,这是一个超级方便的工具,只需几分钟即可从您的代码生成出色的 API 文档,从而简化工程工作流程。

在本教程系列中,我正在为我自己构建 DBChat——一个简单的工具,用于使用 AI 聊天来探索和改进数据库。

请参阅之前的文章以获取更多上下文:

  1. 构建 DBChat - 使用简单的聊天探索和改进您的数据库(第一部分)
  2. DBChat:在 Golang 中启动一个玩具 REPL(第二部分)
  3. DBChat 第三部分 - 配置、连接和转储数据库
  4. 通过 DBChat 和 Gemini 与您的数据库聊天(第四部分)
  5. 语言服务器协议 - 构建 DBChat(第五部分)
  6. 制作 DBChat VSCode 扩展 - 与 LSP 后端进行乒乓球交互(第六部分)
  7. 为 DBChat 启动 VSCode 扩展 UI(第七部分)

在 VSCode 扩展中为 DBChat 构建 TOML 连接管理器 UI

在之前的文章中,我们在 DBChat VSCode 扩展中创建了一个简单的聊天 UI 和数据库连接表单的框架。

在这篇文章中,我将演示 DBChat 扩展如何操作 ~/.dbchat.toml 配置文件的 [connections] 部分以添加/更新/删除条目。

为了唤醒您的记忆,配置文件应该具有如下结构:

<code># DBChat 示例配置文件
# 将此文件复制到 ~/.dbchat.toml 并根据需要修改

[connections]
# 格式:name = "connection_string"
local = "postgresql://postgres:postgres@localhost:5432/postgres"
liveapi = "postgresql://user:pwd@ip:5432/db_name" 

[llm]
gemini_key = "the_key"</code>

结果

DBChat 连接列表:

Manage TOML Configuration From VSCode Extension - DBChat Part 8

DBChat 添加/编辑连接:

Manage TOML Configuration From VSCode Extension - DBChat Part 8

对于编辑和更新,我们还有一个确认提示以避免错误。

处理创建连接请求

首先,安装 toml 扩展:

<code> npm install @iarna/toml</code>

我们得到一些新的导入:

<code>import * as fs from 'fs/promises';
import * as path from 'path';
import * as os from 'os';
import * as TOML from '@iarna/toml';</code>

关键结构是一个消息处理程序,它将接收所有三个操作的事件:

<code>        const messageHandler = this._view.webview.onDidReceiveMessage(
            async (message) => {
                console.log('Received message:', message);
                switch (message.command) {
                    case 'saveConnection':
                        console.log('Processing saveConnection command');
                        const success = await this._saveConnection(message.name, message.connectionString);
                        if (success) {
                            console.log('Connection saved successfully, closing form');
                            this._showingConnectionForm = false;
                            this._updateView();
                        } else {
                            console.log('Connection not saved, keeping form open');
                        }
                        break;
                    case 'cancel':
                        console.log('Processing cancel command');
                        this._showingConnectionForm = false;
                        this._updateView();
                        break;
                    case 'editConnection':
                        this._showingConnectionForm = true;
                        this._editingConnection = message.name;
                        // First update the view to show the form
                        await this._updateView();
                        // Then send the prefill message after a short delay to ensure the form exists
                        setTimeout(() => {
                            this._view.webview.postMessage({ 
                                command: 'prefillForm', 
                                name: message.name, 
                                connectionString: message.connectionString 
                            });
                        }, 100);
                        break;
                    case 'deleteConnection':
                        const choice = await vscode.window.showWarningMessage(
                            `Are you sure you want to delete connection "${message.name}"?`,
                            'Yes',
                            'No'
                        );
                        if (choice === 'Yes') {
                            const deleted = await this._deleteConnection(message.name);
                            if (deleted) {
                                await this._updateView();  // Update view after successful deletion
                                vscode.window.showInformationMessage(`Connection "${message.name}" deleted successfully.`);
                            }
                        }
                        break;
                }
            }
        );

        // Add message handler to subscriptions for cleanup
        context.subscriptions.push(messageHandler);</code>

保存连接非常简单:

<code>    private async _saveConnection(name: string, connectionString: string): Promise<boolean> {
        console.log('Starting _saveConnection with:', { name, connectionString });
        try {
            const configPath = path.join(os.homedir(), 'dbchat.toml');
            console.log('Config path:', configPath);

            let config: any = {
                connections: {},
                llm: {}
            };
            console.log('Initial config structure:', config);

            // Read existing config if it exists
            try {
                console.log('Attempting to read existing config file...');
                const fileContent = await fs.readFile(configPath, 'utf-8');
                console.log('Existing file content:', fileContent);

                console.log('Parsing TOML content...');
                config = TOML.parse(fileContent);
                console.log('Parsed config:', config);

                // Ensure connections section exists
                config.connections = config.connections || {};
                console.log('Config after ensuring connections exist:', config);
            } catch (error: any) {
                console.log('Error reading config:', error);
                if (error.code !== 'ENOENT') {
                    console.error('Unexpected error reading config:', error);
                    throw error;
                }
                console.log('Config file does not exist, will create new one');
            }

            // Check if connection already exists
            if (config.connections[name]) {
                console.log(`Connection "${name}" already exists, showing confirmation dialog`);
                const choice = await vscode.window.showWarningMessage(
                    `Connection "${name}" already exists. Do you want to overwrite it?`,
                    'Yes',
                    'No'
                );
                console.log('User choice for overwrite:', choice);

                if (choice !== 'Yes') {
                    console.log('User declined to overwrite, returning false');
                    return false;
                }
            }

            // Update the connection
            config.connections[name] = connectionString;
            console.log('Updated config:', config);

            // Convert config to TOML and write back to file
            console.log('Converting config to TOML...');
            const tomlContent = TOML.stringify(config);
            console.log('Generated TOML content:', tomlContent);

            // Preserve the header comments
            const finalContent = `# DBChat Sample Configuration File
# Copy this file to ~/.dbchat.toml and modify as needed

${tomlContent}`;
            console.log('Final content to write:', finalContent);

            console.log('Writing to file...');
            await fs.writeFile(configPath, finalContent, 'utf-8');
            console.log('File written successfully');

            // Update view immediately after successful file write
            this._showingConnectionForm = false;
            console.log('Form hidden, updating view');
            this._updateView();

            await vscode.window.showInformationMessage(`Connection "${name}" saved successfully!`, { modal: false });
            return true;
        } catch (error) {
            console.error('Error in _saveConnection:', error);
            if (error instanceof Error) {
                console.error('Error stack:', error.stack);
            }
            await vscode.window.showErrorMessage(`Failed to save connection: ${error}`);
            return false;
        }
    }
</boolean></code>

列出连接

<code>    private async _getConnections(): Promise {
        try {
            const configPath = path.join(os.homedir(), 'dbchat.toml');
            const fileContent = await fs.readFile(configPath, 'utf-8');
            const config = TOML.parse(fileContent);
            return config.connections || {};
        } catch (error) {
            console.error('Error reading connections:', error);
            return {};
        }
    }</code>

删除连接

<code>    private async _deleteConnection(name: string): Promise<boolean> {
        try {
            const configPath = path.join(os.homedir(), 'dbchat.toml');
            const fileContent = await fs.readFile(configPath, 'utf-8');
            const config = TOML.parse(fileContent);

            if (!config.connections || !config.connections[name]) {
                await vscode.window.showErrorMessage(`Connection "${name}" not found.`);
                return false;
            }

            delete config.connections[name];

            const tomlContent = TOML.stringify(config);
            const finalContent = `# DBChat Sample Configuration File
# Copy this file to ~/.dbchat.toml and modify as needed

${tomlContent}`;

            await fs.writeFile(configPath, finalContent, 'utf-8');
            // Show message after file operations are complete
            vscode.window.showInformationMessage(`Connection "${name}" deleted successfully.`);
            return true;
        } catch (error) {
            console.error('Error deleting connection:', error);
            vscode.window.showErrorMessage(`Failed to delete connection: ${error}`);
            return false;
        }
    }
</boolean></code>

这就是这篇文章的全部内容。通过这种结构,我们实现了一个基本的数据库连接列表、添加、删除和更新操作。

后续步骤

由于我们有一个基本的数据库配置机制,接下来我们将致力于启用连接到特定配置、获取模式、与数据库聊天等功能 - 使用 golang LSP。

以上是从 VSCode 扩展管理 TOML 配置 - DBChat 第 8 部分的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python vs. JavaScript:开发人员的比较分析Python vs. JavaScript:开发人员的比较分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

Python vs. JavaScript:选择合适的工具Python vs. JavaScript:选择合适的工具May 08, 2025 am 12:10 AM

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架:为现代网络开发提供动力JavaScript框架:为现代网络开发提供动力May 02, 2025 am 12:04 AM

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

JavaScript,C和浏览器之间的关系JavaScript,C和浏览器之间的关系May 01, 2025 am 12:06 AM

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。