> ## 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::column_store 和 vsql::preview::storage 功能允许扩展程序为其某个自定义类型向 InnoDB 注册自定义的二进制磁盘布局。

本页中的功能处于预览阶段：其 API 并不稳定，声明这些功能的扩展程序需要 `vsql_allow_preview_extensions = ON` 才能安装。有关如何启用预览层和注册功能，请参阅[预览功能](https://villagesql.com/docs/zh/extensions/build/preview-capabilities)。

列存储允许扩展直接向 InnoDB 注册自定义的磁盘布局，用于其自定义类型之一，而不是将该类型的数据通过行的 VARBINARY 负载进行路由。当您的类型需要一种 VARBINARY 无法表达的磁盘布局时，请使用它——例如，必须存储在专用页中的打包浮点数组。这是一个功能特性：它启用了新的存储布局，而不是用于现有布局的调整旋钮。

> [!WARNING]
>
> 列存储是一个预览版 ABI——正在积极开发中，并且可能在不同版本之间发生变化。它目前仅涵盖行级持久性；自定义存储的列只接受[自定义索引](https://villagesql.com/docs/zh/extensions/build/custom-indexes.md)，普通索引会被拒绝，错误为 `ERROR 3219 (HY000): InnoDB: Indexing for types with column storage is supported only with custom index.`

## 声明功能

两个预览功能协同工作：

* `vsql::preview::storage` — 开放对 InnoDB 存储基础设施的访问（微事务、段、页）。在文件范围内声明一个 `StorageCapability`。
* `vsql::preview::column_store` — 将每个类型的存储实现绑定到扩展的自定义类型之一。在文件范围内使用 `make_column_store<Ctx>(TYPE).…build()` 声明一个 `ColumnStoreCapability`。

两者都必须传递给 `make_extension()` 上的 `.with()`：

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

namespace storage = vsql::preview_storage;
using vsql::preview_storage_builder::ColumnStoreCapability;
using vsql::preview_storage_builder::make_column_store;
using vsql::preview_storage_builder::StorageCapability;

struct MyCtx {
  storage::Space::Ref space = 0;
  storage::Segment::PageRef root_page = storage::Page::INVALID_REF;
};

static auto STORAGE = StorageCapability{};

static constexpr auto kMyStorage =
    make_column_store<MyCtx>(MY_TYPE)
        .create<&MyStorage::create>()
        .drop<&MyStorage::drop>()
        .load<&MyStorage::load>()
        .insert<&MyStorage::insert>()
        .select<&MyStorage::select>()
        .mark_delete<&MyStorage::mark_delete>()
        .purge<&MyStorage::purge>()
        .build();

static auto COLUMN_STORE = ColumnStoreCapability().column_store(kMyStorage);

using namespace vsql;

VEF_GENERATE_ENTRY_POINTS(
    make_extension()
        .with(STORAGE)
        .with(COLUMN_STORE)
        .type(MY_TYPE))
```

`make_column_store<MyCtx>(MY_TYPE)` 将实现绑定到在同一扩展上注册的一个自定义类型。所有七个槽位都必须在 `build()` 时提供，因为每个槽位都映射到列生命周期中的一个不同点，InnoDB 在正常操作期间会到达该点。

## 七个存储函数

每个函数都接受 `storage::Column::StorageCtx<MyCtx>*`，其 `user()` 访问器返回扩展的每个列状态，并且其 `arena()` 提供服务器管理的辅助对象分配。每个函数在成功时返回 `false`，在出错时返回 `true`，并将消息写入 `error_msg`（容量 `error_msg_len`）。服务器会将该消息写入其错误日志；失败的 `create` 或 `insert` 会使语句失败，错误为 `ERROR 3219 (HY000): InnoDB: Custom type operation failed. See server error log for details.`

```cpp theme={null}
// CREATE TABLE / ALTER TABLE ADD COLUMN.
// col_len is the type's persisted length. Reserve segments here and store
// space + root_page in ctx->user() so DML functions can reach them.
bool create(storage::Column::StorageCtx<MyCtx>*, storage::Space::Ref,
            storage::Segment::TrxRef, uint32_t col_len,
            char* error_msg, uint32_t error_msg_len);

// DROP TABLE / ALTER TABLE DROP COLUMN.
// Release any segments reserved in create(). Arena memory is freed by the
// server after this call returns.
bool drop(storage::Column::StorageCtx<MyCtx>*, storage::Segment::TrxRef,
          char* error_msg, uint32_t error_msg_len);

// Called when the server reattaches to existing storage (e.g. after restart).
// Recover space and root_page from the StorageRef set in create().
bool load(storage::Column::StorageCtx<MyCtx>*, storage::Column::StorageRef,
          char* error_msg, uint32_t error_msg_len);

// INSERT. col_data is the encoded value; rowid_prefix identifies the owning
// row. Write into your storage layout and return a Column::Ref the server
// stores in the row payload in place of the value bytes.
bool insert(storage::Column::StorageCtx<MyCtx>*, storage::MtrCtx::Ref,
            storage::Segment::TrxRef, storage::Column::Data col_data,
            storage::Column::Data rowid_prefix, storage::Column::Ref* col_ref,
            char* error_msg, uint32_t error_msg_len);

// SELECT. Given the Column::Ref produced by insert, populate col_data and
// rowid_prefix, and report the writing transaction and delete-mark status.
bool select(storage::Column::StorageCtx<MyCtx>*, storage::MtrCtx::Ref,
            storage::Column::Ref, storage::Column::Data* col_data,
            storage::Column::Data* rowid_prefix, storage::Segment::TrxRef*,
            bool* delete_marked, char* error_msg, uint32_t error_msg_len);

// DELETE (in-transaction). Set or clear the delete-mark flag. The actual
// bytes must remain readable until purge() runs.
bool mark_delete(storage::Column::StorageCtx<MyCtx>*, storage::MtrCtx::Ref,
                 storage::Segment::TrxRef, storage::Column::Ref,
                 bool delete_mark, char* error_msg, uint32_t error_msg_len);

// InnoDB purge. Reclaim storage for entries whose deleting transaction is
// no longer visible to any active snapshot.
bool purge(storage::Column::StorageCtx<MyCtx>*, storage::MtrCtx::Ref,
           storage::Segment::TrxRef, storage::Column::Ref,
           char* error_msg, uint32_t error_msg_len);
```

`mark_delete` 和 `purge` 是不同的，因为 InnoDB MVCC 要求已删除的行在 purge 运行之前对旧的快照保持可读。

## 每个列的上下文和 Arena

C++ SDK 在调用 `create` 或 `load` 之前，默认构造 `MyCtx`——在进入您的函数时，`ctx->user()` 已经填充。`MyCtx` 必须是默认可构造的；C++ SDK 使用不带参数的 `T()` 调用。

直接使用 `ctx->user()` 来初始化状态。不要调用 `ctx->arena().construct<MyCtx>()`——这将分配第二个、未使用的实例，并且 `ctx->user()` 不指向它。

```cpp theme={null}
bool MyStorage::create(storage::Column::StorageCtx<MyCtx>* ctx,
                       storage::Space::Ref space, storage::Segment::TrxRef trx,
                       uint32_t col_len,
                       char* error_msg, uint32_t error_msg_len) {
  storage::Segment::PageRef root;
  if (storage::Segment::create(space, 1, trx, root) != storage::Error::SUCCESS) {
    snprintf(error_msg, error_msg_len, "%s", storage::last_error().data());
    return true;
  }

  ctx->user()->space = space;
  ctx->user()->root_page = root;
  // Encode space and root into StorageRef so load() can recover both.
  ctx->set_ref((static_cast<storage::Column::StorageRef>(space) << 32) |
               static_cast<storage::Column::StorageRef>(root));
  return false;
}
```

`load` 遵循相同的模式——`ctx->user()` 预先填充，并且 `storage_ref` 携带由 `ctx->set_ref()` 在 `create` 中存储的打包值：

```cpp theme={null}
bool MyStorage::load(storage::Column::StorageCtx<MyCtx>* ctx,
                     storage::Column::StorageRef storage_ref,
                     char* error_msg, uint32_t error_msg_len) {
  ctx->user()->space =
      static_cast<storage::Space::Ref>(storage_ref >> 32);
  ctx->user()->root_page =
      static_cast<storage::Segment::PageRef>(storage_ref & 0xFFFFFFFF);
  ctx->set_ref(storage_ref);
  return false;
}
```

仅使用 `ctx->arena()` 来分配辅助对象，这些对象太大或太动态，无法直接嵌入到 `MyCtx` 中。C++ SDK 在 `drop` 返回后，无论 `drop` 是否成功，都会自动销毁 arena 并调用 `~MyCtx()`。

## InnoDB 访问实用程序

包含 `<villagesql/preview/storage_api.h>` 以获取 InnoDB 原语。所有页面的读取和写入都必须在微事务中进行：

```cpp theme={null}
storage::MtrCtx mtr;
storage::MtrCtx::Ref mtr_ref = mtr.start();
if (mtr_ref == nullptr) { /* OOM — handle error */ return true; }
// ... page operations ...
mtr.commit();
```

提交微事务会释放页面锁，并写入重做日志记录，以使更改持久化。

**段** 在 `create` 时保留——有关完整的设置模式，请参见上面“每个列的上下文”中的 `create` 和 `load` 示例。在 DML 操作期间，从根页面获取段引用以分配新页面：

```cpp theme={null}
storage::Page root;
root.load(ctx->user()->space, ctx->user()->root_page,
          storage::Page::Latch::EXCLUSIVE, mtr_ref);
storage::Segment::Ref seg = storage::Segment::get_header(root, 0);
storage::Page data_page;
data_page.load_new(seg, mtr_ref);  // allocates a fresh page
```

**页面** 使用共享锁读取，使用独占锁写入。将 `mtr_ref` 传递给写入调用，以便 InnoDB 记录更改：

```cpp theme={null}
// Read: a shared latch
storage::Page page;
page.load(ctx->user()->space, page_num, storage::Page::Latch::SHARED, mtr_ref);
uint32_t v = page.read_integer_4(storage::Page::HEADER_SIZE + offset);
```

```cpp theme={null}
// Write: an exclusive latch. Do not load a page for writing
// when the same mini-transaction already holds it with a shared latch.
storage::Page page;
page.load(ctx->user()->space, page_num, storage::Page::Latch::EXCLUSIVE, mtr_ref);
page.write_integer_4(storage::Page::HEADER_SIZE + offset, v, mtr_ref);
```

页面布局常量：

| 常量 | 值 | 备注 |
| - | - | - |
| `storage::Page::HEADER_SIZE` | `38` | 扩展数据从此偏移量开始。 |
| `storage::Page::TRAILER_SIZE` | `8` | 不要写入 `page_size - TRAILER_SIZE` 之后。 |
| `storage::Page::get_size(space)` | 运行时 | 使用它来代替硬编码的 16384。 |

页面访问器会拒绝位于标头或尾部区域内的偏移量：发布构建版本会跳过该读取或写入，而未定义 `NDEBUG` 的构建版本会触发 `assert` 失败。InnoDB 使用这些字节范围用于其自身的簿记和校验和。


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