← 返回 Skills 市场
hanxweb

sql-linker

作者 CoderHanX · GitHub ↗ · v1.0.4 · MIT-0
cross-platform ⚠ pending
207
总下载
0
收藏
0
当前安装
5
版本数
在 OpenClaw 中安装
/install sql-linker
功能描述
Use this skill whenever you need to query, insert, update, or delete database records. Triggers include: (1) querying database data with SELECT statements an...
使用说明 (SKILL.md)

Important: All scripts/ paths are relative to this skill directory. Run with: cd {skill_dir} && python scripts/sql_linker.py ... Or use the cwd parameter of execute_shell_command.


SQL-Linker — Multi-Database CRUD + Audit / 多数据库增删查改 + 审计


概述 / Overview

(中文) SQL-Linker 提供跨数据库的 CRUD 操作能力,支持 MySQL、PostgreSQL、SQLite 三种主流数据库。内置审计日志模块,每次操作自动记录操作人身份、IP、SQL 语句、操作时间,确保数据可溯源、安全可控。

(English) SQL-Linker provides cross-database CRUD operations, supporting MySQL, PostgreSQL, and SQLite, with a built-in audit trail module that automatically records operator identity, IP, SQL statements, and timestamps for full traceability and compliance.

支持的数据库 / Supported Databases

数据库 驱动 安装命令
MySQL mysql-connector-python pip install mysql-connector-python
PostgreSQL psycopg2 pip install psycopg2
SQLite 内置 (sqlite3) 无需安装

配置 / Configuration

(中文) 配置文件位于工作区 .sql_linker/ 目录下:

.sql_linker/
├── config.yaml         # 数据库连接配置(不含密码)
├── audit_config.json   # 审计配置 + 用户名(发布时排除)
└── .env                # 敏感凭据(发布时排除)

(English) Configuration lives in .sql_linker/ at the workspace root:

.sql_linker/
├── config.yaml         # Database connection (no passwords)
├── audit_config.json   # Audit config + username (excluded from publishing)
└── .env                # Sensitive credentials (excluded from publishing)

config.yaml

(中文) type 字段指定数据库类型:

type: mysql                  # 数据库类型:mysql | postgres | sqlite
host: localhost
port: 3306
database: mydb
user: admin001
password_env: DB_PASSWORD   # .env 中的键名
read_only: false            # true = 禁止所有写操作
max_rows: 1000             # 查询结果行数上限
timeout: 30                 # 连接超时(秒)

(English) The type field specifies the database type:

type: mysql                  # mysql | postgres | sqlite
host: localhost
port: 3306
database: mydb
user: admin001
password_env: DB_PASSWORD   # Key name in .env
read_only: false           # true = block all write operations
max_rows: 1000             # Query result limit
timeout: 30                # Connection timeout (seconds)

audit_config.json

(中文) 审计配置 + 用户名。首次使用前需运行 init_user("你的姓名") 注册用户名

{
  "username": "HR",
  "audit": {
    "enabled": true,
    "log_table": "sql_audit_log",
    "log_select": false,
    "mask_values": true
  }
}
字段 说明
username 操作人姓名,通过 init_user() 自动写入
audit.enabled true = 开启审计
audit.log_table 审计表名
audit.log_select true = SELECT 也记录(默认关闭)
audit.mask_values true = SQL 参数值脱敏(用 ? 替代)

(English) Audit config + username. Run init_user("YourName") on first use to register the username:

{
  "username": "HR",
  "audit": {
    "enabled": true,
    "log_table": "sql_audit_log",
    "log_select": false,
    "mask_values": true
  }
}
Field Description
username Operator name, written by init_user()
audit.enabled true = enable audit
audit.log_table Audit table name
audit.log_select true = also log SELECT (default off)
audit.mask_values true = mask SQL parameter values with ?

SQLite 配置示例 / SQLite Config Example

(中文)

type: sqlite
database: ./data/mydb.sqlite
read_only: false
max_rows: 1000
timeout: 30

(English)

type: sqlite
database: ./data/mydb.sqlite
read_only: false
max_rows: 1000
timeout: 30

.env

(中文)

DB_PASSWORD=your_password_here

(English)

DB_PASSWORD=your_password_here

身份上下文 / Identity Context

(中文) 审计日志需要以下四个字段,优先级如下:

字段 最高优先级 次优先级 最低优先级
user_name CLI 参数(暂无) audit_config.json OPENCLAW_USER env
user_label --user-label CLI flag OPENCLAW_LABEL env auto-detect
ip_address socket 自动检测
session_id --session-id CLI flag OPENCLAW_SESSION env auto-detect

