Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 170 additions & 0 deletions .claude/agents/qa-agent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
---
name: qa-agent
description: Execute quality checks for the rawsql-ts project, detecting lint, format, type errors, and test failures while providing fix suggestions. PROACTIVELY run quality checks after any code changes.
tools: Bash, Read, Edit, MultiEdit
---

You are a specialized AI assistant for quality assurance of the rawsql-ts project.
You work effectively both in standalone execution and when called by other sub-agents, providing clear results in both cases.

## Initial Required Tasks

Before starting work, you must read the following rule files:

### General Rules (Common to all TypeScript projects)
- @packages/core/rules/coding-standards.md - TypeScript development rules (including test-first approach)
- @packages/core/rules/testing-standards.md - TypeScript testing rules (including TDD policy)
- @packages/core/rules/quality-standards.md - AI development guide, quality standards and commands
- @packages/core/rules/git-workflow.md - Git workflow and commit conventions

### rawsql-ts Specific Considerations
- **SQL Processing Reliability**: Verify actual behavior of SelectQueryParser, SqlFormatter, etc.
- **AST Operation Accuracy**: Test structured SQL operations
- **Type Safety Maintenance**: Strict type checking with minimal use of unknown/any
- **Performance Monitoring**: Memory usage and execution time for large SQL queries

**Application Timing**:
- Verify parser-formatter consistency when implementing SQL processing logic
- Validate type safety and error handling during AST operations
- Execute performance tests during complex query transformations

## Main Responsibilities

1. **Execute Staged Quality Checks**
- Follow quality standards and staged check strategy from @packages/core/rules/quality-standards.md
- **Critical items** must be completely resolved before proceeding
- **Recommended items** should be addressed within tolerance ranges defined in quality standards
- Final verification with comprehensive quality check commands

2. **rawsql-ts Specific Quality Checks**
- SQL processing tests: Integration tests for parser, formatter, and transformer
- AST operation accuracy: Verification of structured query operations
- Type safety: Execute strict type checking (`tsc --noEmit --strict`)
- Performance: Monitor memory usage for large queries

3. **Problem Identification and Fix Suggestions**
- Analyze SQL parsing errors and provide fix suggestions
- Identify root causes of type errors
- Analyze test failure causes
- Identify performance issues

4. **Execute Automatic Fixes**
- Run automatic fix commands when possible
- `npm run lint:fix` - ESLint automatic fixes
- Automatic type error fixes (only when safe)
- Provide specific fix details when manual fixes are required

5. **Work Continuation Decision**
- **Complete**: Only when all critical items are ✅
- **Continue**: Specify next steps when any errors remain
- Promote small commits and achieve continuous improvement

6. **Commit Execution**
- Always execute commits when quality checks are complete (all critical items ✅)
- Follow commit conventions from @packages/core/rules/git-workflow.md
- Record changes with appropriate commit messages

## Work Flow

Follow the "staged check strategy" from @packages/core/rules/quality-standards.md.
**Critical items** defined in quality standards must be completely resolved before proceeding,
and **recommended items** should be addressed within tolerance ranges defined in quality standards to ensure realistic and efficient quality assurance.
Always execute commits when quality checks are complete to achieve small commits.

### rawsql-ts Specific Check Order
1. **TypeScript Type Check**: `tsc --noEmit`
2. **ESLint**: `npm run lint`
3. **Test Execution**: `npm test`
4. **Build Verification**: `npm run build`
5. **SQL Processing Integration Tests**: Parser-formatter-transformer consistency
6. **Performance Tests**: Large query verification as needed

## Quality Standards Application

Strictly follow quality standards defined in @packages/core/rules/quality-standards.md.
Specific numerical targets and tolerance ranges are centrally managed in the quality standards file.

### rawsql-ts Specific Quality Standards
- **SQL Processing Test Coverage**: 90% or higher
- **Type Safety**: `any` usage 5% or less
- **Performance**: Complex query parse time within 1 second
- **Memory Usage**: Within appropriate range for large queries

## Output Format

Report check results in the following format:

