# PostgreSQL - Query

> 在 PostgreSQL 数据库上执行 SQL 查询。

Source: https://docs.sommatic.ai/zh/nodes/integrations.postgresql.query/

- 标识: `integrations.postgresql.query`
- 类别: 集成
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

在 PostgreSQL 数据库上执行 SQL 查询。

连接你的 PostgreSQL 实例，使用 $1、$2 位置参数绑定运行参数化查询以防止 SQL 注入。兼容 PostgreSQL、CockroachDB、Supabase 和 Neon。

**操作：**
- **SELECT：** 通过过滤、连接和聚合从表中获取行。无结果时走 empty 端口。
- **INSERT：** 向表中添加新记录，支持 RETURNING。
- **UPDATE：** 修改满足条件的现有记录。
- **DELETE：** 从表中删除记录。
- **函数：** 调用 PL/pgSQL 函数和存储过程。
- **DDL：** 执行 CREATE、ALTER、DROP 语句以管理 schema。

## 配置

- `connection_id` (string, 必填): PostgreSQL 实例的凭据。接受 `connection-string`（postgres:// URI）或 `basic-auth`（用户名 + 密码 + 主机 + 数据库）类型的凭据。
- `sql` (string, 必填, 支持表达式): 要执行的 SQL 语句（例如“SELECT * FROM users WHERE id = $1”）。
- `parameters` (array, 可选): 用于 $1、$2 等位置参数绑定的值数组。

## 输出端口

- `out` (默认): 查询返回的结果行
- `empty`: 未返回任何行
- `error`: 执行期间发生错误

## 输入契约

- `connection_id` (string, 必填)
- `sql` (string, 必填)
- `parameters` (array, 可选)

## 输出契约

- `result` (array<object>, 可选): 查询返回的行数组

## 在表达式中

后续节点可通过 `$("PostgreSQL - Query").item.json.<路径>` 读取此节点输出中的内容（请把 `PostgreSQL - Query` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("PostgreSQL - Query").item.json.result` (array) = `[…] (1)`: 查询返回的行数组


## 工作原理

在 PostgreSQL 上执行一条带位置参数 `$1, $2…` 的 SQL 语句，并将结果行放在 `result` 中返回；没有返回行时经 `empty` 输出。

1. 解析节点配置中的表达式。`connection_id`、`sql` 为空时从输入项读取。参数依次从 `params`、`parameters`、输入项的 `params` 或 `parameters` 读取。
2. 解析连接：`connection_id` 中的 `postgres://` / `postgresql://` URI、`connection-string` 凭据，或包含 `username`、`password`、`host`、`database`、`port`（默认 5432）的 `basic-auth` / `object` 凭据。
3. 建立连接，使用参数执行 `sql`（单个非数组值会被包装成数组），然后关闭连接。
4. 有结果行时经 `out` 返回 `{ result: rows }`，无结果行时经 `empty` 返回 `{ result: [] }`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-find-customer",
  "label": "Find customer",
  "operator_slug": "integrations.postgresql.query",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "sql": "SELECT id, email, created_at FROM customers WHERE email = $1",
    "parameters": [
      "{{ $json.email }}"
    ]
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": [
      {
        "id": 42,
        "email": "ana@example.com",
        "created_at": "2026-11-20T15:04:05.000Z"
      }
    ]
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

语句至少返回了一行。

```json
{
  "result": [
    {
      "id": 42,
      "email": "ana@example.com",
      "created_at": "2026-11-20T15:04:05.000Z"
    }
  ]
}
```

### `empty`

语句没有返回行，包括不带 `RETURNING` 的 INSERT、UPDATE 和 DELETE。

```json
{
  "result": []
}
```

### `error`

校验、凭据解析、连接或语句执行失败。

```json
{
  "error": "relation \"customers\" does not exist"
}
```

## 代码中的行为

