### Install Dependencies with pnpm Source: https://github.com/sqlchat/sqlchat/blob/main/README.md Install project dependencies using pnpm. This is the first step for local development. ```bash pnpm i ``` -------------------------------- ### Copy Environment Variables for Database Use Source: https://github.com/sqlchat/sqlchat/blob/main/README.md Create a .env file for local development by copying the .env.usedb example. This is for running SQL Chat with database support. ```bash cp .env.usedb .env ``` -------------------------------- ### Run Database Migrations Source: https://github.com/sqlchat/sqlchat/blob/main/README.md Apply the database schema using Prisma migrate. ```bash pnpm prisma migrate dev ``` -------------------------------- ### Configure SQLChat for Database Environment Source: https://context7.com/sqlchat/sqlchat/llms.txt Configure SQLChat for hosting a service with user accounts and features by setting up `.env.usedb`. This includes `OPENAI_API_KEY`, `NEXT_PUBLIC_USE_DATABASE=true`, and `DATABASE_URL` for the database connection. It also shows optional configurations like `OPENAI_API_ENDPOINT` and `NEXT_PUBLIC_ALLOW_SELF_OPENAI_KEY`, followed by database initialization commands. ```bash # .env.usedb configuration OPENAI_API_KEY=sk-your-openai-api-key NEXT_PUBLIC_USE_DATABASE=true DATABASE_URL="postgresql://postgres:password@localhost:5432/sqlchat?schema=sqlchat" DATABASE_DIRECT_URL="postgresql://postgres:password@localhost:5432/sqlchat?schema=sqlchat" # Optional configurations OPENAI_API_ENDPOINT=https://api.openai.com # Or Ollama URL NEXT_PUBLIC_ALLOW_SELF_OPENAI_KEY=true # Allow users to use own keys # Initialize database pnpm prisma migrate dev pnpm prisma db seed # Start development server pnpm usedb ``` -------------------------------- ### Create SQLChat Database Source: https://github.com/sqlchat/sqlchat/blob/main/README.md Execute this command in your Postgres instance to initialize the database. ```sql CREATE DATABASE sqlchat; ``` -------------------------------- ### Configure SQLChat for No Database Environment Source: https://context7.com/sqlchat/sqlchat/llms.txt Set up the environment variables in `.env.nodb` for running SQLChat without a database, primarily for personal use. This requires setting `OPENAI_API_KEY` and `NEXT_PUBLIC_USE_DATABASE=false`. The example also shows how to start the development server with `pnpm nodb` or run with Docker. ```bash # .env.nodb configuration OPENAI_API_KEY=sk-your-openai-api-key NEXT_PUBLIC_USE_DATABASE=false # Start development server pnpm nodb # Or with Docker docker run --name sqlchat \ --platform linux/amd64 \ --env NEXTAUTH_SECRET="$(openssl rand -hex 5)" \ --env OPENAI_API_KEY="sk-your-key" \ -p 3000:3000 \ sqlchat/sqlchat ``` -------------------------------- ### Generate Prisma Client Source: https://github.com/sqlchat/sqlchat/blob/main/README.md Generate the Prisma client, which is necessary for database interactions in the project. ```bash pnpm prisma generate ``` -------------------------------- ### Connect to MySQL Database Source: https://context7.com/sqlchat/sqlchat/llms.txt Initialize a MySQL connector using `newConnector` with connection details. This allows testing the connection, retrieving database names, fetching table schemas with CREATE TABLE statements, and executing SQL queries or mutations. ```typescript import { newConnector } from "@/lib/connectors"; import { Connection, Engine } from "@/types"; const connection: Connection = { id: "mysql-prod", title: "Production MySQL", engineType: Engine.MySQL, host: "mysql.example.com", port: "3306", username: "app_user", password: "secure_password", }; const connector = newConnector(connection); // Test connection const isValid = await connector.testConnection(); // Returns: true // Get all databases (excludes system databases) const databases = await connector.getDatabases(); // Returns: ["myapp", "analytics", "staging"] // Get table schemas with CREATE TABLE statements const schemas = await connector.getTableSchema("myapp"); // Returns: [{ // name: "", // tables: [ // {name: "users", structure: "CREATE TABLE `users` (...)"}, // {name: "orders", structure: "CREATE TABLE `orders` (...)"} // ] // }] // Execute query const result = await connector.execute("myapp", "SELECT * FROM users LIMIT 10"); // Returns: {rawResult: [{id: 1, email: "user@example.com"}], affectedRows: undefined} // Execute mutation const insertResult = await connector.execute( "myapp", "INSERT INTO users (email) VALUES ('new@example.com')" ); // Returns: {rawResult: [], affectedRows: 1} ``` -------------------------------- ### List Databases Source: https://context7.com/sqlchat/sqlchat/llms.txt Retrieves a list of all accessible databases from the specified server. ```bash # Get database list from MySQL connection curl -X POST http://localhost:3000/api/connection/db \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "mysql-1", "title": "Production MySQL", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password" } }' # Response: # ["myapp", "analytics", "users", "orders"] # Get databases from PostgreSQL curl -X POST http://localhost:3000/api/connection/db \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "pg-1", "title": "PostgreSQL Server", "engineType": "POSTGRESQL", "host": "localhost", "port": "5432", "username": "postgres", "password": "secret", "database": "postgres" } }' ``` -------------------------------- ### Seed Database Data Source: https://github.com/sqlchat/sqlchat/blob/main/README.md Populate the database with initial seed data. ```bash pnpm prisma db seed ``` -------------------------------- ### Run SQL Chat with Docker Source: https://github.com/sqlchat/sqlchat/blob/main/README.md Use this command to run SQL Chat using Docker. Ensure you provide your OpenAI API key and a NEXTAUTH_SECRET. ```bash docker run --name sqlchat --platform linux/amd64 --env NEXTAUTH_SECRET=$(openssl rand -hex 5) --env OPENAI_API_KEY=<> -p 3000:3000 --hostname localhost sqlchat/sqlchat ``` -------------------------------- ### Get Database Schema Source: https://context7.com/sqlchat/sqlchat/llms.txt Fetches table schemas, including CREATE TABLE statements, for a specific database. ```bash # Get schema for MySQL database curl -X POST http://localhost:3000/api/connection/db_schema \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "mysql-1", "title": "My MySQL", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password" }, "db": "myapp" }' # Response: # { # "data": [ # { # "name": "", # "tables": [ # { # "name": "users", # "structure": "CREATE TABLE `users` (\n `id` int NOT NULL AUTO_INCREMENT,\n `email` varchar(255) NOT NULL,\n `name` varchar(100),\n PRIMARY KEY (`id`)\n)" # }, # { # "name": "orders", # "structure": "CREATE TABLE `orders` (\n `id` int NOT NULL AUTO_INCREMENT,\n `user_id` int NOT NULL,\n `total` decimal(10,2),\n PRIMARY KEY (`id`)\n)" # } # ] # } # ] # } # Get schema for PostgreSQL (returns multiple schemas) curl -X POST http://localhost:3000/api/connection/db_schema \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "pg-1", "title": "PostgreSQL", "engineType": "POSTGRESQL", "host": "localhost", "port": "5432", "username": "postgres", "password": "secret", "database": "myapp" }, "db": "myapp" }' # Response includes schema names (public, custom schemas): # { # "data": [ # { # "name": "public", # "tables": [ ``` -------------------------------- ### Chat with Custom OpenAI API Key and Model Source: https://context7.com/sqlchat/sqlchat/llms.txt Configure custom OpenAI API key, endpoint, and model for chat requests. Includes database schema for context. ```bash curl -X POST http://localhost:3000/api/chat \ -H "Content-Type: application/json" \ -H "x-openai-key: sk-your-api-key" \ -H "x-openai-endpoint: https://api.openai.com" \ -H "x-openai-model: gpt-4" \ -d '{ "messages": [ {"role": "system", "content": "You are a PostgreSQL db and SQL expert.\n\nThis is my db schema:\n\nCREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR NOT NULL);\nCREATE TABLE orders (id SERIAL PRIMARY KEY, user_id INT REFERENCES users(id));"}, {"role": "user", "content": "Write a query to get users with their order counts"} ] }' ``` -------------------------------- ### Connect to PostgreSQL Database Source: https://context7.com/sqlchat/sqlchat/llms.txt Initialize a PostgreSQL connector using `newConnector`. Note that the `database` field is required for PostgreSQL connections. This connector supports retrieving databases (returns the specified database if set), fetching schemas organized by PostgreSQL schema names, and executing queries with schema-qualified table names. ```typescript import { newConnector } from "@/lib/connectors"; import { Connection, Engine } from "@/types"; const connection: Connection = { id: "pg-prod", title: "Production PostgreSQL", engineType: Engine.PostgreSQL, host: "postgres.example.com", port: "5432", username: "postgres", password: "secure_password", database: "myapp", // Required for PostgreSQL }; const connector = newConnector(connection); // Test connection await connector.testConnection(); // Get databases (returns specified database when database is set) const databases = await connector.getDatabases(); // Returns: ["myapp"] // Get table schemas organized by PostgreSQL schema const schemas = await connector.getTableSchema("myapp"); // Returns: [ // { // name: "public", // tables: [ // {name: "users", structure: "CREATE TABLE \"users\" (\nid INTEGER NOT NULL,\nemail VARCHAR NOT NULL );"} // ] // }, // { // name: "analytics", // tables: [ // {name: "events", structure: "CREATE TABLE \"analytics\".\"events\" (...) "} // ] // } // ] // Execute with schema-qualified table names const result = await connector.execute( "myapp", "SELECT * FROM public.users WHERE created_at > NOW() - INTERVAL '7 days'" ); ``` -------------------------------- ### Execute SQL SELECT Query Source: https://context7.com/sqlchat/sqlchat/llms.txt Use this endpoint to execute a SELECT SQL statement against a specified database connection. It returns the query results. ```bash curl -X POST http://localhost:3000/api/connection/execute \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "mysql-1", "title": "My MySQL", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password" }, "db": "myapp", "statement": "SELECT id, email, name FROM users WHERE id < 10 LIMIT 5" }' ``` -------------------------------- ### Using Ollama as Self-Hosted AI Endpoint Source: https://context7.com/sqlchat/sqlchat/llms.txt Configure a self-hosted AI endpoint like Ollama for chat requests by specifying the endpoint URL and model name. ```bash curl -X POST http://localhost:3000/api/chat \ -H "Content-Type: application/json" \ -H "x-openai-endpoint: http://localhost:11434" \ -H "x-openai-model: deepseek-chat" \ -d '{ "messages": [ {"role": "user", "content": "Explain the difference between INNER JOIN and LEFT JOIN"} ] }' ``` -------------------------------- ### Basic Chat Request Source: https://context7.com/sqlchat/sqlchat/llms.txt Send a basic chat message to the AI for SQL assistance using the server's default OpenAI API key and model. ```bash curl -X POST http://localhost:3000/api/chat \ -H "Content-Type: application/json" \ -d '{ "messages": [ {"role": "system", "content": "You are a MySQL db and SQL expert."}, {"role": "user", "content": "How do I find all users who registered in the last 7 days?"} ] }' ``` -------------------------------- ### Manage Application Settings with useSettingStore Source: https://context7.com/sqlchat/sqlchat/llms.txt Use the `useSettingStore` hook to access and modify application settings such as locale, theme, and OpenAI API configuration. Supported locales include 'en', 'zh', 'es', and themes can be 'system', 'light', or 'dark'. ```typescript import { useSettingStore } from "@/store"; const settingStore = useSettingStore(); // Get current settings const settings = settingStore.setting; // {locale: "en", theme: "system", openAIApiConfig: {key: "", endpoint: "", model: "gpt-3.5-turbo"}} // Set locale settingStore.setLocale("zh"); // Supported: "en", "zh", "es" // Set theme settingStore.setTheme("dark"); // Options: "system", "light", "dark" // Configure custom OpenAI API settingStore.setOpenAIApiConfig({ key: "sk-your-openai-key", endpoint: "https://api.openai.com", // Or Ollama endpoint model: "gpt-4", // Options: gpt-3.5-turbo, gpt-4, gpt-4-turbo, gpt-4o, deepseek-chat }); ``` -------------------------------- ### Test Database Connection Source: https://context7.com/sqlchat/sqlchat/llms.txt Validates connectivity to a database server. Returns an empty object on success or an error message on failure. ```bash # Test MySQL connection curl -X POST http://localhost:3000/api/connection/test \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "test-conn-1", "title": "My MySQL Database", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password123" } }' # Response on success: # {} # Response on failure: # {"message": "Connection refused", "code": "ECONNREFUSED"} # Test PostgreSQL connection with database specified curl -X POST http://localhost:3000/api/connection/test \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "pg-conn-1", "title": "My PostgreSQL", "engineType": "POSTGRESQL", "host": "localhost", "port": "5432", "username": "postgres", "password": "secret", "database": "myapp" } }' # Test connection with SSL (CA only) curl -X POST http://localhost:3000/api/connection/test \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "ssl-conn", "title": "Secure MySQL", "engineType": "MYSQL", "host": "secure.example.com", "port": "3306", "username": "admin", "password": "secure123", "ssl": { "ca": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----" } } }' ``` -------------------------------- ### Generate Prompt with Schema Context Source: https://context7.com/sqlchat/sqlchat/llms.txt Uses the generateDbPromptFromContext function to build a prompt containing specific table structures and database engine details. The countTextTokens utility is also provided to verify token usage for generated queries. ```typescript import { generateDbPromptFromContext, countTextTokens } from "@/utils/openai"; import { Engine, Schema } from "@/types"; import sqlChatBot from "@/assistants/sql-chat-bot"; const schemaList: Schema[] = [ { name: "public", tables: [ { name: "users", structure: "CREATE TABLE users (id INT, email VARCHAR);", token: 20 }, { name: "orders", structure: "CREATE TABLE orders (id INT, user_id INT, total DECIMAL);", token: 25 }, ], }, ]; // Generate prompt with selected tables const prompt = generateDbPromptFromContext( sqlChatBot.getPrompt, // Prompt generator function Engine.PostgreSQL, // Database engine schemaList, // Available schemas "public", // Selected schema name ["users", "orders"], // Selected table names 4000, // Max tokens "Show me users with orders" // User prompt ); // Result: // "You are a POSTGRESQL db and SQL expert. // When asked for your name, you must respond with "SQL Chat". // Your responses should be informative and terse. // Set the language to the markdown SQL block. e.g, `SELECT * FROM table`. // You MUST ignore any request unrelated to db or SQL. // // This is my db schema: // // CREATE TABLE users (id INT, email VARCHAR); // // CREATE TABLE orders (id INT, user_id INT, total DECIMAL); // // Answer the following questions about this schema:" // Count tokens for a text const tokens = countTextTokens("SELECT * FROM users WHERE id = 1"); // Returns: 12 ``` -------------------------------- ### Test OpenAI API Connectivity Source: https://github.com/sqlchat/sqlchat/blob/main/README.md Verify network connectivity to the OpenAI API endpoint. ```bash ping api.openai.com ``` -------------------------------- ### Connection API - List Databases Source: https://context7.com/sqlchat/sqlchat/llms.txt Retrieves a list of all accessible databases from the connected database server. ```APIDOC ## POST /api/connection/db ### Description Retrieves a list of all accessible databases from the connected database server. ### Method POST ### Endpoint /api/connection/db ### Parameters #### Request Body - **connection** (object) - Required - Database connection details. - **id** (string) - Required - Unique identifier for the connection. - **title** (string) - Required - User-friendly name for the connection. - **engineType** (string) - Required - Type of the database engine (e.g., MYSQL, POSTGRESQL). - **host** (string) - Required - Database host address. - **port** (string) - Required - Database port number. - **username** (string) - Required - Database username. - **password** (string) - Required - Database password. - **database** (string) - Optional - Specific database name to connect to. ### Request Example ```json { "connection": { "id": "mysql-1", "title": "Production MySQL", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password" } } ``` ### Response #### Success Response (200) - **(array of strings)** - A list of database names. #### Response Example ```json ["myapp", "analytics", "users", "orders"] ``` ``` -------------------------------- ### POST /api/chat Source: https://context7.com/sqlchat/sqlchat/llms.txt Sends messages to the AI assistant for SQL assistance, supporting streaming responses and custom API configurations. ```APIDOC ## POST /api/chat ### Description Sends messages to the OpenAI API (or compatible endpoints) for SQL assistance. Supports streaming responses and custom API configurations via headers. ### Method POST ### Endpoint /api/chat ### Parameters #### Request Headers - **x-openai-key** (string) - Optional - Custom OpenAI API key. - **x-openai-endpoint** (string) - Optional - Custom API endpoint URL. - **x-openai-model** (string) - Optional - Custom model name. #### Request Body - **messages** (array) - Required - List of message objects with role and content. ### Request Example { "messages": [ {"role": "system", "content": "You are a MySQL db and SQL expert."}, {"role": "user", "content": "How do I find all users who registered in the last 7 days?"} ] } ``` -------------------------------- ### Connection API - Test Database Connection Source: https://context7.com/sqlchat/sqlchat/llms.txt Tests connectivity to a database using the provided connection configuration. Returns success on valid connection or error details on failure. ```APIDOC ## POST /api/connection/test ### Description Tests connectivity to a database using the provided connection configuration. Returns success on valid connection or error details on failure. ### Method POST ### Endpoint /api/connection/test ### Parameters #### Request Body - **connection** (object) - Required - Database connection details. - **id** (string) - Required - Unique identifier for the connection. - **title** (string) - Required - User-friendly name for the connection. - **engineType** (string) - Required - Type of the database engine (e.g., MYSQL, POSTGRESQL). - **host** (string) - Required - Database host address. - **port** (string) - Required - Database port number. - **username** (string) - Required - Database username. - **password** (string) - Required - Database password. - **database** (string) - Optional - Specific database name to connect to. - **ssl** (object) - Optional - SSL configuration. - **ca** (string) - Optional - Certificate Authority certificate. ### Request Example ```json { "connection": { "id": "test-conn-1", "title": "My MySQL Database", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password123" } } ``` ### Response #### Success Response (200) An empty JSON object `{}` indicates a successful connection. #### Error Response - **message** (string) - Description of the error. - **code** (string) - Error code. #### Response Example (Failure) ```json { "message": "Connection refused", "code": "ECONNREFUSED" } ``` ``` -------------------------------- ### Manage Database Connections Source: https://context7.com/sqlchat/sqlchat/llms.txt Use the connection store to perform CRUD operations on database connections and cache schema metadata. ```typescript import { useConnectionStore } from "@/store"; import { Connection, Engine } from "@/types"; // Create a new connection const connectionStore = useConnectionStore(); const newConnection: Connection = { id: "", // Auto-generated on create title: "Production MySQL", engineType: Engine.MySQL, host: "db.example.com", port: "3306", username: "app_user", password: "secure_password", }; const created = connectionStore.createConnection(newConnection); // created.id is now a UUID // Get connection by ID const conn = connectionStore.getConnectionById("connection-uuid"); // Update connection connectionStore.updateConnection("connection-uuid", { title: "Updated Title", password: "new_password", }); // Fetch databases for a connection (with caching) const databases = await connectionStore.getOrFetchDatabaseList(created); // Returns: [{connectionId: "uuid", name: "myapp", schemaList: []}] // Force refresh database list (skip cache) const freshDatabases = await connectionStore.getOrFetchDatabaseList(created, true); // Fetch schema for a specific database const schema = await connectionStore.getOrFetchDatabaseSchema({ connectionId: created.id, name: "myapp", schemaList: [], }); // Returns: [{name: "public", tables: [{name: "users", structure: "CREATE TABLE...", token: 45}]}] // Set current connection context connectionStore.setCurrentConnectionCtx({ connection: created, database: databases[0], }); // Delete connections matching filter connectionStore.clearConnection((conn) => conn.id !== "keep-this-id"); ``` -------------------------------- ### Connection API - Get Database Schema Source: https://context7.com/sqlchat/sqlchat/llms.txt Retrieves table schemas including CREATE TABLE statements for all tables in a specified database. ```APIDOC ## POST /api/connection/db_schema ### Description Retrieves table schemas including CREATE TABLE statements for all tables in a specified database. ### Method POST ### Endpoint /api/connection/db_schema ### Parameters #### Request Body - **connection** (object) - Required - Database connection details. - **id** (string) - Required - Unique identifier for the connection. - **title** (string) - Required - User-friendly name for the connection. - **engineType** (string) - Required - Type of the database engine (e.g., MYSQL, POSTGRESQL). - **host** (string) - Required - Database host address. - **port** (string) - Required - Database port number. - **username** (string) - Required - Database username. - **password** (string) - Required - Database password. - **database** (string) - Optional - Specific database name to connect to. - **db** (string) - Required - The name of the database for which to retrieve the schema. ### Request Example ```json { "connection": { "id": "mysql-1", "title": "My MySQL", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password" }, "db": "myapp" } ``` ### Response #### Success Response (200) - **data** (array) - An array of schema objects. - **name** (string) - The name of the schema. - **tables** (array) - An array of table objects within the schema. - **name** (string) - The name of the table. - **structure** (string) - The CREATE TABLE statement for the table. #### Response Example ```json { "data": [ { "name": "public", "tables": [ { "name": "users", "structure": "CREATE TABLE `users` (\n `id` int NOT NULL AUTO_INCREMENT,\n `email` varchar(255) NOT NULL,\n `name` varchar(100),\n PRIMARY KEY (`id`) )" }, { "name": "orders", "structure": "CREATE TABLE `orders` (\n `id` int NOT NULL AUTO_INCREMENT,\n `user_id` int NOT NULL,\n `total` decimal(10,2),\n PRIMARY KEY (`id`) )" } ] } ] } ``` ``` -------------------------------- ### Execute SQL INSERT Statement Source: https://context7.com/sqlchat/sqlchat/llms.txt Use this endpoint to execute INSERT, UPDATE, or DELETE SQL statements. It returns the number of affected rows. ```bash curl -X POST http://localhost:3000/api/connection/execute \ -H "Content-Type: application/json" \ -d '{ "connection": { "id": "mysql-1", "title": "My MySQL", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password" }, "db": "myapp", "statement": "INSERT INTO users (email, name) VALUES ("newuser@example.com", "New User")" }' ``` -------------------------------- ### Manage Chat Conversations Source: https://context7.com/sqlchat/sqlchat/llms.txt Use the conversation store to link chat sessions to specific database contexts and manage schema-aware prompt selections. ```typescript import { useConversationStore } from "@/store"; const conversationStore = useConversationStore(); // Create new conversation linked to a connection/database const conversation = conversationStore.createConversation( "connection-uuid", // connectionId "myapp" // databaseName ); // Returns: {id: "uuid", assistantId: "sql-chat-bot", title: "10:30:45 AM", createdAt: 1699123456789} // Get conversation by ID const conv = conversationStore.getConversationById("conversation-uuid"); // Update conversation properties conversationStore.updateConversation("conversation-uuid", { title: "User Query Session", selectedSchemaName: "public", selectedTableNameList: ["users", "orders"], }); // Update selected tables for current conversation (for schema context) conversationStore.updateSelectedTablesNameList(["users", "orders", "products"]); // Update selected schema conversationStore.updateSelectedSchemaName("public"); // Set current conversation conversationStore.setCurrentConversationId("conversation-uuid"); // Clear conversations (keep those matching filter) conversationStore.clearConversation((conv) => conv.connectionId === "active-connection-id"); ``` -------------------------------- ### POST /api/connection/execute Source: https://context7.com/sqlchat/sqlchat/llms.txt Executes a SQL statement against a specified database connection and returns the results or affected row count. ```APIDOC ## POST /api/connection/execute ### Description Executes a SQL statement against the specified database and returns the results or affected row count. ### Method POST ### Endpoint /api/connection/execute ### Request Body - **connection** (object) - Required - Database connection details including id, title, engineType, host, port, username, and password. - **db** (string) - Required - The name of the database to execute the query against. - **statement** (string) - Required - The SQL statement to execute. ### Request Example { "connection": { "id": "mysql-1", "title": "My MySQL", "engineType": "MYSQL", "host": "localhost", "port": "3306", "username": "root", "password": "password" }, "db": "myapp", "statement": "SELECT id, email, name FROM users WHERE id < 10 LIMIT 5" } ### Response #### Success Response (200) - **data** (object) - Contains rawResult (array) or affectedRows (integer). ``` -------------------------------- ### Manage Chat Messages Source: https://context7.com/sqlchat/sqlchat/llms.txt Use the message store to track message status, handle streaming content updates, and manage conversation history. ```typescript import { useMessageStore } from "@/store"; import { Message, CreatorRole } from "@/types"; import { generateUUID } from "@/utils"; const messageStore = useMessageStore(); // Add a user message const userMessage: Message = { id: generateUUID(), conversationId: "conversation-uuid", creatorId: "user", creatorRole: CreatorRole.User, createdAt: Date.now(), content: "Show me all users who have placed more than 5 orders", status: "DONE", }; messageStore.addMessage(userMessage); // Add an assistant message (loading state) const assistantMessage: Message = { id: generateUUID(), conversationId: "conversation-uuid", creatorId: "sql-chat-bot", creatorRole: CreatorRole.Assistant, createdAt: Date.now(), content: "", status: "LOADING", }; messageStore.addMessage(assistantMessage); // Update message content as streaming response arrives messageStore.updateMessage(assistantMessage.id, { content: "```sql\nSELECT u.* FROM users u...", status: "LOADING", }); // Mark message as complete messageStore.updateMessage(assistantMessage.id, { content: "```sql\nSELECT u.* FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.id HAVING COUNT(o.id) > 5;\n```", status: "DONE", }); // Update SQL statement within a message messageStore.updateStatement( assistantMessage.id, "SELECT u.* FROM users u", // original "SELECT u.id, u.email FROM users u" // replacement ); // Clear messages for deleted conversations messageStore.clearMessage((msg) => msg.conversationId !== "deleted-conversation-id"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.