(English) Four fields are required for audit logging, with the following priority:

Field Highest Priority Second Priority Lowest Priority
user_name CLI param (not yet) audit_config.json OPENCLAW_USER env
user_label --user-label CLI flag OPENCLAW_LABEL env auto-detect
ip_address socket auto-detect
session_id --session-id CLI flag OPENCLAW_SESSION env auto-detect

⚠️ (中文)CLI flag 优先级最高,确保审计可溯源时应使用 --user-label--session-id ⚠️ CLI flags take highest priority — always use --user-label and --session-id for real traceability.


Python API

初始化 + 注册用户名 / Initialize + Register Username

(中文)

from sql_linker import SQLLinker

linker = SQLLinker()
linker.connect()

# 首次使用:注册用户名(写入 audit_config.json,持久化)
linker.init_user("HR")

(English)

from sql_linker import SQLLinker

linker = SQLLinker()
linker.connect()

# First use: register username (persisted to audit_config.json)
linker.init_user("HR")

自动身份上下文 / Auto Identity Context

(中文)

# 自动获取:IP 从 socket 检测,username 从 audit_config.json 读取
linker.set_user_context_auto()

# 或手动完整传入(从消息 metadata 获取 label 和 session_id)
linker.set_user_context(
    user_name=linker._username,           # 从配置读
    user_label="openclaw-control-ui",    # 从消息 metadata
    ip_address="192.168.1.48",          # socket 自动检测
    session_id="agent:hr:dashboard:..."  # 从消息 context
)

(English)

# Auto: IP from socket, username from audit_config.json
linker.set_user_context_auto()

# Or manual full context (from message metadata)
linker.set_user_context(
    user_name=linker._username,           # from config
    user_label="openclaw-control-ui",    # from message metadata
    ip_address="192.168.1.48",          # socket auto-detect
    session_id="agent:hr:dashboard:..."  # from message context
)

查询 SELECT / Query

(中文)

results = linker.query(
    "SELECT id, name FROM users WHERE status = %s",
    ("active",)
)
# 返回字典列表;失败时返回空列表
# SELECT 操作是否记录取决于 config 中 audit.log_select

(English)

results = linker.query(
    "SELECT id, name FROM users WHERE status = %s",
    ("active",)
)
# Returns list of dicts; empty list on failure
# SELECT is logged only if audit.log_select is true in audit_config.json

插入 INSERT / Insert

(中文)

row_id = linker.insert("users", {
    "name": "张三",
    "email": "[email protected]",
    "status": "active"
})
# 返回自增 ID 或影响行数;自动写审计日志

(English)

row_id = linker.insert("users", {
    "name": "张三",
    "email": "[email protected]",
    "status": "active"
})
# Returns auto-increment ID or rowcount; audit log written automatically

批量插入 / Batch Insert

(中文)

data = [
    {"name": "李四", "email": "[email protected]", "status": "active"},
    {"name": "王五", "email": "[email protected]", "status": "active"},
]
count = linker.batch_insert("users", data)

(English)

data = [
    {"name": "李四", "email": "[email protected]", "status": "active"},
    {"name": "王五", "email": "[email protected]", "status": "active"},
]
count = linker.batch_insert("users", data)

更新 UPDATE / Update

(中文)

count = linker.update(
    "users",
    {"status": "inactive", "updated_at": "2024-01-01"},
    "id = %s AND status = %s",
    (1, "active")
)
# WHERE 条件(不含 WHERE 关键字);自动写审计日志

(English)

count = linker.update(
    "users",
    {"status": "inactive", "updated_at": "2024-01-01"},
    "id = %s AND status = %s",
    (1, "active")
)
# WHERE clause (no WHERE keyword); audit log written automatically

删除 DELETE / Delete

(中文)

count = linker.delete("users", "id = %s AND status = %s", (1, "active"))

(English)

count = linker.delete("users", "id = %s AND status = %s", (1, "active"))

事务控制 / Transaction Control

(中文)

linker.begin()
linker.insert("users", {"name": "test"})
linker.update("products", {"stock": 50}, "id = %s", (1,))
linker.commit()    # 提交 — 或:
# linker.rollback()  # 出错时回滚

(English)

linker.begin()
linker.insert("users", {"name": "test"})
linker.update("products", {"stock": 50}, "id = %s", (1,))
linker.commit()    # Commit — or:
# linker.rollback()  # Roll back on error

只读模式 / Read-Only Mode

(中文)config.yamlread_only: true 时,所有写操作返回 0 并打印警告:

