# IMean Cassandra ORM (v2)

基于 Zod 的 Cassandra ORM，提供类型安全的 schema 定义、CQL 编译、schema 同步与可选的 ClickHouse 双写。

## 特性
- **类型安全**：基于 Zod 的 schema 验证与类型推断
- **自动 CQL 生成**：CRUD 与查询条件自动编译
- **Schema 同步**：自动创建与迁移表结构（含索引）
- **可选双写**：best‑effort 写入 ClickHouse
- **向量搜索**：支持 ANN 向量检索

## 安装

```bash
npm install imean-cassandra-orm
```

## 快速开始

### 1) 定义 Schema

```ts
import { z } from "zod";
import { defineTable, Types } from "imean-cassandra-orm";

const userSchema = defineTable({
  keyspace: "my_keyspace",
  tableName: "users",
  fields: {
    user_id: z.string(),
    email: z.string().email(),
    name: z.string(),
    age: z.number().int().positive(),
    is_active: z.boolean(),
    metadata: Types.json(),
    created_at: z.date(),
  },
  partitionKey: ["user_id"],
});
```

### 2) 初始化 Client（推荐简化方式）

```ts
import { createClientV2 } from "imean-cassandra-orm";

const { client, shutdown } = await createClientV2({
  cassandra: {
    contactPoints: ["127.0.0.1"],
    localDataCenter: "datacenter1",
  },
  clickhouse: {
    config: {
      host: "127.0.0.1",
      port: 8123,
      username: "default",
      password: "localpass",
      database: "default",
    },
  },
});
```

### 3) 基本 CRUD

```ts
const userModel = client.model(userSchema);
await userModel.syncSchema();

await userModel.insert({
  user_id: "u1",
  email: "u1@example.com",
  name: "Alice",
  age: 20,
  is_active: true,
  metadata: { score: 95 },
  created_at: new Date(),
});

const found = await userModel.findOne({ user_id: "u1" });
await userModel.update({ user_id: "u1" }, { name: "Bob" });
await userModel.delete({ user_id: "u1" });
```

## Schema 同步

```ts
await userModel.syncSchema(); // 自动创建/迁移表结构
```

## 查询语法

详见 `QUERY_SYNTAX.md`。

## 向量搜索

```ts
const vectorSchema = defineTable({
  keyspace: "my_keyspace",
  tableName: "docs",
  fields: {
    id: z.string(),
    embedding: Types.vector(128),
    title: z.string(),
  },
  partitionKey: ["id"],
  indexes: {
    embedding: { similarity_function: "COSINE" },
  },
});

const model = client.model(vectorSchema);
await model.syncSchema();

const results = await model.find(
  { embedding: new Array(128).fill(0).map(() => Math.random()) },
  { limit: 10 }
);
```

## 关闭连接

```ts
await shutdown();
```
