> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-8a08bda2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# DataStore 디버깅

> explain(), 프로파일링, 로깅을 사용해 DataStore 작업을 디버깅합니다

DataStore는 데이터 파이프라인을 이해하고 최적화하는 데 도움이 되는 다양한 디버깅 도구를 제공합니다.

<div id="overview">
  ## 디버깅 도구 개요
</div>

| 도구          | 목적          | 사용 시점         |
| ----------- | ----------- | ------------- |
| `explain()` | 실행 계획 보기    | 실행될 SQL 파악    |
| 프로파일러       | 성능 측정       | 느린 작업 찾기      |
| 로깅          | 실행 세부 정보 보기 | 예상치 못한 동작 디버깅 |

<div id="decision-matrix">
  ## 빠른 의사결정 매트릭스
</div>

| 필요한 작업     | 도구          | 명령어                         |
| ---------- | ----------- | --------------------------- |
| 실행 계획 보기   | `explain()` | `ds.explain()`              |
| 성능 측정      | 프로파일러       | `config.enable_profiling()` |
| SQL 쿼리 디버깅 | 로깅          | `config.enable_debug()`     |
| 위 항목 모두    | 조합          | 아래 참고                       |

<div id="quick-setup">
  ## 빠른 설정
</div>

<div id="enable-all">
  ### 모든 디버깅 기능 활성화
</div>

```python theme={null}
from chdb import datastore as pd
from chdb.datastore.config import config

# 모든 디버깅 활성화
config.enable_debug()        # 상세 로깅
config.enable_profiling()    # 성능 추적

ds = pd.read_csv("data.csv")
result = ds.filter(ds['age'] > 25).groupby('city').agg({'salary': 'mean'})

# 실행 계획 확인
result.explain()

# 프로파일러 보고서 가져오기
from chdb.datastore.config import get_profiler
profiler = get_profiler()
profiler.report()
```

***

<div id="explain">
  ## explain() 메서드
</div>

쿼리를 실행하기 전에 실행 계획을 확인하세요.

```python title="Query" theme={null}
ds = pd.read_csv("data.csv")

query = (ds
    .filter(ds['amount'] > 1000)
    .groupby('region')
    .agg({'amount': ['sum', 'mean']})
)

# 실행 계획 보기
query.explain()
```

```text title="Response" theme={null}
Pipeline:
  Source: file('data.csv', 'CSVWithNames')
  Filter: amount > 1000
  GroupBy: region
  Aggregate: sum(amount), avg(amount)

Generated SQL:
SELECT region, SUM(amount) AS sum, AVG(amount) AS mean
FROM file('data.csv', 'CSVWithNames')
WHERE amount > 1000
GROUP BY region
```

자세한 내용은 [explain() 문서](/ko/products/chdb/debugging/explain)를 확인하십시오.

***

<div id="profiling">
  ## 프로파일링
</div>

각 연산의 실행 시간을 측정합니다.

```python title="Query" theme={null}
from chdb.datastore.config import config, get_profiler

# 프로파일링 활성화
config.enable_profiling()

# 작업 실행
ds = pd.read_csv("large_data.csv")
result = (ds
    .filter(ds['amount'] > 100)
    .groupby('category')
    .agg({'amount': 'sum'})
    .sort('sum', ascending=False)
    .head(10)
    .to_df()
)

# 보고서 확인
profiler = get_profiler()
profiler.report(min_duration_ms=0.1)
```

```text title="Response" theme={null}
Performance Report
==================
Step                          Duration    Calls
----                          --------    -----
read_csv                      1.234s      1
filter                        0.002s      1
groupby                       0.001s      1
agg                           0.089s      1
sort                          0.045s      1
head                          0.001s      1
to_df (SQL execution)         0.567s      1
----                          --------    -----
Total                         1.939s      7
```

자세한 내용은 [프로파일링 가이드](/ko/products/chdb/debugging/profiling)를 참조하십시오.

***

<div id="logging">
  ## 로깅
</div>

상세한 실행 로그를 확인할 수 있습니다.

```python theme={null}
from chdb.datastore.config import config

# 디버그 로깅 활성화
config.enable_debug()

# 작업 실행 시 로그에 표시되는 항목:
# - 생성된 SQL 쿼리
# - 사용된 실행 엔진
# - 캐시 적중/미적중
# - 타이밍 정보
```

로그 출력 예시:

```text theme={null}
DEBUG - DataStore: Creating from file 'data.csv'
DEBUG - Query: SELECT region, SUM(amount) FROM ... WHERE amount > 1000 GROUP BY region
DEBUG - Engine: Using chdb for aggregation
DEBUG - Execution time: 0.089s
DEBUG - Cache: Storing result (key: abc123)
```

