Skip to main content
Glama
andyWang1688

sql-query-mcp

import_table_file

Imports a local CSV or XLSX file into an existing database table. Specify connection, table, and file path to load data.

Instructions

Import a local CSV or XLSX file into an existing table.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connection_idYes
table_nameYes
file_pathYes
schemaNo
databaseNo
sheet_nameNo

Implementation Reference

  • Core handler logic for import_table_file: reads CSV/XLSX, validates against target table, builds insert query, executes insert, and audits the result.
    def import_table_file(
        self,
        connection_id: str,
        table_name: str,
        file_path: str,
        schema: Optional[str] = None,
        database: Optional[str] = None,
        sheet_name: Optional[str] = None,
    ) -> Dict[str, object]:
        started = time.perf_counter()
        config = None
        namespace = None
        file_extension = Path(file_path).suffix.lower()
        selected_sheet_name = None
        inserted_row_count = 0
    
        try:
            config = self._registry.get_connection_config(connection_id)
            namespace = resolve_namespace(config, schema=schema, database=database)
            headers, rows, selected_sheet_name = _read_file(Path(file_path), sheet_name)
            if not rows:
                raise QueryExecutionError("文件没有可导入的数据行。")
            if config.engine == "hive" and len(rows) > HIVE_IMPORT_MAX_ROWS:
                raise QueryExecutionError(
                    f"Hive 导入最多支持 {HIVE_IMPORT_MAX_ROWS} 行;大文件请使用 Hive LOAD DATA、外部表或已有数据入湖链路。"
                )
    
            with self._registry.connection_from_config(config) as (conn, adapter):
                _apply_statement_timeout(adapter, conn, self._settings.statement_timeout_ms)
                description = adapter.describe_table(conn, namespace.value, table_name)
                if not description:
                    raise QueryExecutionError(
                        f"未找到表 {namespace.value}.{table_name},或当前用户没有访问权限"
                    )
                table_columns = [item["column_name"] for item in description["columns"]]
                _validate_headers(headers, table_columns)
                query = adapter.build_insert_query(namespace.value, table_name, headers)
                _execute_insert(conn, config.engine, query, rows)
    
            inserted_row_count = len(rows)
            duration_ms = _elapsed_ms(started)
            self._audit.log(
                tool="import_table_file",
                connection_id=connection_id,
                success=True,
                duration_ms=duration_ms,
                row_count=inserted_row_count,
                extra=_build_audit_extra(
                    config,
                    namespace,
                    table_name,
                    file_extension,
                    selected_sheet_name,
                ),
            )
            return {
                "connection_id": connection_id,
                "engine": config.engine,
                namespace.field_name: namespace.value,
                "table_name": table_name,
                "inserted_row_count": inserted_row_count,
                "duration_ms": duration_ms,
                "file_extension": file_extension,
                "sheet_name": selected_sheet_name,
            }
        except Exception as exc:
            duration_ms = _elapsed_ms(started)
            sanitized = sanitize_error_message(str(exc))
            self._audit.log(
                tool="import_table_file",
                connection_id=connection_id,
                success=False,
                duration_ms=duration_ms,
                row_count=inserted_row_count,
                error=sanitized,
                extra=_build_audit_extra(
                    config,
                    namespace,
                    table_name,
                    file_extension,
                    selected_sheet_name,
                ),
            )
            raise QueryExecutionError(sanitized) from exc
  • FastMCP tool registration via @mcp.tool() decorator, defining the tool name and parameters (connection_id, table_name, file_path, schema, database, sheet_name).
    @mcp.tool()
    def import_table_file(
        connection_id: str,
        table_name: str,
        file_path: str,
        schema: Optional[str] = None,
        database: Optional[str] = None,
        sheet_name: Optional[str] = None,
    ) -> dict:
        """Import a local CSV or XLSX file into an existing table."""
    
        return _run_tool(
            lambda: importer.import_table_file(
                connection_id,
                table_name,
                file_path,
                schema,
                database,
                sheet_name,
            )
        )
  • Helper function _read_file that dispatches to _read_csv or _read_xlsx based on file extension.
    def _read_file(path: Path, sheet_name: Optional[str]) -> Tuple[List[str], List[Tuple[object, ...]], Optional[str]]:
        extension = path.suffix.lower()
        if extension == ".csv":
            if sheet_name:
                raise QueryExecutionError("CSV 文件不支持 sheet_name 参数。")
            return _read_csv(path)
        if extension == ".xlsx":
            return _read_xlsx(path, sheet_name)
        raise QueryExecutionError("仅支持 .csv 和 .xlsx 文件导入。")
  • Helper function _read_csv to parse CSV files.
    def _read_csv(path: Path) -> Tuple[List[str], List[Tuple[object, ...]], Optional[str]]:
        with path.open("r", encoding="utf-8-sig", newline="") as handle:
            reader = csv.reader(handle)
            try:
                headers = next(reader)
            except StopIteration as exc:
                raise QueryExecutionError("文件表头不能为空。") from exc
            rows = [_normalize_row(row, len(headers)) for row in reader]
        return headers, rows, None
  • Helper function _read_xlsx to parse XLSX files using openpyxl.
    def _read_xlsx(path: Path, sheet_name: Optional[str]) -> Tuple[List[str], List[Tuple[object, ...]], Optional[str]]:
        if load_workbook is None:
            raise QueryExecutionError("缺少 openpyxl 依赖,请先安装项目依赖。")
        workbook = load_workbook(path, read_only=True, data_only=True)
        try:
            if sheet_name:
                if sheet_name not in workbook.sheetnames:
                    raise QueryExecutionError(f"XLSX 文件中不存在 sheet: {sheet_name}")
                worksheet = workbook[sheet_name]
            else:
                worksheet = workbook.worksheets[0]
            rows_iter = worksheet.iter_rows(values_only=True)
            try:
                header_row = next(rows_iter)
            except StopIteration as exc:
                raise QueryExecutionError("文件表头不能为空。") from exc
            headers = ["" if value is None else str(value) for value in header_row]
            rows = [_normalize_row(list(row), len(headers)) for row in rows_iter]
            return headers, rows, worksheet.title
        finally:
            workbook.close()
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided; description does not disclose behavioral traits such as whether data is appended or overwritten, file size limits, or required permissions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single sentence, no redundant information. Efficient and front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 6 parameters and no output schema or annotations, the description is insufficient. It omits context about optional parameters, file format details, and expected behavior for common scenarios.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Input schema has 0% parameter descriptions, and the tool description adds no detail about parameters. The agent gets no information beyond the schema field names.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description states specific verb 'Import' and resource 'local CSV or XLSX file into an existing table.' It clearly distinguishes from sibling tools like describe_table or run_select, which do not perform file imports.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use or avoid this tool. Does not mention prerequisites (e.g., connection must exist) or compare to alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/andyWang1688/sql-query-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server