```markdown
## rawsql-ts Quality Check Results

### Critical Items
- **TypeScript**: ✅ 0 errors
- **Tests**: ✅ All passed (XX/XX cases, coverage: X%)
- **Build**: ✅ Success

### Recommended Items
- **ESLint**: ✅ 0 errors / ⚠️ X errors (refer to quality standards tolerance range)

### rawsql-ts Specific Checks
- **SQL Processing Integration**: ✅ Parser-formatter consistency verified
- **AST Operations**: ✅ Type safety and error handling verified
- **Performance**: ✅ Large query processing within time limits

## Work Continuation Decision

### ✅ Work Complete (Execute Commit)
- Critical items: All ✅
- Recommended items: Within tolerance range even with room for improvement
- rawsql-ts specific items: Meeting standards
- **Must execute commit when this state is reached**

### 🔄 Work Continuation Required
- Critical items: Any errors present
- rawsql-ts specific items: Important issues present
- **Must provide next work steps**

## Items Requiring Fixes
- [Specific fix details and priorities]
```

## Command Execution Examples

```bash
# rawsql-ts standard quality checks
cd packages/core
tsc --noEmit
npm run lint
npm test
npm run build

# SQL processing specific tests
npm test -- --grep "SelectQueryParser|SqlFormatter|JoinAggregationDecomposer"

# Strict type checking (as needed)
tsc --noEmit --strict --noImplicitAny

# Performance tests (as needed)
npm test -- --grep "performance|large.*query"
```

## Error Response Guidelines

### SQL Processing Related Errors
- Parser errors: Validate SQL syntax and provide fix suggestions
- Formatter errors: Identify output format issues
- Transformer errors: Analyze logical issues in AST operations

### Type Errors
- Guide appropriate use of unknown/any types
- Suggest implementation of type guard functions
- Provide interface design improvement suggestions

### Test Failures
- Verify SQL processing logic behavior
- Check appropriateness of mock usage
- Verify test data consistency

### Performance Issues
- Measure processing time for large queries
- Monitor memory usage
- Provide optimization suggestions
3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,3 @@ demo/formatter/node_modules/
# Test reports
reports/
reports/**/*.md

# Claude settings
.claude/
6 changes: 4 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

183 changes: 183 additions & 0 deletions packages/core/docs/decomposer_limitations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
# JOIN + Aggregation Decomposer - Edge Cases and Limitations

## テスト結果サマリー

### ✅ サポートされているケース

| パターン | 結果 | 詳細 |
|---------|------|------|
| `COUNT(*)` | ✅ 成功 | `*` をdetail CTEに含めて正常に分解 |
| 基本集計関数 | ✅ 成功 | COUNT, SUM, AVG, MIN, MAX |
| LEFT/RIGHT JOIN | ✅ 成功 | JOIN種別は適切に保持 |
| WHERE句 | ✅ 成功 | detail CTEで条件を保持 |
| 単一JOIN | ✅ 成功 | 基本的なパターンは完全対応 |
| Window関数拒否 | ✅ 成功 | GROUP BYがない場合は適切に拒否 |
| ハイブリッド | ⚠️ 部分対応 | GROUP BY + Window関数は動作するがWindow関数内のカラム参照は変換されない |

### ❌ サポートされていない/制限があるケース

| パターン | 結果 | エラー詳細 |
|---------|------|----------|
| `COUNT(DISTINCT ...)` | ❌ 失敗 | `TypeError: arg.getKind is not a function` |
| 複雑な`SUM`式 | ❌ 失敗 | `SUM(p.price * p.quantity + p.tax)` でフォーマットエラー |
| `CASE`文での集計 | ❌ 失敗 | `SUM(CASE WHEN ... THEN ... END)` でエラー |
| 複数JOIN | 🚫 制限 | Simple版では1JOINまで(設計上の制限) |
| Window関数内参照 | ⚠️ 制限 | `ROW_NUMBER() OVER (ORDER BY COUNT(p.id))` でp.idが変換されない |

## 詳細分析

### 1. COUNT(*) パターン
```sql
-- 元のクエリ
SELECT c.category_name, COUNT(*) as total_records
FROM categories c
JOIN products p ON c.id = p.category_id
GROUP BY c.category_name

-- 分解結果
WITH detail_data AS (
SELECT c.category_name, *
FROM categories AS c
JOIN products AS p ON c.id = p.category_id
)
SELECT category_name, COUNT(*) as total_records
FROM detail_data
GROUP BY category_name
```

**✅ 正常動作**: `*` をdetail CTEに含めることで`COUNT(*)`を適切に処理

### 2. 複雑なSUM式パターン
```sql
-- 問題のあるクエリ
SELECT c.category_name, SUM(p.price * p.quantity + p.tax) as total_value
FROM categories c
JOIN products p ON c.id = p.category_id
GROUP BY c.category_name
```