linker.insert("users", {...})   # 只读模式禁止插入
linker.update("users", {...})   # 只读模式禁止更新
linker.delete("users", ...)     # 只读模式禁止删除

(English) When config.yaml has read_only: true, all write operations return 0 and print a warning:

linker.insert("users", {...})   # 只读模式禁止插入 / Read-only mode: insert blocked
linker.update("users", {...})   # 只读模式禁止更新 / Read-only mode: update blocked
linker.delete("users", ...)     # 只读模式禁止删除 / Read-only mode: delete blocked

关闭连接 / Close

(中文)

linker.close()

(English)

linker.close()

审计日志 / Audit Trail

审计表结构 / Audit Table Schema

审计表会在首次写入时自动创建(如果不存在)。结构如下:

CREATE TABLE sql_audit_log (
    id            BIGINT AUTO_INCREMENT PRIMARY KEY,
    log_time      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    user_name     VARCHAR(128)     -- 操作人姓名
    user_label    VARCHAR(128)     -- 会话标签(来源系统)
    ip_address    VARCHAR(64)      -- 客户端 IP
    session_id    VARCHAR(128)     -- OpenClaw session key
    db_type       VARCHAR(32)      -- mysql / postgres / sqlite
    operation     VARCHAR(16)      -- SELECT / INSERT / UPDATE / DELETE / BATCH_INSERT
    table_name    VARCHAR(128)     -- 操作的目标表
    sql_statement TEXT             -- 脱敏后的 SQL
    rows_affected INT              -- 影响行数
    status        VARCHAR(16)      -- SUCCESS / FAILED
    error_msg     TEXT             -- 失败时的错误信息
);

查询审计日志 / Query Audit Logs

(中文)

# 查询某人的所有操作记录
logs = linker._audit.query_logs(
    user_name="HR",
    start_time="2026-05-01 00:00:00",
    end_time="2026-05-31 23:59:59",
    limit=100
)
for row in logs:
    print(row["log_time"], row["operation"], row["table_name"], row["status"])

# 查询某张表的所有操作
logs = linker._audit.query_logs(table_name="users", limit=50)

(English)

# Query all operations by a specific user
logs = linker._audit.query_logs(
    user_name="HR",
    start_time="2026-05-01 00:00:00",
    end_time="2026-05-31 23:59:59",
    limit=100
)
for row in logs:
    print(row["log_time"], row["operation"], row["table_name"], row["status"])

# Query all operations on a specific table
logs = linker._audit.query_logs(table_name="users", limit=50)

初始化审计表 / Initialize Audit Table

(中文)

python scripts/sql_linker.py audit-setup

python scripts/sql_linker.py audit-logs               # 最近 100 条
python scripts/sql_linker.py audit-logs HR           # 按操作人过滤
python scripts/sql_linker.py audit-logs HR 50        # 指定数量

(English)

python scripts/sql_linker.py audit-setup

python scripts/sql_linker.py audit-logs               # Last 100 records
python scripts/sql_linker.py audit-logs HR           # Filter by user
python scripts/sql_linker.py audit-logs HR 50        # With limit

命令行接口 / Command-Line Interface

python scripts/sql_linker.py [flags] \x3Caction> [options]

Flags:
  --user-label \x3Clabel>    Override user_label (for real audit traceability)
  --session-id \x3Cid>       Override session_id  (for real audit traceability)

Actions: query, insert, update, delete, audit-setup, audit-logs

(中文)完整示例(含身份上下文)/ Full example with identity context

# 查询(身份自动检测 / identity auto-detected)
python scripts/sql_linker.py query "SELECT * FROM users LIMIT 10"

# 插入 — 必须传入真实 user_label 和 session_id
python scripts/sql_linker.py \
  --user-label "openclaw-control-ui" \
  --session-id "agent:hr:dashboard:2454324d-1bd5-4e04-9746-1e5df62bb9a7" \
  insert "users" '{"name":"张三","email":"[email protected]"}'

# 更新
python scripts/sql_linker.py \
  --user-label "openclaw-control-ui" \
  --session-id "agent:hr:dashboard:2454324d-..." \
  update "users" '{"status":"inactive"}' "id = 1"

# 删除
python scripts/sql_linker.py \
  --user-label "openclaw-control-ui" \
  --session-id "agent:hr:dashboard:2454324d-..." \
  delete "users" "id = 1"

(English)Full example with identity context

# Query (identity auto-detected)
python scripts/sql_linker.py query "SELECT * FROM users LIMIT 10"

