> ## 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 Extension Examples

> Learn from the vsql_rot13 and vsql_rational reference implementations using the Rust SDK

Two reference extensions ship in the Rust SDK repository — a minimal function-only example and a complete custom type with arithmetic, ordering, and hashing.

**Source:** `examples/` in [vsql-rust-sdk](https://github.com/villagesql/vsql-rust-sdk/tree/main/examples)

***

## vsql\_rot13 — Function-Only Extension

The simplest possible Rust extension: one VDF that takes a STRING and returns a STRING.

**Usage:**

```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
```

### Directory Structure

```
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
```

### Implementation

**File: `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),
    ]
}
```

**Key patterns:**

* VDFs receive `&[InValue]` and return `VdfReturn` — both are safe Rust enums
* NULL is a first-class variant on both sides; pattern-match it directly
* The `extension!` macro generates the C entry points the server calls at load time
* `func!` declares the SQL signature; argument and return types use `villagesql::Type::*`

### Manifest

**File: `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 — Custom Type with Arithmetic

A complete custom type: rational numbers stored as `(numerator, denominator)` in reduced form, with arithmetic functions, ordering, and hashing.

**Usage:**

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

### Binary Storage Format

`rational` stores **16 bytes** (little-endian):

* Bytes 0–7: numerator (`i64`)
* Bytes 8–15: denominator (`i64`)

Values are always stored in reduced form (GCD = 1) with a positive denominator.

### Type-System Functions

**File: `src/lib.rs`**

The type registers four operations: encode (string → bytes), decode (bytes → string), compare (for ORDER BY), and hash (for indexing).

```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 Implementations

VDFs that take a custom type receive `InValue::Custom(&[u8])` and decode the bytes themselves:

```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(),
    }
}
```

### Registration

The `extension!` macro registers both the type and its functions in a single declaration:

```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",
        ),
    ]
}
```

**Key patterns:**

* `villagesql::custom!("name")` references a custom type as an argument or return
* `custom_type!` registers the type alongside its encode/decode/compare/hash functions
* `default: "0/1"` is the intrinsic default — the server calls `encode()` on this string at type initialization, so it must be a valid value
* `persisted_length` must match the byte length `encode()` returns
* `deterministic: true` lets the optimizer fold constant calls

***

## Key Implementation Patterns

| Pattern                  | Usage                                              |
| ------------------------ | -------------------------------------------------- |
| **VDF signature**        | `fn impl(args: &[InValue]) -> VdfReturn`           |
| **NULL handling**        | Match `InValue::Null` and `None` explicitly        |
| **Error reporting**      | `VdfReturn::error("message")` aborts the statement |
| **Custom type encode**   | Returns `Result<Vec<u8>, String>`                  |
| **Custom type decode**   | Returns `Result<String, String>`                   |
| **Type-aware arguments** | Use `villagesql::custom!("name")` in `func!`       |
| **Registration**         | Single `extension!` block declares funcs and types |

***

## Testing

Both examples use MTR (the MySQL Test Runner) just like C++ extensions:

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

Generate or update expected results with `--record`.

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Creating Extensions in Rust" icon="rust" href="/mysql-8.4/0.0.5/rust-sdk">
    SDK installation, build, and the extension! macro
  </Card>

  <Card title="Rust Custom Types" icon="cube" href="/mysql-8.4/0.0.5/rust-custom-types">
    Deep dive on encode, decode, compare, and hash
  </Card>

  <Card title="Rust API Reference" icon="book" href="/mysql-8.4/0.0.5/rust-api-reference">
    InValue, VdfReturn, and the macro surface
  </Card>

  <Card title="Example Source" icon="github" href="https://github.com/villagesql/vsql-rust-sdk/tree/main/examples">
    vsql\_rot13 and vsql\_rational complete source
  </Card>
</CardGroup>
