入门 eslint-plugin-pg
发布: (2026年1月1日 GMT+8 02:45)
2 min read
原文: Dev.to
Source: Dev.to
快速安装
npm install --save-dev eslint-plugin-pg
扁平配置
// eslint.config.js
import pg from 'eslint-plugin-pg';
export default [pg.configs.recommended];
运行 ESLint
npx eslint .
示例输出:
src/users.ts
15:3 error 🔒 CWE-89 OWASP:A03 CVSS:9.8 | Unsafe SQL query detected
Fix: Use parameterized query: client.query('SELECT * FROM users WHERE id = $1', [id])
src/orders.ts
28:5 error 🔒 CWE-772 | pool.connect() without client.release()
Fix: Add client.release() in finally block
规则概览
| 规则 | CWE | 检测内容 |
|---|---|---|
no-unsafe-query | CWE-89 | SQL 注入(通过字符串拼接) |
no-missing-client-release | CWE-772 | 连接池泄漏 |
prevent-double-release | CWE-415 | 双重释放导致崩溃 |
no-transaction-on-pool | CWE-362 | 事务竞争条件 |
prefer-pool-query | CWE-400 | 不必要的 connect/release |
no-unsafe-copy-from | CWE-22 | COPY FROM 中的路径遍历 |
no-unsafe-search-path | CWE-426 | search_path 劫持 |
no-n-plus-one-query | Perf | N+1 查询模式 |
| … | … | 另加 5 条… |
快速收益
之前(SQL 注入)
// ❌ SQL Injection
const query = `SELECT * FROM users WHERE id = '${userId}'`;
await pool.query(query);
之后(参数化查询)
// ✅ Parameterized Query
const query = 'SELECT * FROM users WHERE id = $1';
await pool.query(query, [userId]);
之前(连接泄漏)
// ❌ Connection Leak
const client = await pool.connect();
const result = await client.query('SELECT * FROM users');
return result.rows;
// Missing client.release()!
之后(确保释放)
// ✅ Guaranteed Release
const client = await pool.connect();
try {
const result = await client.query('SELECT * FROM users');
return result.rows;
} finally {
client.release();
}
可用预设
// Security + best practices
pg.configs.recommended;
// All rules enabled
pg.configs.all;
自定义规则
// eslint.config.js
import pg from 'eslint-plugin-pg';
export default [
pg.configs.recommended,
{
rules: {
// Downgrade to warning
'pg/prefer-pool-query': 'warn',
// Increase strictness
'pg/no-unsafe-query': [
'error',
{
allowLiteral: false,
},
],
},
},
];
性能
┌─────────────────────────────────────────────────────┐
│ Benchmark: 1000 files │
├─────────────────────────────────────────────────────┤
│ eslint-plugin-pg: 785ms │
│ 100% precision (0 false positives in tests) │
└─────────────────────────────────────────────────────┘
与其他插件结合
import pg from 'eslint-plugin-pg';
import secureCoding from 'eslint-plugin-secure-coding';
export default [pg.configs.recommended, secureCoding.configs.recommended];
快速参考
# Install
npm install --save-dev eslint-plugin-pg
# Config (eslint.config.js)
import pg from 'eslint-plugin-pg';
export default [pg.configs.recommended];
# Run
npx eslint .
链接
- npm: eslint-plugin-pg
- 完整规则列表: GitHub docs
- Star on GitHub: