SQL を使わないデータベース
DynamoDB のように SDK で読むデータベースも、SQL で読むものと同じように使います。クライアントをルーターの状態に置き、ハンドラはその呼び出しを .await します。
ルーターの状態に置くクライアント
SQL の代わりに SDK で使うデータベースも、SQL のものと形は同じで、クライアントをルーターの状態に置き、ハンドラはその呼び出しを .await します。下のサンプルは AWS 公式のクレート aws-sdk-dynamodb で DynamoDB を読みます。次の 2 つのクレートが必要です。
[dependencies]
aws-config = "1.13"
aws-sdk-dynamodb = "1.134"use aws_config::BehaviorVersion;
use aws_sdk_dynamodb::Client;
use aws_sdk_dynamodb::types::AttributeValue;
#[derive(Clone)]
struct AppState {
dynamo: Client,
}
#[derive(Debug)]
struct DbError(String);
impl IntoResponse for DbError {
fn into_response(self) -> Response {
eprintln!("DynamoDB: {}", self.0);
let message = "The list could not be read. Try again.";
(StatusCode::INTERNAL_SERVER_ERROR, message).into_response()
}
}
/// The titles of the todos under the partition key `list = "home"`.
async fn titles(state: &AppState) -> Result<Vec<String>, DbError> {
let output = state
.dynamo
.query()
.table_name("todos")
.key_condition_expression("list = :list")
.expression_attribute_values(":list", AttributeValue::S("home".to_owned()))
.send()
.await
.map_err(|error| DbError(error.to_string()))?;
let titles = output.items().iter().filter_map(|item| item.get("title")?.as_s().ok());
Ok(titles.cloned().collect())
}
async fn index(state: AppState, (): ()) -> Result<Page<Todos>, DbError> {
let titles = titles(&state).await?;
let count = i32::try_from(titles.len()).unwrap_or(i32::MAX);
let list = ul().children(titles.into_iter().map(|title| li().text(title)));
Ok(Page::new("Todos", Todos { count }).child(list))
}
hypersig::routes! {
fn pages(Router<AppState>);
const INDEX: Route = "/" => index;
}
/// The region and the credentials come from the environment, as the AWS
/// CLI reads them.
async fn state() -> AppState {
let config = aws_config::defaults(BehaviorVersion::latest()).load().await;
AppState {
dynamo: Client::new(&config),
}
}aws_config::defaults(..).load() は AWS CLI と同じようにリージョンと認証情報を環境から読むので、これらはサーバーから出ません。Client は Clone で、複製どうしが 1 つのクライアントを共有します。そのため状態には Arc に入れずに置き、サーバーの起動時に 1 回だけ作ります。認証情報がないときのように呼び出しが失敗すると、エラーが返ります。DbError はそれをログに出し、SQL のサンプルと同じように 500 で応答します。
型で検査しないもの
テーブル名、キーの条件、属性の名前は、コンパイラが読まない文字列です。テーブル名や条件を間違えると send を実行したときに失敗し、訪問者には 500 が届きます。title のない項目や、title が文字列でない項目は as_s が受け付けず、サンプルの filter_map は何も知らせずにその項目を一覧から外します。属性がないことを誤りとして知りたいときは、飛ばす代わりにログに出してください。
Firestore
Firestore については、2026 年 10 月の時点で Google はドキュメントを読み書きするクレートを公開しておらず、公開しているのは管理用 API の google-cloud-firestore-admin-v1 だけです。よく使われているのはコミュニティの firestore クレートです。
次に読むページ
- データを保存する では状態に置く接続、クエリが失敗したときの応答、プロセスをまたぐ更新を説明します。
- デプロイ先ごとのデータベース ではネットワーク越しかバインディングでしかデータベースを使えないデプロイ先を説明します。