- `params`: `parameters` 的未声明别名，二者同时设置时优先使用它。
- `connection_id`: 使用连接字符串时启用 TLS 但不校验证书（localhost 不使用 TLS）。使用结构化凭据时，仅当凭据配置设置了 `ssl` 才启用 TLS。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `connection_id is required` | `error` | 配置和输入项中都没有凭据。 |
| `sql query is required` | `error` | `sql` 为空。 |
| `bind message supplies <n> parameters, but prepared statement "" requires <m>` | `error` | 参数数量与 `sql` 中的 `$n` 占位符数量不一致。 |
| `Credential <connection_id> has unsupported type '<type>' for integrations.postgresql.query. Use 'connection-string' or 'basic-auth'.` | `error` | 本节点不支持该凭据类型。 |

## 说明与限制

- 如需写操作经 `out` 输出，请使用 `RETURNING`；否则它们总是经 `empty` 输出。
- 每次运行都会新建并关闭连接，节点不会重试。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "integrations.postgresql.query",
  "name": "PostgreSQL - Query",
  "category": "integrations",
  "version": "1.0.0",
  "description": "Execute SQL queries on PostgreSQL databases.\n\n  Connect your PostgreSQL instance and run parameterized queries with $1, $2 positional binding for SQL injection prevention. Compatible with PostgreSQL, CockroachDB, Supabase, and Neon.\n\n  **Operations:**\n  - **SELECT:** Fetch rows from tables with filters, joins, and aggregations. Returns empty port when no results.\n  - **INSERT:** Add new records to tables with RETURNING support.\n  - **UPDATE:** Modify existing records matching a condition.\n  - **DELETE:** Remove records from tables.\n  - **Functions:** Call PL/pgSQL functions and stored procedures.\n  - **DDL:** Execute CREATE, ALTER, DROP statements for schema management.",
  "capabilities": [
    "sql",
    "database",
    "postgres",
    "postgresql"
  ],
  "group": [
    {
      "key": "postgresql",
      "name": "PostgreSQL",
      "icon_url": "/icons/integrations/postgresql/postgresql.svg"
    }
  ],
  "icon_url": "/icons/integrations/postgresql/postgresql.svg",
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "PostgreSQL Credential",
        "description": "Credential for your PostgreSQL instance. Accepts credentials of type `connection-string` (postgres:// URI) or `basic-auth` (username + password + host + database).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "connection-string",
            "basic-auth"
          ],
          "types": [
            "postgres"
          ]
        }
      },
      "sql": {
        "type": "string",
        "title": "SQL Query",
        "description": "The SQL statement to execute (e.g., \"SELECT * FROM users WHERE id = $1\").",
        "format": "expression",
        "ui_widget": "sql_editor"
      },
      "parameters": {
        "type": "array",
        "title": "Query Parameters",
        "description": "Array of values for positional $1, $2, ... parameter binding."
      }
    },
    "required": [
      "connection_id",
      "sql"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "sql": {
        "type": "string"
      },
      "parameters": {
        "type": "array"
      }
    },
    "required": [
      "connection_id",
      "sql"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "array",
        "items": {
          "type": "object"
        },
        "description": "Array of rows returned by the query"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Rows",
      "description": "Resulting rows from the query",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "Empty",
      "description": "No rows returned",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Error occurred during execution",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "db-io"
  ],
  "tags": [
    "sql",
    "database"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://sommatic.ai",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "PostgreSQL Credential",
      "description": "Credential for your PostgreSQL instance. Accepts credentials of type `connection-string` (postgres:// URI) or `basic-auth` (username + password + host + database).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "connection-string",
          "basic-auth"
        ],
        "types": [
          "postgres"
        ]
      }
    },
    "sql": {
      "type": "string",
      "title": "SQL Query",
      "description": "The SQL statement to execute (e.g., \"SELECT * FROM users WHERE id = $1\").",
      "format": "expression",
      "ui_widget": "sql_editor"
    },
    "parameters": {
      "type": "array",
      "title": "Query Parameters",
      "description": "Array of values for positional $1, $2, ... parameter binding."
    }
  },
  "required": [
    "connection_id",
    "sql"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "sql": {
      "type": "string"
    },
    "parameters": {
      "type": "array"
    }
  },
  "required": [
    "connection_id",
    "sql"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "array",
      "items": {
        "type": "object"
      },
      "description": "Array of rows returned by the query"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Rows",
    "description": "Resulting rows from the query",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "Empty",
    "description": "No rows returned",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Error occurred during execution",
    "is_default": false,
    "supports_condition": false
  }
]
```
