1#![warn(missing_docs)]
2
3mod op;
18mod r#type;
19mod value;
20
21pub(crate) use r#type::TypeExt;
22pub(crate) use value::Value;
23
24use async_trait::async_trait;
25use toasty_core::{
26 Error, Result, Schema,
27 driver::{
28 Capability, ConnectContext, Driver, ExecResponse, QueryLogConfig, log::QueryLog,
29 operation::Operation,
30 },
31 schema::db::{self, Column, ColumnId, Table},
32 stmt::{self, ExprContext},
33};
34
35use aws_sdk_dynamodb::{
36 Client,
37 error::SdkError,
38 operation::transact_write_items::TransactWriteItemsError,
39 operation::update_item::UpdateItemError,
40 types::{
41 AttributeDefinition, AttributeValue, BillingMode, Delete, GlobalSecondaryIndex,
42 KeySchemaElement, KeyType, KeysAndAttributes, Projection, ProjectionType, Put, PutRequest,
43 ReturnValuesOnConditionCheckFailure, TransactWriteItem, Update, WriteRequest,
44 },
45};
46use std::{borrow::Cow, collections::HashMap, sync::Arc};
47
48#[derive(Debug, Clone)]
54pub struct DynamoDb {
55 url: String,
56 client: Client,
57}
58
59impl DynamoDb {
60 pub fn new(url: String, client: Client) -> Self {
62 Self { url, client }
63 }
64
65 pub async fn from_env(url: String) -> Result<Self> {
68 use aws_config::BehaviorVersion;
69
70 let parsed = toasty_core::driver::ConnectionUrl::parse(&url)?;
74 parsed.validate_authority()?;
75
76 if !parsed.has_scheme("dynamodb") {
77 return Err(toasty_core::Error::invalid_connection_url(format!(
78 "connection URL does not have a `dynamodb` scheme; url={url}"
79 )));
80 }
81
82 let sdk_config = aws_config::defaults(BehaviorVersion::latest()).load().await;
83 let client = Client::new(&sdk_config);
84 Ok(Self::new(url, client))
85 }
86
87 pub fn with_sdk_config(url: String, sdk_config: &aws_config::SdkConfig) -> Self {
89 let client = Client::new(sdk_config);
90 Self::new(url, client)
91 }
92}
93
94#[async_trait]
95impl Driver for DynamoDb {
96 fn url(&self) -> Cow<'_, str> {
97 Cow::Borrowed(&self.url)
98 }
99
100 fn capability(&self) -> &'static Capability {
101 &Capability::DYNAMODB
102 }
103
104 async fn connect(
105 &self,
106 cx: &ConnectContext,
107 ) -> toasty_core::Result<Box<dyn toasty_core::driver::Connection>> {
108 let mut connection = Connection::new(self.client.clone());
110 connection.query_log = cx.query_log;
111 Ok(Box::new(connection))
112 }
113
114 async fn reset_db(&self) -> toasty_core::Result<()> {
115 let mut exclusive_start_table_name = None;
117 loop {
118 let mut req = self.client.list_tables();
119 if let Some(start) = &exclusive_start_table_name {
120 req = req.exclusive_start_table_name(start);
121 }
122
123 let resp = req
124 .send()
125 .await
126 .map_err(toasty_core::Error::driver_operation_failed)?;
127
128 if let Some(table_names) = &resp.table_names {
129 for table_name in table_names {
130 self.client
131 .delete_table()
132 .table_name(table_name)
133 .send()
134 .await
135 .map_err(toasty_core::Error::driver_operation_failed)?;
136 }
137 }
138
139 exclusive_start_table_name = resp.last_evaluated_table_name;
140 if exclusive_start_table_name.is_none() {
141 break;
142 }
143 }
144
145 Ok(())
146 }
147}
148
149#[derive(Debug)]
151pub struct Connection {
152 client: Client,
154 query_log: QueryLogConfig,
155}
156
157impl Connection {
158 pub fn new(client: Client) -> Self {
160 Self {
161 client,
162 query_log: QueryLogConfig::default(),
163 }
164 }
165}
166
167fn op_table_name<'a>(schema: &'a Schema, op: &Operation) -> Option<&'a str> {
169 let table_id = match op {
170 Operation::GetByKey(op) => op.table,
171 Operation::QueryPk(op) => op.table,
172 Operation::DeleteByKey(op) => op.table,
173 Operation::UpdateByKey(op) => op.table,
174 Operation::Upsert(op) => op.stmt.target.as_table_unwrap().table,
175 Operation::FindPkByIndex(op) => op.table,
176 Operation::Scan(op) => op.table,
177 _ => return None,
178 };
179 Some(&schema.db.table(table_id).name)
180}
181
182#[async_trait]
183impl toasty_core::driver::Connection for Connection {
184 async fn exec(&mut self, schema: &Arc<Schema>, op: Operation) -> Result<ExecResponse> {
185 let log = QueryLog::operation(
186 &self.query_log,
187 "dynamodb",
188 op.name(),
189 op_table_name(schema, &op),
190 );
191 let result = self.exec2(schema, op).await;
192 log.finish(&result);
193 result
194 }
195
196 async fn push_schema(&mut self, schema: &Schema) -> Result<()> {
197 for table in &schema.db.tables {
198 tracing::debug!(table = %table.name, "creating table");
199 self.create_table(&schema.db, table, true).await?;
200 }
201 Ok(())
202 }
203
204 async fn applied_migrations(
205 &mut self,
206 ) -> Result<Vec<toasty_core::schema::db::AppliedMigration>> {
207 Err(Error::unsupported_feature(
208 "migrations are not supported by the DynamoDB driver",
209 ))
210 }
211
212 async fn apply_migration(
213 &mut self,
214 _id: u64,
215 _name: &str,
216 _migration: &toasty_core::schema::db::Migration,
217 ) -> Result<()> {
218 Err(Error::unsupported_feature(
219 "migrations are not supported by the DynamoDB driver",
220 ))
221 }
222}
223
224impl Connection {
225 async fn exec2(&mut self, schema: &Arc<Schema>, op: Operation) -> Result<ExecResponse> {
226 match op {
227 Operation::GetByKey(op) => self.exec_get_by_key(schema, op).await,
228 Operation::QueryPk(op) => self.exec_query_pk(schema, op).await,
229 Operation::DeleteByKey(op) => self.exec_delete_by_key(&schema.db, op).await,
230 Operation::UpdateByKey(op) => self.exec_update_by_key(&schema.db, op).await,
231 Operation::Upsert(op) => self.exec_upsert(&schema.db, op).await,
232 Operation::FindPkByIndex(op) => self.exec_find_pk_by_index(schema, op).await,
233 Operation::Insert(op) => {
234 self.exec_insert(&schema.db, op.stmt.into_insert_unwrap())
235 .await
236 }
237 Operation::QuerySql(op) => todo!("op={:#?}", op.stmt),
238 Operation::Scan(op) => self.exec_scan(schema, op).await,
239 Operation::RawSql(_) => Err(Error::unsupported_feature(
240 "raw SQL is only supported by SQL drivers",
241 )),
242 Operation::Transaction(_) => Err(Error::unsupported_feature(
243 "transactions are not supported by the DynamoDB driver",
244 )),
245 }
246 }
247}
248
249fn ddb_key(table: &Table, key: &stmt::Value) -> HashMap<String, AttributeValue> {
250 let mut ret = HashMap::new();
251
252 for (index, column) in table.primary_key_columns().enumerate() {
253 let value = match key {
254 stmt::Value::Record(record) => &record[index],
255 value => value,
256 };
257
258 ret.insert(column.name.clone(), Value::from(value.clone()).to_ddb());
259 }
260
261 ret
262}
263
264fn attr_value_to_stmt_value(attr: &AttributeValue) -> stmt::Value {
266 use AttributeValue as AV;
267
268 match attr {
269 AV::S(s) => stmt::Value::String(s.clone()),
270 AV::N(n) => {
271 n.parse::<i64>()
273 .map(stmt::Value::I64)
274 .unwrap_or_else(|_| stmt::Value::String(n.clone()))
275 }
276 AV::Bool(b) => stmt::Value::Bool(*b),
277 AV::B(bytes) => stmt::Value::Bytes(bytes.clone().into_inner()),
278 AV::Null(_) => stmt::Value::Null,
279 _ => stmt::Value::String(format!("{:?}", attr)),
281 }
282}
283
284fn serialize_ddb_cursor(last_key: &HashMap<String, AttributeValue>) -> stmt::Value {
288 let mut fields = Vec::with_capacity(last_key.len() * 2);
289
290 for (name, attr_value) in last_key {
291 fields.push(stmt::Value::String(name.clone()));
292 fields.push(attr_value_to_stmt_value(attr_value));
293 }
294
295 stmt::Value::Record(stmt::ValueRecord::from_vec(fields))
296}
297
298fn deserialize_ddb_cursor(cursor: &stmt::Value) -> HashMap<String, AttributeValue> {
301 let mut ret = HashMap::new();
302
303 if let stmt::Value::Record(fields) = cursor {
304 for chunk in fields.chunks(2) {
306 if chunk.len() == 2
307 && let (stmt::Value::String(name), value) = (&chunk[0], &chunk[1])
308 {
309 ret.insert(name.clone(), Value::from(value.clone()).to_ddb());
310 }
311 }
312 }
313
314 ret
315}
316
317fn ddb_key_schema(
318 partition_columns: &[&Column],
319 range_columns: &[&Column],
320) -> Vec<KeySchemaElement> {
321 let mut ks = vec![];
322
323 for col in partition_columns {
324 ks.push(
325 KeySchemaElement::builder()
326 .attribute_name(&col.name)
327 .key_type(KeyType::Hash)
328 .build()
329 .unwrap(),
330 );
331 }
332
333 for col in range_columns {
334 ks.push(
335 KeySchemaElement::builder()
336 .attribute_name(&col.name)
337 .key_type(KeyType::Range)
338 .build()
339 .unwrap(),
340 );
341 }
342
343 ks
344}
345
346fn item_to_record<'a, 'stmt>(
347 item: &HashMap<String, AttributeValue>,
348 columns: impl Iterator<Item = &'a Column>,
349) -> Result<stmt::ValueRecord> {
350 Ok(stmt::ValueRecord::from_vec(
351 columns
352 .map(|column| {
353 if let Some(value) = item.get(&column.name) {
354 Value::from_ddb(&column.ty, value).into_inner()
355 } else {
356 stmt::Value::Null
357 }
358 })
359 .collect(),
360 ))
361}
362
363fn ddb_expression(
364 cx: &ExprContext<'_, db::Schema>,
365 attrs: &mut ExprAttrs,
366 primary: bool,
367 expr: &stmt::Expr,
368) -> String {
369 match expr {
370 stmt::Expr::Between(expr_between) => {
371 let field = ddb_expression(cx, attrs, primary, &expr_between.expr);
372 let low = ddb_expression(cx, attrs, primary, &expr_between.low);
373 let high = ddb_expression(cx, attrs, primary, &expr_between.high);
374 format!("{field} BETWEEN {low} AND {high}")
375 }
376 stmt::Expr::BinaryOp(expr_binary_op) => {
377 let lhs = ddb_expression(cx, attrs, primary, &expr_binary_op.lhs);
378 let rhs = ddb_expression(cx, attrs, primary, &expr_binary_op.rhs);
379
380 match expr_binary_op.op {
381 stmt::BinaryOp::Eq => format!("{lhs} = {rhs}"),
382 stmt::BinaryOp::Ne if primary => {
383 todo!("!= conditions on primary key not supported")
384 }
385 stmt::BinaryOp::Ne => format!("{lhs} <> {rhs}"),
386 stmt::BinaryOp::Gt => format!("{lhs} > {rhs}"),
387 stmt::BinaryOp::Ge => format!("{lhs} >= {rhs}"),
388 stmt::BinaryOp::Lt => format!("{lhs} < {rhs}"),
389 stmt::BinaryOp::Le => format!("{lhs} <= {rhs}"),
390 stmt::BinaryOp::Add | stmt::BinaryOp::Sub => {
395 todo!(
396 "arithmetic operators in DynamoDB condition expressions are not supported"
397 )
398 }
399 }
400 }
401 stmt::Expr::Reference(expr_reference) => {
402 let (column, col_alias) = column_alias(cx, attrs, expr_reference);
403 if column.ty.is_bool() {
406 let true_val = attrs.ddb_value(aws_sdk_dynamodb::types::AttributeValue::Bool(true));
407 format!("{col_alias} = {true_val}")
408 } else {
409 col_alias
410 }
411 }
412 stmt::Expr::Value(val) => attrs.value(val),
413 stmt::Expr::Func(stmt::ExprFunc::JsonExtract(func)) => {
418 let (path, leaf_ty) = document_path(cx, attrs, func);
419 if leaf_ty.is_bool() {
422 let true_val = attrs.ddb_value(aws_sdk_dynamodb::types::AttributeValue::Bool(true));
423 format!("{path} = {true_val}")
424 } else {
425 path
426 }
427 }
428 stmt::Expr::And(expr_and) => {
429 let operands = expr_and
430 .operands
431 .iter()
432 .map(|operand| ddb_expression(cx, attrs, primary, operand))
433 .collect::<Vec<_>>();
434 operands.join(" AND ")
435 }
436 stmt::Expr::Or(expr_or) => {
437 let operands = expr_or
438 .operands
439 .iter()
440 .map(|operand| ddb_expression(cx, attrs, primary, operand))
441 .collect::<Vec<_>>();
442 format!("({})", operands.join(" OR "))
443 }
444 stmt::Expr::InList(in_list) => {
445 let expr = ddb_expression(cx, attrs, primary, &in_list.expr);
446
447 let items = match &*in_list.list {
449 stmt::Expr::Value(stmt::Value::List(vals)) => vals
450 .iter()
451 .map(|val| attrs.value(val))
452 .collect::<Vec<_>>()
453 .join(", "),
454 _ => {
455 ddb_expression(cx, attrs, primary, &in_list.list)
457 }
458 };
459
460 format!("{expr} IN ({items})")
461 }
462 stmt::Expr::IsNull(expr_is_null) => {
463 let inner = match &*expr_is_null.expr {
471 stmt::Expr::Reference(expr_reference) => column_alias(cx, attrs, expr_reference).1,
472 stmt::Expr::Func(stmt::ExprFunc::JsonExtract(func)) => {
473 document_path(cx, attrs, func).0
474 }
475 other => ddb_expression(cx, attrs, primary, other),
476 };
477 if expr_is_null.negated {
478 format!("attribute_exists({inner})")
479 } else {
480 format!("attribute_not_exists({inner})")
481 }
482 }
483 stmt::Expr::Not(expr_not) => {
484 let inner = ddb_expression(cx, attrs, primary, &expr_not.expr);
485 format!("(NOT {inner})")
486 }
487 stmt::Expr::StartsWith(expr_starts_with) => {
488 let expr = ddb_expression(cx, attrs, primary, &expr_starts_with.expr);
489 let prefix = ddb_expression(cx, attrs, primary, &expr_starts_with.prefix);
490 format!("begins_with({expr}, {prefix})")
491 }
492 stmt::Expr::Like(_) => {
493 panic!(
494 "LIKE is not supported by the DynamoDB driver; use starts_with for prefix matching"
495 )
496 }
497 stmt::Expr::AnyOp(any) if matches!(any.op, stmt::BinaryOp::Eq) => {
498 let value = ddb_expression(cx, attrs, primary, &any.lhs);
502 let path = ddb_expression(cx, attrs, primary, &any.rhs);
503 format!("contains({path}, {value})")
504 }
505 stmt::Expr::Length(expr) => {
506 let inner = ddb_expression(cx, attrs, primary, &expr.expr);
507 format!("size({inner})")
508 }
509 stmt::Expr::Cast(expr_cast) if expr_cast.ty == stmt::Type::Bool => {
510 let col_alias = ddb_expression(cx, attrs, primary, &expr_cast.expr);
517 let true_val =
518 attrs.ddb_value(aws_sdk_dynamodb::types::AttributeValue::N("1".to_string()));
519 format!("{col_alias} = {true_val}")
520 }
521 _ => todo!("FILTER = {:#?}", expr),
522 }
523}
524
525fn column_alias<'a>(
529 cx: &ExprContext<'a, db::Schema>,
530 attrs: &mut ExprAttrs,
531 expr_reference: &stmt::ExprReference,
532) -> (&'a Column, String) {
533 let column = cx.resolve_expr_reference(expr_reference).as_column_unwrap();
534 let alias = attrs.column(column).to_string();
535 (column, alias)
536}
537
538fn document_path<'a>(
544 cx: &ExprContext<'a, db::Schema>,
545 attrs: &mut ExprAttrs,
546 func: &'a stmt::FuncJsonExtract,
547) -> (String, &'a stmt::Type) {
548 let stmt::Expr::Reference(expr_reference) = func.base.as_ref() else {
549 todo!("document path base must be a column reference; func={func:#?}")
550 };
551 let (_, mut path) = column_alias(cx, attrs, expr_reference);
552
553 for name in &func.path {
554 path.push('.');
555 path.push_str(attrs.document_segment(name));
556 }
557
558 (path, &func.ty)
559}
560
561#[derive(Default)]
562struct ExprAttrs {
563 columns: HashMap<ColumnId, String>,
564 document_segments: HashMap<String, String>,
567 attr_names: HashMap<String, String>,
568 attr_values: HashMap<String, AttributeValue>,
569}
570
571impl ExprAttrs {
572 fn column(&mut self, column: &Column) -> &str {
573 use std::collections::hash_map::Entry;
574
575 match self.columns.entry(column.id) {
576 Entry::Vacant(e) => {
577 let name = format!("#col_{}", column.id.index);
578 self.attr_names.insert(name.clone(), column.name.clone());
579 e.insert(name)
580 }
581 Entry::Occupied(e) => e.into_mut(),
582 }
583 }
584
585 fn document_segment(&mut self, name: &str) -> &str {
588 use std::collections::hash_map::Entry;
589
590 match self.document_segments.entry(name.to_owned()) {
591 Entry::Vacant(e) => {
592 let placeholder = format!("#doc_{}", self.attr_names.len());
593 self.attr_names.insert(placeholder.clone(), name.to_owned());
594 e.insert(placeholder)
595 }
596 Entry::Occupied(e) => e.into_mut(),
597 }
598 }
599
600 fn value(&mut self, val: &stmt::Value) -> String {
601 self.ddb_value(Value::from(val.clone()).to_ddb())
602 }
603
604 fn ddb_value(&mut self, val: AttributeValue) -> String {
605 let i = self.attr_values.len();
606 let name = format!(":v_{i}");
607 self.attr_values.insert(name.clone(), val);
608 name
609 }
610}