> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qoder.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Database

## Overview

Qoder supports using database connections in JetBrains IDE as AI context. Through the @database feature, AI can generate SQL, perform schema analysis, or generate related code based on actual database table structures.

## Prerequisites

Before using database features, you need to configure database connections in JetBrains IDE:

1. Open the Database tool window
2. Create a database connection
3. Test if the connection is working

For detailed configuration instructions: [https://www.jetbrains.com/help/idea/database-tool-window.html](https://www.jetbrains.com/help/idea/database-tool-window.html)

## Usage

### Referencing Database in Ask/Agent Mode

**Add database to context:**

1. Click "Add Context" in the Qoder input box
2. Select @database
3. Select the target database Schema

**Note:**

* SQL files added to context are generated based on the database schema
* If a database has multiple schemas, multiple corresponding schema SQL files will be generated

After adding, you can directly ask AI database-related questions, such as:

* Generate SQL to query a specific table
* Analyze table structure design
* Generate code based on table structure

**Execute generated SQL:**

SQL code blocks returned in Ask Mode will have an execute button. Click to execute directly.

**Note:** Qoder executes SQL in the currently active database Query Console, so you need to open the corresponding database's Query Console in advance.

### Generate SQL in Query Console

1. Open the database's Query Console
2. Press `Ctrl + Shift + I`
3. Enter natural language description
4. Press Enter to generate SQL

Qoder will automatically use the current database schema as context.

### Using Slash Commands

You can create custom commands to quickly complete common operations.

**Create commands:**

1. Click the profile icon in the Qoder window
2. Select "Settings" → "Commands"
3. Create a new command

**Invoke commands:**

In the Qoder dialog, type `/` followed by the command name to invoke it. For example, type `/sql` to invoke the SQL generation command.

**Common command examples:**

Generate SQL (/sql):

```
Generate SQL statements based on current database schema
```

Database Review (/db-review):

```
Review database schema, check: naming conventions, index design, data types, table relationships
```

Generate Test Data (/mock-data):

```
Generate INSERT test data based on table structure
```

**Tip:** If a command only involves database operations (such as NL2SQL), you can add "Don't scan project files!" at the beginning to avoid scanning project files, saving tokens and avoiding ambiguity. Note that [AGENTS.md](http://AGENTS.md) and Rules files will still be included.

## Using in DataGrip

**Add Qoder to toolbar:**

1. Click the "..." icon at the top
2. Select "Qoder"
3. Click the pin icon to fix it

**Usage:**

* Click the Qoder button in Query Console
* Or press the shortcut `Ctrl + Shift + I`

Qoder will automatically select the corresponding database schema.

**Suggestion:** Add an [AGENTS.md](http://AGENTS.md) file in the project directory to describe table naming conventions, SQL guidelines, or specific data annotations and other project conventions.

## Practical Scenarios

### Database Design

#### Agent Mode (for complex scenarios)

**Suitable for:**

* Need to reference design documents
* Need to generate SQL that complies with specific specifications
* Need to generate migration scripts in specific formats (such as Flyway)

**Steps:**

1. Add relevant documents to context in Agent Mode
2. Describe requirements in natural language
3. Generate SQL file
4. Open and execute the SQL file

#### Query Console Mode (for simple scenarios)

**Suitable for:**

* Simple database structure design
* Table structure adjustments
* Minor modifications

**Steps:**

1. Open the database Schema's Query Console
2. Enter requirements
3. Adjust and execute the generated SQL

#### Database Design Best Practices

**Provide table structure examples:**

If you have standard table structure samples, you can provide them to Qoder as reference:

```
-- Table-level comment example
CREATE TABLE user_info (
    id INT COMMENT 'User ID (standard field name: user_id, primary key)',
    name VARCHAR(50) COMMENT 'User name (standard field name: name, real name)',
    created_at DATETIME COMMENT 'Registration time (standard field name: created_at, account creation time)',
    status TINYINT COMMENT 'Status (standard field name: status, enum: 0-disabled 1-normal 2-frozen)',
    PRIMARY KEY (id)
) COMMENT='User basic information table | Standard table name: user_information | Business domain: User domain | Update method: Real-time';
```

**Design specification recommendations:**

Naming conventions:

* Use clear descriptive names; table and field names should directly express meaning (e.g., user, order\_item), singular form recommended
* Maintain naming consistency; uniformly use snake\_case or camelCase
* Avoid abbreviations; use customer\_address instead of cust\_addr
* Add prefixes for boolean fields, such as is\_active, has\_paid

Structure design:

* Clear primary keys; each table has a clear primary key, named id or table\_name\_id
* Clear foreign key relationships; foreign keys named like user\_id, order\_id, clearly pointing to associated tables
* Add timestamps; include created\_at, updated\_at fields

Documentation and comments:

* Add table comments explaining the table's purpose
* Add field comments explaining field meaning, value range, units, etc.
* Explain enum values; for status fields, comment on the meaning of each value

Type selection:

* Use appropriate data types; avoid using VARCHAR for everything
* Set reasonable length limits
* Clear NULL value strategy; which fields allow NULL, which are required
* Clear default values; specify if there are clear default values

### Annotating Legacy Databases

For legacy databases with non-standard naming, you can use JSON files for annotation to help AI better understand the database structure.

**Example scenario:**

Suppose there is the following legacy database table:

```
CREATE TABLE tbl_yonghu (
  id        BIGINT AUTO_INCREMENT PRIMARY KEY,
  xin_bie   CHAR(2)     NOT NULL,
  nian_ling INT         NOT NULL,
  gonghao   VARCHAR(32) NOT NULL UNIQUE,
  jiru_date VARCHAR(32)
);
```

If you cannot adjust the existing database structure, you can create a `db-metadata.json` file for annotation:

```
{
  "type": "database",
  "description": "Database table structure annotation, use definitions here as standard",
  "tables": {
    "tbl_yonghu": {
      "label": "User table",
      "description": "Store system user information",
      "required": [
        "id",
        "xin_bie",
        "nian_ling",
        "gonghao"
      ],
      "columns": {
        "id": {
          "label": "User ID",
          "type": "int",
          "description": "Unique identifier"
        },
        "xin_bie": {
          "label": "Gender",
          "type": "char(2)",
          "description": "User gender",
          "enum": ["Male", "Female"]
        },
        "nian_ling": {
          "label": "Age",
          "type": "int",
          "description": "User age"
        },
        "gonghao": {
          "label": "Employee ID",
          "type": "varchar(16)",
          "description": "User's employee ID",
          "unique": true
        },
        "jiru_date": {
          "label": "Join date",
          "type": "varchar(16)",
          "description": "User's join date",
          "format": "date",
          "nullable": true
        }
      }
    }
  }
}
```

**Usage:**

When adding database schema to context, also add this JSON annotation file. Qoder will reference this JSON when understanding the database structure, thereby generating code and SQL more accurately.

## Notes

### Very Large Number of Database Tables

If the database schema is very large (many tables, such as in ERP, CRM scenarios), it may exceed the Agent's context limit.

**Solutions:**

* Export the database schema as multiple SQL files
* Add them to context in batches by adding files
* Only add tables relevant to the current task

### Database Dialect

Qoder automatically adds the database dialect as a comment to the database schema, so you don't need to manually declare the database type.

**If you need to manually add SQL files to context:**

* You can add comments in the SQL file to indicate the database type, for example: `-- dialect: mysql`
* You can also declare the database type in the global [AGENTS.md](http://AGENTS.md)