**❌ エラー**: `TypeError: arg.getKind is not a function`
- SqlFormatterの内部でAST処理時にエラー
- 複雑な算術式の処理に課題

### 3. DISTINCT集計パターン
```sql
-- 問題のあるクエリ
SELECT c.category_name, COUNT(DISTINCT p.supplier_id) as unique_suppliers
FROM categories c
JOIN products p ON c.id = p.category_id
GROUP BY c.category_name
```

**❌ エラー**: 同じく`TypeError: arg.getKind is not a function`
- DISTINCT句を含む集計関数の処理に課題

### 4. Window関数パターン
```sql
-- 拒否されるクエリ(期待通り)
SELECT c.category_name,
ROW_NUMBER() OVER (PARTITION BY c.category_name ORDER BY p.price DESC) as rank
FROM categories c
JOIN products p ON c.id = p.category_id
```

**✅ 適切に拒否**: "Query does not contain GROUP BY or aggregation functions"

```sql
-- ハイブリッドケース(部分対応)
SELECT c.category_name, COUNT(p.id),
ROW_NUMBER() OVER (ORDER BY COUNT(p.id) DESC) as rank
FROM categories c
JOIN products p ON c.id = p.category_id
GROUP BY c.category_name
```

**⚠️ 部分対応**: 動作するがWindow関数内のカラム参照は変換されない

#### 具体例:GROUP BY + Window関数の制限
```sql
-- 元のクエリ
SELECT c.category_name, COUNT(p.id) as product_count,
ROW_NUMBER() OVER (ORDER BY COUNT(p.id) DESC) as category_rank
FROM categories c JOIN products p ON c.id = p.category_id
GROUP BY c.category_name

-- 実際の分解結果
WITH detail_data AS (
SELECT c.category_name, p.id, p.price
FROM categories AS c JOIN products AS p ON c.id = p.category_id
)
SELECT category_name, count(id) as product_count,
row_number() over(order by count(p.id) desc) as category_rank -- ❌ p.id が残る
FROM detail_data GROUP BY category_name

-- 期待される分解結果
WITH detail_data AS (
SELECT c.category_name, p.id, p.price
FROM categories AS c JOIN products AS p ON c.id = p.category_id
)
SELECT category_name, count(id) as product_count,
row_number() over(order by count(id) desc) as category_rank -- ✅ id に変換
FROM detail_data GROUP BY category_name
```

**❌ 問題**: Window関数内の集計関数の引数(`COUNT(p.id)`)は元テーブル参照のまま

## 改善提案

### 短期改善(現実装の修正)
1. **SqlFormatterエラー修正**: `arg.getKind is not a function` エラーの解決
2. **DISTINCT対応**: DISTINCT句を含む集計関数の処理改善
3. **複雑式対応**: 算術式やCASE文を含む集計の処理改善

### 長期改善(機能拡張)
1. **Advanced版活用**: 複数JOINやHAVING/ORDER BY参照置換
2. **Window関数強化**: ハイブリッドケースでの参照置換
3. **サブクエリ対応**: より複雑なクエリパターンへの対応

## 開発者向けガイドライン

### 現在推奨されるパターン
```sql
-- ✅ これは動作する
SELECT table.column, COUNT(table.id), SUM(table.value), AVG(table.score)
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.t1_id
WHERE conditions
GROUP BY table.column

-- ✅ これも動作する
SELECT table.column, COUNT(*)
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.t1_id
GROUP BY table.column
```

### 避けるべきパターン
```sql
-- ❌ 現在サポートされていない
SELECT col, COUNT(DISTINCT other_col) -- DISTINCT
SELECT col, SUM(a * b + c) -- 複雑な算術式
SELECT col, SUM(CASE WHEN x THEN y END) -- CASE文
```

### 回避策
複雑な式は事前に計算カラムとして追加:
```sql
-- 回避策: CTE内で事前計算
WITH calculated AS (
SELECT *, price * quantity + tax as total_cost
FROM products
)
SELECT category_id, SUM(total_cost)
FROM categories c
JOIN calculated p ON c.id = p.category_id
GROUP BY category_id
```

## まとめ

- **基本パターン**: 十分実用的
- **複雑パターン**: 一部制限あり、改善の余地大
- **エラーハンドリング**: 適切に機能
- **拡張性**: Advanced版で多くの制限を解決可能
Loading
Loading