ergokv 0.1.8

Easily store and retrieve data from TiKV with a derive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# ergokv

`DISCLAIMER:` THIS IS ALPHA AS FUCK. (not yet suitable for production)

A Rust library for easy integration with TiKV, providing derive macros
for automatic CRUD operations.

[![](https://img.shields.io/crates/v/ergokv.svg)](https://crates.io/crates/ergokv)
[![](https://docs.rs/ergokv/badge.svg)](https://docs.rs/ergokv)
[![](https://img.shields.io/badge/license-Fair-blue.svg)](https://github.com/luciumagn/ergokv/blob/main/LICENSE)

## Installation

Add this to your `Cargo.toml`:

``` toml
[dependencies]
ergokv = "0.1.8"
```

## Documentation

For detailed documentation, including usage examples and API reference,
please visit:

[<https://docs.rs/ergokv>](https://docs.rs/ergokv)

You can also generate the documentation locally by running:

``` bash
cargo doc --open
```

## Prerequisites

- Rust (edition 2021 or later)
- Protobuf
- GRPC
- TiKV (can be installed via TiUP or automatically via LocalCluster)

### Installing TiKV

There are two primary ways to install TiKV:

1.  Manual Installation with TiUP:

    ``` bash
    # Install TiUP (TiKV's package manager)
    curl --proto '=https' --tlsv1.2 -sSf https://tiup-mirrors.pingcap.com/install.sh | sh

    # Set up TiKV cluster for development
    tiup playground
    ```

2.  Automatic Installation with LocalCluster:

    ``` rust
    use ergokv::LocalCluster;

    // LocalCluster automatically downloads and sets up TiKV if not present
    let cluster = LocalCluster::start(temp_dir).unwrap();
    let client = cluster.spawn_client().await.unwrap();
    ```

    LocalCluster is particularly useful for development and testing, as
    it automatically handles TiKV installation and cluster setup.

## Attributes

The `Store` derive supports several attributes to customize your data
model:

- `@[key]`: Marks the primary key field (exactly one field must have
  this attribute)

  ``` rust
  #[derive(Store)]
  struct User {
      #[key]
      id: Uuid,  // Primary key for identifying the entity
  }
  ```

- `@[unique_index]`: Creates a unique index on a field, allowing
  efficient lookup with guaranteed uniqueness

  ``` rust
  #[derive(Store)]
  struct User {
      #[key]
      id: Uuid,
      #[unique_index]
      username: String,  // 1:1 mapping
  }
  ```

- `@[index]`: Creates a non-unique index on a field, allowing multiple
  entities to share the same indexed value

  ``` rust
  #[derive(Store)]
  struct User {
      #[key]
      id: Uuid,
      #[index]
      department: String,  // Multiple users can be in the same department
  }
  ```

- `@[migrate_from]`: Used for schema migrations, specifying the previous
  version of the struct

  ``` rust
  #[derive(Store)]
  #[migrate_from(OldUser)]
  struct User {
      // Migration logic implementation
  }
  ```

- `@[model_name]`: Used during migrations when the struct name changes

  ``` rust
  #[derive(Store)]
  #[model_name = "User"]  // Helps track model across versions
  struct UserV2 {
      // Struct definition
  }
  ```

## Usage

Basic usage with various index types:

``` rust
use ergokv::Store;
use serde::{Serialize, Deserialize};
use uuid::Uuid;

#[derive(Store, Serialize, Deserialize)]
struct User {
    #[key]
    id: Uuid,
    #[unique_index]
    username: String,
    #[index]
    email: String,
    #[index]
    department: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Use LocalCluster for easy development setup
    let cluster = LocalCluster::start(std::env::temp_dir()).await?;
    let client = cluster.spawn_client().await?;

    // Create a new user
    let user = User {
        id: Uuid::new_v4(),
        username: "johndoe",
        email: "john@example.com",
        department: "Engineering",
    };

    let mut txn = client.begin_optimistic().await?;

    // Save the user
    user.save(&mut txn).await?;
    txn.commit().await?;

    // Lookup methods
    let mut txn = client.begin_optimistic().await?;
    let user_by_username = User::by_username("johndoe", &mut txn).await?;
    let users_in_engineering = User::by_department("Engineering", &mut txn).await?;

    Ok(())
}
```

Longer example:

``` rust
use ergokv::Store;
use serde::{Serialize, Deserialize};
use uuid::Uuid;

#[derive(Store, Serialize, Deserialize)]
struct User {
    #[key]
    id: Uuid,
    #[unique_index]
    username: String,
    email: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Set up TiKV client
    let client = tikv_client::TransactionClient::new(vec!["127.0.0.1:2379"]).await?;

    // Create a new user
    let user = User {
        id: Uuid::new_v4(),
        username: "testuser".to_string(),
        email: "test@example.com".to_string(),
    };

    // Start a transaction
    let mut txn = client.begin_optimistic().await?;

    // Save the user
    user.save(&mut txn).await?;

    // Commit the transaction
    txn.commit().await?;

    // Load the user
    let mut txn = client.begin_optimistic().await?;
    let loaded_user = User::load(&user.id, &mut txn).await?;
    println!("Loaded user: {:?}", loaded_user);

    Ok(())
}
```

## Backup and Restore

The `Store` derive automatically implements backup and restore
functionality for your models:

``` rust
use ergokv::Store;
use serde::{Serialize, Deserialize};
use uuid::Uuid;

#[derive(Store, Serialize, Deserialize)]
struct User {
    #[key]
    id: Uuid,
    #[unique_index]
    username: String,
    email: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = tikv_client::TransactionClient::new(vec!["127.0.0.1:2379"]).await?;

    // Backup all users
    let mut txn = client.begin_optimistic().await?;
    let backup_path = User::backup(&mut txn, "backups/").await?;
    println!("Backup created at: {}", backup_path.display());
    txn.commit().await?;

    // Restore from backup
    let mut txn = client.begin_optimistic().await?;
    User::restore(&mut txn, backup_path).await?;
    txn.commit().await?;

    Ok(())
}
```

Backups are stored as line-delimited JSON files, with automatic
timestamping: `User_1708644444.json`. Each line contains one serialized
instance, making the backups human-readable and easy to process with
standard tools.

## Migrations

Store migrations are supported via the \`#\[migrate<sub>from</sub>\]\`
attribute. This allows you to evolve your data structures while keeping
data integrity.

### Example

The recommended approach is to use private submodules for versioning
models and always re-export the latest version:

``` rust
mod models {
    mod v1 {
        #[derive(Store, Serialize, Deserialize)]
        #[model_name = "User"]  // Required when struct was renamed
        pub(super) struct UserV1 {
            #[key]
            id: Uuid,
            name: String,
            email: String,
        }
    }

    mod v2 {
        #[derive(Store, Serialize, Deserialize)]
        #[migrate_from(super::v1::UserV1)]
        pub(super) struct User {
            #[key]
            id: Uuid,
            first_name: String,
            last_name: String,
            email: String,
        }

        impl UserV1ToUser for User {
            fn from_user_v1(prev: &super::v1::UserV1) -> Result<Self, tikv_client::Error> {
                let (first, last) = prev.name
                    .split_once(' ')
                    .ok_or_else(|| tikv_client::Error::StringError(
                        "Invalid name format".into()
                    ))?;

                Ok(Self {
                    id: prev.id,
                    first_name: first.to_string(),
                    last_name: last.to_string(),
                    email: prev.email.clone(),
                })
            }
        }
    }

    // Always re-export latest version
    pub use v2::User;
}
```

Note: The \`#\[model<sub>name</sub>\]\` attribute is required when the
struct name changes between versions (like UserV1 -\> User above). This
ensures ergokv can track the underlying model correctly across
migrations.

Run migrations:

``` rust
User::ensure_migrations(&client).await?;
```

## Running TiKV

### For Development

Use TiUP playground:

``` bash
tiup playground
```

This sets up a local TiKV cluster for testing.

### For Production

1.  Create a topology file (e.g., \`topology.yaml\`):

    ``` yaml
    global:
      user: "tidb"
      ssh_port: 22
      deploy_dir: "/tidb-deploy"
      data_dir: "/tidb-data"

    pd_servers:
      - host: 10.0.1.1
      - host: 10.0.1.2
      - host: 10.0.1.3

    tikv_servers:
      - host: 10.0.1.4
      - host: 10.0.1.5
      - host: 10.0.1.6

    tidb_servers:
      - host: 10.0.1.7
      - host: 10.0.1.8
      - host: 10.0.1.9
    ```

2.  Deploy the cluster:

    ``` bash
    tiup cluster deploy mytikvcluster 5.1.0 topology.yaml --user root -p
    ```

3.  Start the cluster:

    ``` bash
    tiup cluster start mytikvcluster
    ```

## Testing

To run tests, ensure you have TiUP installed and then use:

``` bash
cargo test
```

Tests will automatically start and stop a TiKV instance using TiUP.

I will be honest with you, chief, I made one test and that's it.

## License

This project is licensed under the Fair License:

> Copyright (c) 2024 Lukáš Hozda
>
> Usage of the works is permitted provided that this instrument is
> retained with the works, so that any entity that uses the works is
> notified of this instrument.
>
> DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

There is a lot of things that could be improved:

- Make ergokv support more KV stores
- Improve documentation
- Allow swapping the serialization format (currently we use CBOR via
  ciborium)
- Let methods be generic (in the case of TiKV) over RawClient,
  Transaction and TransactionClient
- Add additional methods that retrieve multiple structures, to make it
  useful to e.g. fetch entities like articles and all users (note that
  this can be done already by manually making a sort of entity registry
  for yourself)

## GitHub Repository

[github.com/luciumagn/ergokv](https://github.com/luciumagn/ergokv)