目錄
在 VSCode 擴充功能中為 DBChat 建置 TOML 連線管理器 UI
結果
處理建立連線請求
列出連接
刪除連線
後續步驟
首頁 web前端 js教程 從 VSCode 擴充功能管理 TOML 設定 - DBChat 第 8 部分

從 VSCode 擴充功能管理 TOML 設定 - DBChat 第 8 部分

Jan 22, 2025 am 04:32 AM

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

熱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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1666
14
CakePHP 教程
1425
52
Laravel 教程
1328
25
PHP教程
1273
29
C# 教程
1253
24
JavaScript引擎:比較實施 JavaScript引擎:比較實施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

從C/C到JavaScript:所有工作方式 從C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript和Web:核心功能和用例 JavaScript和Web:核心功能和用例 Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在行動中:現實世界中的示例和項目 JavaScript在行動中:現實世界中的示例和項目 Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

了解JavaScript引擎:實施詳細信息 了解JavaScript引擎:實施詳細信息 Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python vs. JavaScript:社區,圖書館和資源 Python vs. JavaScript:社區,圖書館和資源 Apr 15, 2025 am 12:16 AM

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python vs. JavaScript:開發環境和工具 Python vs. JavaScript:開發環境和工具 Apr 26, 2025 am 12:09 AM

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

See all articles