LoginSignup
1
0

More than 3 years have passed since last update.

【Rust】rusoto_dynamodbが使いやすくなるdynomiteの紹介

Posted at

はじめに

RustでDynamoDBを扱うときはrusoto_dynamodbを使いますが、
dynomiteというCrateを組みあわせると非常に使いやすくなります。
カッコよく言えば、ハイレベルなインターフェースを提供してくれます。

DynamoDBのBooksというテーブルに項目を作成するコードを、
「rusoto_dynamodbのみで書いた場合」と「dynomiteを使った場合」で比較してみます。

rusoto_dynamodbのみで書いた場合

rusoto_dynamodbでテーブルに項目を作成するときは、
PutItemInput構造体のインスタンスを生成する必要があります。
作成したい項目の情報はHashMap<String, AttributeValue>でitemにセットします。

pub struct PutItemInput {
    pub item: HashMap<String, AttributeValue>,
    pub table_name: String,
    ...
}

AttributeValueはDynamoDBのデータ型1に対応したフィールドを持ちます。

pub struct AttributeValue {
    pub b: Option<Bytes>, // Binary
    pub bool: Option<bool>, // Boolean
    pub bs: Option<Vec<Bytes>>, // Binary Set
    pub l: Option<Vec<AttributeValue>>, // List
    pub m: Option<HashMap<String, AttributeValue>>, // Map
    pub n: Option<String>, // Number
    pub ns: Option<Vec<String>>, // Number Set
    pub null: Option<bool>, // Null
    pub s: Option<String>, // String
    pub ss: Option<Vec<String>>, // String Set
}

例えば、下の表のような項目を作成するとします。

名前 データ型
id 101 Number
title Book 101 Title String
price 2 Number

このときのコードはこんな感じです。

rusoto_dynamo.rs
let mut new_item = HashMap::new();
new_item.insert(
    "id".to_string(),
    AttributeValue {
        n: Some("101".to_string()),
        ..AttributeValue::default()
    },
);

new_item.insert(
    "title".to_string(),
    AttributeValue {
        s: Some("Book 101 Title".to_string()),
        ..AttributeValue::default()
    },
);

new_item.insert(
    "price".to_string(),
    AttributeValue {
        n: Some("2".to_string()),
        ..AttributeValue::default()
    },
);

let input = PutItemInput {
    table_name: "Books".to_string(),
    item: new_item,
    ..PutItemInput::default()
};

dynomiteを使った場合

まずは項目を表す構造体を定義します。

use dynomite::Item;

#[derive(Item)]
struct Book {
    #[dynomite(partition_key)]
    id: i32,
    title: String,
    price: i32,
}

すると先ほどのコードはこのように簡潔に書けます。
new_item.into()Book構造体をHashMap<String, AttributeValue>に変換してくれます。

dynomite.rs
let new_item = Book {
    id: 101,
    title: "Book 101 Title".to_string(),
    price: 2,
};

let input = PutItemInput {
    table_name: "Books".to_string(),
    item: new_item.into(),
    ..PutItemInput::default()
};

このとき、Book::from_attrs(hm)HashMap<String, AttributeValue>->Book構造体の変換もサポートしています。
項目を取得したときに大活躍します。

参考

rusoto_dynamodb - Rust
softprops/dynomite: ⚡🦀 🧨 make your rust types fit DynamoDB and visa versa

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0