자세한 내용은 [로깅 구성](/ko/products/chdb/debugging/logging)을 참조하십시오.

***

<div id="scenarios">
  ## 자주 발생하는 디버깅 시나리오
</div>

<div id="scenario-wrong-results">
  ### 1. 쿼리 결과가 예상과 다를 때
</div>

```python theme={null}
# 1단계: 실행 계획 확인
query = ds.filter(ds['age'] > 25).groupby('city').sum()
query.explain(verbose=True)

# 2단계: SQL 확인을 위한 로깅 활성화
config.enable_debug()

# 3단계: 실행 후 로그 확인
result = query.to_df()
```

<div id="scenario-slow">
  ### 2. 쿼리 실행이 느린 경우
</div>

```python theme={null}
# 1단계: 프로파일링 활성화
config.enable_profiling()

# 2단계: 쿼리 실행
result = process_data()

# 3단계: 프로파일러 보고서 확인
profiler = get_profiler()
profiler.report()

# 4단계: 느린 작업 식별 및 최적화
```

<div id="scenario-engine">
  ### 3. 엔진 선택 이해하기
</div>

```python theme={null}
# 상세 로깅 활성화
config.enable_debug()

# 작업 실행
result = ds.filter(ds['x'] > 10).apply(custom_func)

# 각 작업에 사용된 엔진이 로그에 표시됩니다:
# DEBUG - filter: Using chdb engine
# DEBUG - apply: Using pandas engine (custom function)
```

<div id="scenario-cache">
  ### 4. 캐시 문제 디버깅
</div>

```python theme={null}
# 캐시 작업을 확인하려면 디버그를 활성화하세요
config.enable_debug()

# 첫 번째 실행
result1 = ds.filter(ds['x'] > 10).to_df()
# LOG: 캐시 미스, 쿼리 실행 중

# 두 번째 실행 (캐시 사용 예정)
result2 = ds.filter(ds['x'] > 10).to_df()
# LOG: 캐시 히트, 캐시된 결과 반환

# 예상과 달리 캐싱이 되지 않는 경우 다음을 확인하세요:
# - 작업이 동일한가요?
# - 캐시가 활성화되어 있나요? config.cache_enabled
```

***

<div id="best-practices">
  ## 권장 사항
</div>

<div id="best-practice-1">
  ### 1. 프로덕션이 아니라 개발 환경에서 디버깅하기
</div>

```python theme={null}
# 개발
config.enable_debug()
config.enable_profiling()

# 프로덕션
config.set_log_level(logging.WARNING)
config.set_profiling_enabled(False)
```

<div id="best-practice-2">
  ### 대규모 쿼리를 실행하기 전에 explain()를 사용하세요
</div>

```python theme={null}
# 쿼리 빌드
query = ds.filter(...).groupby(...).agg(...)

# 먼저 실행 계획 확인
query.explain()

# 실행 계획이 적절하면 실행
result = query.to_df()
```

<div id="best-practice-3">
  ### 3. 최적화 전에 프로파일링하기
</div>

```python theme={null}
# 느린 부분을 추측하지 말고 직접 측정하세요
config.enable_profiling()
result = your_pipeline()
get_profiler().report()
```

<div id="best-practice-4">
  ### 4. 결과가 올바르지 않을 때 SQL 확인
</div>

```python theme={null}
# 생성된 SQL 확인
print(query.to_sql())

# 예상 SQL과 비교
# ClickHouse에서 직접 SQL을 실행하여 검증
```

***

<div id="summary">
  ## 디버깅 도구 요약
</div>

| 도구          | 명령어                         | 출력           |
| ----------- | --------------------------- | ------------ |
| 실행 계획 확인    | `ds.explain()`              | 실행 단계 + SQL  |
| 상세 실행 계획 확인 | `ds.explain(verbose=True)`  | + 메타데이터      |
| SQL 보기      | `ds.to_sql()`               | SQL 쿼리 문자열   |
| 디버그 활성화     | `config.enable_debug()`     | 상세 logs      |
| 프로파일링 활성화   | `config.enable_profiling()` | 시간 측정 데이터    |
| 프로파일러 보고서   | `get_profiler().report()`   | 성능 요약        |
| 프로파일러 초기화   | `get_profiler().reset()`    | 시간 측정 데이터 삭제 |

***

<div id="next-steps">
  ## 다음 단계
</div>

* [explain() 메서드](/ko/products/chdb/debugging/explain) - 상세 실행 계획 문서
* [프로파일링 가이드](/ko/products/chdb/debugging/profiling) - 성능 측정
* [로깅 구성](/ko/products/chdb/debugging/logging) - 로그 레벨 및 포맷 설정