# Insert — always pass real user_label and session_id
python scripts/sql_linker.py \
  --user-label "openclaw-control-ui" \
  --session-id "agent:hr:dashboard:2454324d-1bd5-4e04-9746-1e5df62bb9a7" \
  insert "users" '{"name":"Zhang San","email":"[email protected]"}'

# Update
python scripts/sql_linker.py \
  --user-label "openclaw-control-ui" \
  --session-id "agent:hr:dashboard:2454324d-..." \
  update "users" '{"status":"inactive"}' "id = 1"

# Delete
python scripts/sql_linker.py \
  --user-label "openclaw-control-ui" \
  --session-id "agent:hr:dashboard:2454324d-..." \
  delete "users" "id = 1"

Note / 注意: On Windows, set $env:PYTHONIOENCODING='utf-8' before running queries that return Chinese characters to avoid GBK encoding errors. Windows PowerShell: JSON arguments MUST use double quotes — single quotes cause escape loss.


错误处理 / Error Handling

(中文)

情况 返回值
连接失败 False / 0
SQL 执行失败 自动 rollback,返回 0
查询失败 空列表 []
不支持的数据库类型 抛出 ValueError
审计写入失败 不影响主操作(静默忽略)

(English)

Scenario Return Value
Connection failure False / 0
SQL execution failure auto rollback, returns 0
Query failure empty list []
Unsupported database type raises ValueError
Audit write failure Silent — does not affect main operation

安全建议 / Security Notes

(中文)

做法 原因
参数化查询(%s + tuple) 防止 SQL 注入
.env 存储密码 凭据不进入配置文件
audit_config.json 排除发布 防止用户名和审计配置泄露
mask_values: true SQL 参数值脱敏,防止敏感信息泄露
audit.enabled: true 完整操作追溯,快速定位问题
生产环境开启 read_only: true 阻止意外写操作
审计表禁止 DELETE/UPDATE 权 审计记录不可篡改

(English)

Practice Why
Parameterized queries (%s + tuple) Prevents SQL injection
.env for passwords Keeps credentials out of config files
audit_config.json excluded from publishing Prevents user/audit config leaks
mask_values: true Masks SQL parameter values, prevents data leaks
audit.enabled: true Full operation traceability, fast incident investigation
read_only: true in production Blocks accidental writes
No DELETE/UPDATE on audit table Audit records are tamper-proof
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install sql-linker
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /sql-linker 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.4
sql-linker 1.0.4 changelog: - Updated identity context priority rules for audit logging; CLI flags (`--user-label`, `--session-id`) now have highest precedence, followed by config and environment variables. - SKILL.md documentation revised to clarify traceability configuration and priority order of identity information sources.
v1.0.3
**Version 1.0.3 Changelog** - Added built-in audit trail module (`scripts/sql_audit.py`) for logging operator identity, IP, SQL statements, and operation time. - Expanded configuration: introduced `audit_config.json` to manage audit options and username registration. - New user registration method (`init_user`) and automatic or manual identity context setting. - SQL audit logs can record all operations or only write queries, with optional SQL parameter masking for compliance. - Updated documentation to reflect audit features and configuration changes.
v1.0.2
**sql-linker v1.0.2 changelog** - Adds support for PostgreSQL and SQLite databases, in addition to MySQL. - Updated configuration to allow database type selection (`mysql`, `postgres`, `sqlite`). - Documentation improved to include multi-database usage and configuration examples. - Python and CLI usage expanded for cross-database compatibility. - Read-only and error handling features retained for all supported databases.
v1.0.1
- Documentation updated to include full Chinese/English bilingual instructions. - No code changes in this version. - All usage examples, configuration details, and error handling now appear in both Chinese and English for improved accessibility.
v1.0.0
Initial release of sql-linker: full MySQL CRUD, transaction control, and read-only protection. - Provides Python API for querying, inserting, updating, and deleting MySQL records with parameter binding. - Implements transaction support (begin, commit, rollback) and batch operations. - Enforces read-only mode to block all write operations for safer usage. - Includes command-line interface for direct database manipulation. - Configuration separates credentials and settings for better security.
元数据
Slug sql-linker
版本 1.0.4
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 5
常见问题

sql-linker 是什么?

Use this skill whenever you need to query, insert, update, or delete database records. Triggers include: (1) querying database data with SELECT statements an... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 207 次。

如何安装 sql-linker?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install sql-linker」即可一键安装,无需额外配置。

sql-linker 是免费的吗?

是的,sql-linker 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

sql-linker 支持哪些平台?

sql-linker 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 sql-linker?

由 CoderHanX(@hanxweb)开发并维护,当前版本 v1.0.4。

💬 留言讨论