> ## 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.

# Rust 拡張の例

> Rust SDK を使用した vsql_rot13 および vsql_rational の参照実装から学ぶ

Rust SDK リポジトリには 2 つの参照拡張が同梱されています。関数のみの最小限の例と、算術演算、順序付け、ハッシュ化を備えた完全なカスタム型です。

**ソース:** [vsql-rust-sdk](https://github.com/villagesql/vsql-rust-sdk/tree/main/examples) の `examples/`

***

## vsql\_rot13 — 関数のみの拡張

考えられる最も単純な Rust 拡張です。STRING を受け取り STRING を返す 1 つの VDF です。

**使用例:**

```sql theme={null}
INSTALL EXTENSION vsql_rot13;

SELECT rot13('Hello, World!');
-- 'Uryyb, Jbeyq!'

SELECT rot13(rot13('Hello, World!'));
-- 'Hello, World!' (rot13 is its own inverse)

SELECT rot13(NULL);
-- NULL
```

### ディレクトリ構造

```
vsql_rot13/
├── Cargo.toml          # cdylib crate, depends on villagesql
├── manifest.json       # Extension metadata
├── src/
│   └── lib.rs          # Implementation + extension! registration
└── mysql-test/
    └── t/*.test        # MTR test cases
```

### 実装

**ファイル: `src/lib.rs`**

```rust theme={null}
use villagesql::{InValue, VdfReturn};

/// SQL: rot13(s STRING) -> STRING
fn rot13_impl(args: &[InValue]) -> VdfReturn {
    match args.first() {
        Some(InValue::String(s)) => VdfReturn::string(rot13(s)),
        Some(InValue::Null) | None => VdfReturn::null(),
        _ => VdfReturn::error("rot13: expected a STRING argument"),
    }
}

fn rot13(s: &str) -> String {
    s.chars()
        .map(|c| match c {
            'a'..='m' | 'A'..='M' => (c as u8 + 13) as char,
            'n'..='z' | 'N'..='Z' => (c as u8 - 13) as char,
            _ => c,
        })
        .collect()
}

villagesql::extension! {
    funcs: [
        villagesql::func!(rot13_impl, "rot13",
            [villagesql::Type::String] -> villagesql::Type::String),
    ]
}
```

**主要なパターン:**

* VDF は `&[InValue]` を受け取り `VdfReturn` を返します。どちらも安全な Rust の列挙型です
* NULL は両側で第一級のバリアントです。直接パターンマッチできます
* `extension!` マクロは、サーバーがロード時に呼び出す C エントリポイントを生成します
* `func!` は SQL シグネチャを宣言します。引数と戻り値の型には `villagesql::Type::*` を使用します

### マニフェスト

**ファイル: `manifest.json`**

```json theme={null}
{
  "name": "vsql_rot13",
  "version": "0.1.0",
  "description": "Example VillageSQL extension: provides vsql_rot13(STRING) -> STRING",
  "author": "VillageSQL Community",
  "license": "GPL-2.0"
}
```

***

## vsql\_rational — 算術演算を備えたカスタム型

完全なカスタム型です。有理数を約分された形の `(numerator, denominator)` として格納し、算術関数、順序付け、ハッシュ化を備えています。

**使用例:**

```sql theme={null}
INSTALL EXTENSION vsql_rational;

CREATE TABLE measurements (id INT, ratio rational);
INSERT INTO measurements VALUES
    (1, '1/2'),
    (2, '2/4'),   -- normalizes to '1/2' on storage
    (3, '-3/6'),  -- normalizes to '-1/2'
    (4, '0/1');

SELECT id, ratio FROM measurements ORDER BY ratio;

SELECT rational_add('1/2', '1/3');     -- '5/6'
SELECT rational_mul('2/3', '3/4');     -- '1/2'
SELECT rational_to_real('22/7');       -- 3.142857...
```

### バイナリ格納形式

`rational` は **16 バイト** (リトルエンディアン) を格納します。

* バイト 0–7: 分子 (`i64`)
* バイト 8–15: 分母 (`i64`)

値は常に、正の分母を持つ約分された形 (GCD = 1) で格納されます。

### 型システム関数

**ファイル: `src/lib.rs`**

この型は 4 つの操作を登録します。エンコード (文字列 → バイト)、デコード (バイト → 文字列)、比較 (ORDER BY 用)、ハッシュ (インデックス作成用) です。

```rust theme={null}
pub fn rational_encode(s: &str) -> Result<Vec<u8>, String> {
    let (num_s, den_s) = s
        .split_once('/')
        .ok_or_else(|| format!("rational: expected 'n/d', got {s:?}"))?;
    let num: i64 = num_s.trim().parse().map_err(|e| format!("numerator: {e}"))?;
    let den: i64 = den_s.trim().parse().map_err(|e| format!("denominator: {e}"))?;
    let (n, d) = normalize(i128::from(num), i128::from(den))
        .ok_or_else(|| "rational: zero or overflowing denominator".to_string())?;
    Ok(to_bytes(n, d))
}

pub fn rational_decode(b: &[u8]) -> Result<String, String> {
    if b.len() < BYTES {
        return Err(format!("rational: expected {} bytes, got {}", BYTES, b.len()));
    }
    let (n, d) = from_bytes(b);
    Ok(format!("{n}/{d}"))
}

pub fn rational_compare(a: &[u8], b: &[u8]) -> std::cmp::Ordering {
    let (n1, d1) = from_bytes(a);
    let (n2, d2) = from_bytes(b);
    // Cross-multiply; denominators are always positive after normalization
    let lhs = i128::from(n1) * i128::from(d2);
    let rhs = i128::from(n2) * i128::from(d1);
    lhs.cmp(&rhs)
}
```

### VDF の実装

カスタム型を受け取る VDF は `InValue::Custom(&[u8])` を受け取り、バイトを自身でデコードします。

```rust theme={null}
fn rational_add_impl(args: &[InValue]) -> VdfReturn {
    match (arg(args, 0), arg(args, 1)) {
        (Ok(Some((n1, d1))), Ok(Some((n2, d2)))) => {
            match normalize(
                i128::from(n1) * i128::from(d2) + i128::from(n2) * i128::from(d1),
                i128::from(d1) * i128::from(d2),
            ) {
                Some((n, d)) => VdfReturn::Binary(to_bytes(n, d)),
                None => VdfReturn::error("rational_add: overflow"),
            }
        }
        (Err(e), _) | (_, Err(e)) => VdfReturn::error(format!("rational_add: {e}")),
        _ => VdfReturn::null(),
    }
}
```

### 登録

`extension!` マクロは、型とその関数の両方を 1 つの宣言で登録します。

```rust theme={null}
villagesql::extension! {
    funcs: [
        villagesql::func!(rational_add_impl, "rational_add",
            [villagesql::custom!("rational"), villagesql::custom!("rational")]
            -> villagesql::custom!("rational"),
            deterministic: true),
        villagesql::func!(rational_sub_impl, "rational_sub",
            [villagesql::custom!("rational"), villagesql::custom!("rational")]
            -> villagesql::custom!("rational"),
            deterministic: true),
        villagesql::func!(rational_mul_impl, "rational_mul",
            [villagesql::custom!("rational"), villagesql::custom!("rational")]
            -> villagesql::custom!("rational"),
            deterministic: true),
        villagesql::func!(rational_div_impl, "rational_div",
            [villagesql::custom!("rational"), villagesql::custom!("rational")]
            -> villagesql::custom!("rational"),
            deterministic: true),
        villagesql::func!(rational_numer_impl, "rational_numer",
            [villagesql::custom!("rational")] -> villagesql::Type::Int,
            deterministic: true),
        villagesql::func!(rational_denom_impl, "rational_denom",
            [villagesql::custom!("rational")] -> villagesql::Type::Int,
            deterministic: true),
        villagesql::func!(rational_to_real_impl, "rational_to_real",
            [villagesql::custom!("rational")] -> villagesql::Type::Real,
            deterministic: true),
    ],
    types: [
        villagesql::custom_type!(
            type_name: "rational",
            persisted_length: 16,
            max_decode_buffer_length: 42,
            encode: rational_encode,
            decode: rational_decode,
            compare: rational_compare,
            hash: rational_hash,
            default: "0/1",
        ),
    ]
}
```

**主要なパターン:**

* `villagesql::custom!("name")` は、引数または戻り値としてカスタム型を参照します
* `custom_type!` は、型をその encode/decode/compare/hash 関数とともに登録します
* `default: "0/1"` は組み込みのデフォルト値です。サーバーは型の初期化時にこの文字列に対して `encode()` を呼び出すため、有効な値である必要があります
* `persisted_length` は `encode()` が返すバイト長と一致する必要があります
* `deterministic: true` により、オプティマイザは定数呼び出しを畳み込むことができます

***

## 主要な実装パターン

| パターン            | 使用法                                             |
| --------------- | ----------------------------------------------- |
| **VDF シグネチャ**   | `fn impl(args: &[InValue]) -> VdfReturn`        |
| **NULL の処理**    | `InValue::Null` と `None` を明示的にパターンマッチします        |
| **エラー報告**       | `VdfReturn::error("message")` はステートメントを中止します    |
| **カスタム型のエンコード** | `Result<Vec<u8>, String>` を返します                 |
| **カスタム型のデコード**  | `Result<String, String>` を返します                  |
| **型を認識する引数**    | `func!` 内で `villagesql::custom!("name")` を使用します |
| **登録**          | 単一の `extension!` ブロックで関数と型を宣言します                |

***

## テスト

どちらの例も、C++ 拡張と同様に MTR (MySQL Test Runner) を使用します。

```bash theme={null}
cd /path/to/villagesql/build/mysql-test
./mysql-test-run.pl --suite=vsql_rot13
./mysql-test-run.pl --suite=vsql_rational
```

`--record` を使用して期待される結果を生成または更新します。

***

## 次のステップ

<CardGroup cols={2}>
  <Card title="Rust で拡張機能を作成する" icon="rust" href="/docs/ja/mysql-8.4/0.0.5/rust-sdk">
    SDK のインストール、ビルド、および extension! マクロ
  </Card>

  <Card title="Rust カスタム型" icon="cube" href="/docs/ja/mysql-8.4/0.0.5/rust-custom-types">
    encode、decode、compare、hash の詳細
  </Card>

  <Card title="Rust API リファレンス" icon="book" href="/docs/ja/mysql-8.4/0.0.5/rust-api-reference">
    InValue、VdfReturn、およびマクロの API サーフェス
  </Card>

  <Card title="サンプルソース" icon="github" href="https://github.com/villagesql/vsql-rust-sdk/tree/main/examples">
    vsql\_rot13 および vsql\_rational の完全なソース
  </Card>
</CardGroup>
