> ## Documentation Index
> Fetch the complete documentation index at: https://villagesql.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 문 이벤트

> vsql::preview::statement_event 기능은 각 쿼리 실행이 끝난 후 확장 프로그램의 핸들러를 실행하며, 쿼리 텍스트, 타이밍, 행 수, 연결 식별 정보를 전달합니다.

이 페이지의 기능은 미리보기 단계입니다. API는 안정적이지 않으며, 이 기능을 선언하는 확장 프로그램은 설치 시 `vsql_allow_preview_extensions = ON`이 필요합니다. 미리보기 계층을 활성화하고 기능을 등록하는 방법은 [미리보기 기능](https://villagesql.com/docs/ko/extensions/build/preview-capabilities)을 참조하세요.

문 이벤트 기능(`vsql::preview::statement_event`)은 각 쿼리 실행이 완료된 후 확장 프로그램이 제공한 핸들러를 실행합니다. 서버는 쿼리 자체의 스레드에서 핸들러를 동기적으로 호출하고 실행 메타데이터 — 쿼리 텍스트, 타이밍, 행 개수, 연결 식별 정보, 그리고 옵티마이저 품질 지표를 전달합니다. 느린 쿼리 로깅, 감사 또는 메트릭 수집에 사용하세요.

기능 이름 `VEF_PREVIEW_STATEMENT_EVENT_NAME`은 `"vsql::preview::statement_event"`입니다.

## 기능 선언

파일 범위에서 발동 단계와 핸들러 함수로 인스턴스화된 `StatementEventCapability`을 선언하고 `.with()`에 전달합니다:

```cpp theme={null}
#include <villagesql/preview/statement_event.h>
#include <villagesql/vsql.h>

namespace se = vsql::preview_statement_event;

static void on_statement(const se::StatementEventArgs &args,
                         se::StatementEventResult &result) {
  // inspect args; optionally write an advisory message via result
}

static se::StatementEventCapability<VEF_STATEMENT_EVENT_POSTEXECUTE,
                                    &on_statement>
    g_statement_event;

VEF_GENERATE_ENTRY_POINTS(
    make_extension()
        .with(g_statement_event))
```

첫 번째 템플릿 인수는 발동 단계이며, `vef_statement_event_phase_t` 값입니다. `VEF_STATEMENT_EVENT_POSTEXECUTE`는 쿼리 실행이 완료된 후 성공 또는 실패와 관계없이 발동하며, 이 버전에서 구현된 유일한 단계입니다. 다른 `vef_statement_event_phase_t` 값은 예약되어 있으며, 그중 하나에 대한 핸들러를 선언하면 서버가 `INSTALL EXTENSION`을 거부합니다.

## 핸들러 인수

`StatementEventArgs`는 완료된 쿼리의 읽기 전용 뷰입니다. POSTEXECUTE 단계에서는 모든 필드가 채워져 있습니다. 주요 접근자:

| 접근자 | 의미 |
| - | - |
| `query()` | 쿼리 텍스트, `string_view`로. 서버가 문의 재작성된 형태를 가지고 있는 경우, 이것이 그 형태입니다 — 일반 로그와 슬로우 쿼리 로그가 기록하는 것과 동일한, 민감 정보가 가려진(마스킹된) 텍스트입니다. |
| `query_time_secs()` | 실제 실행 시간, 초 단위. |
| `lock_time_secs()` | 락을 기다리는 데 소요된 시간, 초 단위. |
| `rows_sent()`, `rows_examined()`, `rows_affected()` | 행 카운터. |
| `user()`, `client_ip()`, `connection_id()` | 연결 식별 정보. |
| `schema()` | 기본 스키마, 또는 선택된 것이 없으면 `NULL`. |
| `status()` | 성공 시 `0`, 그렇지 않으면 MySQL 오류 코드. |
| `warning_count()` | 문이 실행되는 동안 발생한 노트와 경고의 수. 문이 실패한 경우에는 오류 전에 발생한 수. |
| `digest_text()` | 유사한 쿼리를 그룹화하기 위한 정규화된 쿼리 형태. |
| `no_index_used()` | 쿼리가 사용 가능한 인덱스 없이 실행되었을 때 `true`. |
| `digest_hash()` | 64자의 소문자 16진수로 된 문 다이제스트 — `performance_schema`가 `DIGEST`로 노출하는 값. 동일한 문을 그룹화하기 위한 간결한 키이며, `digest_text()`가 `NULL`일 때는 이 값도 `NULL`입니다. |
| `read_first()`, `read_last()`, `read_key()`, `read_next()`, `read_prev()`, `read_rnd()`, `read_rnd_next()` | 문별 핸들러 행 접근 카운터(슬로우 로그의 `Read_*` 필드). `no_index_used()`가 표시만 하는 접근 방식을 수치화합니다 — 예를 들어 `read_rnd_next()`가 높으면 전체 테이블 스캔을 의미합니다. |
| `client_pid()`, `client_name()`, `program_name()` | 핸드셰이크 시 한 번 전송되는 클라이언트 제공 연결 속성(`_pid`, `_client_name`, `program_name`): 클라이언트의 OS 프로세스 id, 커넥터/드라이버 라이브러리(예: `libmysql`, `mysql-connector-j`), 애플리케이션 이름(예: `mysql`, `mysqldump`). 클라이언트가 해당 속성을 보내지 않은 경우 각각 `NULL`입니다. |

`query()`는 재작성된 형태가 존재하는 경우 그것을 반환하므로, 자격 증명을 담은 문은 일반 로그와 슬로우 쿼리 로그가 이미 민감 정보를 가리는 방식과 일치하게 비밀이 평문이 아닌 난독화된 상태로 도착합니다: `SET PASSWORD`, `CREATE`/`ALTER USER ... IDENTIFIED BY`, `CHANGE REPLICATION SOURCE ... SOURCE_PASSWORD`, 그리고 `CREATE SERVER ... OPTIONS(PASSWORD ...)`. 재작성 규칙이 없는 문은 그대로 전달됩니다.

`query()`, `sqlstate()`, `error_message()`와 같은 문자열 접근자는 핸들러 호출 기간 동안만 유효한 저장소를 가리킵니다 — 핸들러가 반환된 후에도 필요하면 바이트를 복사하세요.

`StatementEventResult::error_msg(fmt, ...)`은 printf 형식의 메시지를 작성합니다. POSTEXECUTE 단계에서는 이 메시지가 권고용입니다: 서버가 로깅하지만 클라이언트에 전파하지 않습니다.

## 완전한 예제

[`vsql_slow_query_log`](https://github.com/villagesql/villagesql-server/tree/main/villagesql/test-extensions/vsql-slow-query-log)
테스트 확장 프로그램의 축약된 형태입니다. 이는 실행 시간이 임계값을 초과하는 각 쿼리를 로깅하며, 문 이벤트 기능을 런타임 구성을 위한 [시스템 변수](https://villagesql.com/docs/ko/extensions/build/preview-server-variables.md#system-variables)와 결합합니다:

```cpp theme={null}
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <mutex>

#include <villagesql/preview/statement_event.h>
#include <villagesql/preview/sys_var.h>
#include <villagesql/vsql.h>

using namespace vsql;
namespace sv = vsql::preview_sys_var;
namespace se = vsql::preview_statement_event;

static bool g_enabled;
static long long g_threshold_ms;
static char *g_log_filename;
static std::mutex g_log_mutex;

static void slow_query_hook(const se::StatementEventArgs &args,
                            se::StatementEventResult &result) {
  if (!g_enabled) return;
  if (args.query_time_secs() * 1000.0 < static_cast<double>(g_threshold_ms))
    return;

  time_t now = static_cast<time_t>(args.query_start_utime() / 1000000);
  char ts[32];
  struct tm tm_utc;
  gmtime_r(&now, &tm_utc);
  strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%SZ", &tm_utc);

  std::lock_guard<std::mutex> lock(g_log_mutex);
  FILE *f = fopen(g_log_filename, "a");
  if (f == nullptr) {
    result.error_msg("failed to open '%s': %s", g_log_filename,
                     strerror(errno));
    return;
  }

  fprintf(f, "# Time: %s\n", ts);
  fprintf(f, "# User@Host: %s @ %s  Id: %lu\n", args.user() ? args.user() : "",
          args.client_ip() ? args.client_ip() : "", args.connection_id());
  fprintf(f,
          "# Schema: %s  Query_time: %.6f  Lock_time: %.6f"
          "  Rows_sent: %llu  Rows_examined: %llu\n",
          args.schema() ? args.schema() : "", args.query_time_secs(),
          args.lock_time_secs(), (unsigned long long)args.rows_sent(),
          (unsigned long long)args.rows_examined());
  fprintf(f, "SET timestamp=%llu;\n", (unsigned long long)now);
  auto q = args.query();
  fprintf(f, "%.*s;\n", (int)q.size(), q.data());
  fclose(f);
}

static auto SYS_VARS = sv::make_capability({
    sv::make_bool("enabled", "Enable the slow query log", &g_enabled, false),
    sv::make_int("threshold_ms", "Minimum execution time to log, in ms",
                 &g_threshold_ms, 1000, 0, 3600000),
    sv::make_str("log_file", "Path to the slow query log file",
                 &g_log_filename, "/tmp/vsql_slow_query.log")});

static se::StatementEventCapability<VEF_STATEMENT_EVENT_POSTEXECUTE,
                                    &slow_query_hook>
    STATEMENT_EVENT;

VEF_GENERATE_ENTRY_POINTS(
    make_extension().with(SYS_VARS).with(STATEMENT_EVENT))
```

### SQL에서 활성화

미리보기 계층이 활성화된 상태에서(참조: [미리보기 계층 활성화](https://villagesql.com/docs/ko/extensions/build/preview-capabilities#enabling-the-preview-tier)), 확장 프로그램을 빌드하고, 그 `.veb` 파일을 `veb_dir`에 복사하고, 설치한 다음, 시스템 변수를 통해 구성합니다:

```sql theme={null}
INSTALL EXTENSION vsql_slow_query_log;
SET GLOBAL vsql_slow_query_log.enabled = ON;
SET GLOBAL vsql_slow_query_log.threshold_ms = 500;
```

임계값보다 느린 각 쿼리는 구성된 로그 파일에 추가됩니다:

```
# Time: 2026-06-22T22:53:44Z
# User@Host: root @   Id: 27
# Schema:   Query_time: 0.605084  Lock_time: 0.000000  Rows_sent: 1  Rows_examined: 1
SET timestamp=1782168824;
SELECT SLEEP(0.6);
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.