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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
mod list;
mod map;
mod num;
mod scalar;
mod set;
mod value_or_ref;
pub use list::List;
pub use map::Map;
pub use num::Num;
pub use scalar::Scalar;
pub use set::{BinarySet, NumSet, Set, StringSet};
pub use value_or_ref::{Ref, StringOrRef};
pub(crate) use value_or_ref::ValueOrRef;
use core::fmt::{self, LowerExp, UpperExp};
use aws_sdk_dynamodb::{primitives::Blob, types::AttributeValue};
use base64::{engine::general_purpose, Engine as _};
use itermap::IterMap;
use itertools::Itertools;
/// A DynamoDB value
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Value {
Scalar(Scalar),
Set(Set),
Map(Map),
List(List),
}
impl Value {
/// Use when you need a [string][1] value for DynamoDB.
///
/// See also: [`Scalar::new_string`]
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html#DDB-Type-AttributeValue-S
pub fn new_string<T>(value: T) -> Self
where
T: Into<String>,
{
value.into().into()
}
/// Use when you need a [numeric][1] value for DynamoDB.
///
/// See also:, [`Value::new_num_lower_exp`], [`Value::new_num_upper_exp`],
/// [`Scalar::new_num`], [`Num::new`]
///
/// # Examples
///
/// ```
/// use dynamodb_expression::Value;
/// # use pretty_assertions::assert_eq;
///
/// let value = Value::new_num(2600);
/// assert_eq!("2600", value.to_string());
///
/// let value = Value::new_num(2600.0);
/// assert_eq!("2600", value.to_string());
/// ```
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html#DDB-Type-AttributeValue-N
pub fn new_num<N>(value: N) -> Self
where
N: ToString + ::num::Num,
{
Num::new(value).into()
}
/// Use when you need a [numeric][1] value for DynamoDB in exponent form
/// (with a lowercase `e`).
///
/// See also:, [`Value::new_num`], [`Value::new_num_upper_exp`],
/// [`Scalar::new_num_lower_exp`], [`Num::new_lower_exp`]
///
/// # Examples
///
/// ```
/// use dynamodb_expression::Value;
/// # use pretty_assertions::assert_eq;
///
/// let value = Value::new_num_lower_exp(2600);
/// assert_eq!("2.6e3", value.to_string());
///
/// let value = Value::new_num_lower_exp(2600.0);
/// assert_eq!("2.6e3", value.to_string());
/// ```
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html#DDB-Type-AttributeValue-N
pub fn new_num_lower_exp<N>(value: N) -> Self
where
N: LowerExp + ::num::Num,
{
Num::new_lower_exp(value).into()
}
/// Use when you need a [numeric][1] value for DynamoDB in exponent form
/// (with an uppercase `e`).
///
/// See also:, [`Value::new_num`], [`Value::new_num_lower_exp`],
/// [`Scalar::new_num_upper_exp`], [`Num::new_upper_exp`]
///
/// # Examples
///
/// ```
/// use dynamodb_expression::Value;
/// # use pretty_assertions::assert_eq;
///
/// let value = Value::new_num_upper_exp(2600);
/// assert_eq!("2.6E3", value.to_string());
///
/// let value = Value::new_num_upper_exp(2600.0);
/// assert_eq!("2.6E3", value.to_string());
/// ```
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html#DDB-Type-AttributeValue-N
pub fn new_num_upper_exp<N>(value: N) -> Self
where
N: UpperExp + ::num::Num,
{
Num::new_upper_exp(value).into()
}
/// Use when you need a [boolean][1] value for DynamoDB.
///
/// See also: [`Scalar::new_bool`]
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html#DDB-Type-AttributeValue-BOOL
pub fn new_bool(b: bool) -> Self {
b.into()
}
/// Use when you need a [binary][1] value for DynamoDB.
///
/// See also: [`Scalar::new_binary`]
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html#DDB-Type-AttributeValue-B
pub fn new_binary<B>(binary: B) -> Self
where
B: Into<Vec<u8>>,
{
binary.into().into()
}
/// Use when you need a [null][1] value for DynamoDB.
///
/// See also: [`Scalar::new_null`]
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html#DDB-Type-AttributeValue-NULL
pub fn new_null() -> Self {
Self::Scalar(Scalar::Null)
}
// TODO:
/// See also: [`Set::new_string_set`], [`StringSet::new`]
pub fn new_string_set<T>(string_set: T) -> Self
where
T: Into<StringSet>,
{
string_set.into().into()
}
// TODO:
/// See also: [`Set::new_num_set`], [`NumSet::new`]
pub fn new_num_set<T>(num_set: T) -> Self
where
T: Into<NumSet>,
{
num_set.into().into()
}
// TODO:
/// See also: [`Set::new_binary_set`], [`BinarySet::new`]
pub fn new_binary_set<T>(binary_set: T) -> Self
where
T: Into<BinarySet>,
{
binary_set.into().into()
}
// TODO:
/// See also: [`Map::new`]
pub fn new_map<T>(map: T) -> Self
where
T: Into<Map>,
{
map.into().into()
}
// TODO:
/// See also: [`List::new`]
pub fn new_list<T>(list: T) -> Self
where
T: Into<List>,
{
list.into().into()
}
// Intentionally not using `impl From<ScalarValue> for AttributeValue` because
// I don't want to make this a public API people rely on. The purpose of this
// crate is not to make creating `AttributeValues` easier. They should try
// `serde_dynamo`.
pub(crate) fn into_attribute_value(self) -> AttributeValue {
match self {
Self::Scalar(value) => value.into_attribute_value(),
Self::Set(value) => value.into_attribute_value(),
Self::Map(value) => value.into_attribute_value(),
Self::List(value) => value.into_attribute_value(),
}
}
}
impl From<Scalar> for Value {
fn from(value: Scalar) -> Self {
Self::Scalar(value)
}
}
impl From<String> for Value {
fn from(value: String) -> Self {
Scalar::from(value).into()
}
}
impl From<&String> for Value {
fn from(value: &String) -> Self {
Scalar::from(value).into()
}
}
impl From<&str> for Value {
fn from(value: &str) -> Self {
Scalar::from(value).into()
}
}
impl From<&&str> for Value {
fn from(value: &&str) -> Self {
Scalar::from(value).into()
}
}
impl From<Num> for Value {
fn from(value: Num) -> Self {
Scalar::from(value).into()
}
}
impl From<bool> for Value {
fn from(value: bool) -> Self {
Scalar::from(value).into()
}
}
impl From<Vec<u8>> for Value {
fn from(value: Vec<u8>) -> Self {
Scalar::from(value).into()
}
}
impl<const N: usize> From<[u8; N]> for Value {
fn from(value: [u8; N]) -> Self {
Scalar::from(value).into()
}
}
impl From<()> for Value {
fn from(value: ()) -> Self {
Scalar::from(value).into()
}
}
impl FromIterator<u8> for Value {
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = u8>,
{
Scalar::from_iter(iter).into()
}
}
impl From<Set> for Value {
fn from(set: Set) -> Self {
Self::Set(set)
}
}
impl From<StringSet> for Value {
fn from(string_set: StringSet) -> Self {
Self::Set(string_set.into())
}
}
impl From<NumSet> for Value {
fn from(num_set: NumSet) -> Self {
Self::Set(num_set.into())
}
}
impl From<BinarySet> for Value {
fn from(string_set: BinarySet) -> Self {
Self::Set(string_set.into())
}
}
impl From<Map> for Value {
fn from(map: Map) -> Self {
Self::Map(map)
}
}
impl From<List> for Value {
fn from(list: List) -> Self {
Self::List(list)
}
}
impl TryFrom<AttributeValue> for Value {
type Error = AttributeValue;
/// On error, the unknown `AttributeValue` is returned. This will only occur
/// if a new `AttributeValue` variant is added to the AWS DynamoDB SDK.
///
/// See: [`AttributeValue::Unknown`]
fn try_from(value: AttributeValue) -> Result<Self, Self::Error> {
Ok(match value {
AttributeValue::B(value) => Scalar::Binary(value.into_inner()).into(),
AttributeValue::Bool(value) => Scalar::Bool(value).into(),
AttributeValue::Bs(value) => {
BinarySet::from_iter(value.into_iter().map(Blob::into_inner)).into()
}
AttributeValue::L(value) => List::from(
value
.into_iter()
.map(Self::try_from)
.try_collect::<_, Vec<_>, _>()?,
)
.into(),
AttributeValue::M(value) => Map::from(
value
.into_iter()
.map(|(k, v)| Self::try_from(v).map(|v| (k, v)))
.try_collect::<_, Vec<_>, _>()?,
)
.into(),
AttributeValue::N(value) => Num { n: value }.into(),
AttributeValue::Ns(value) => {
NumSet::from_iter(value.into_iter().map(|n| Num { n })).into()
}
AttributeValue::Null(_value) => Scalar::Null.into(),
AttributeValue::S(value) => Scalar::String(value).into(),
AttributeValue::Ss(value) => StringSet::from(value).into(),
_ => return Err(value),
})
}
}
impl From<serde_json::Value> for Value {
/// Converts a [`serde_json::Value`] into a [`Value`].
///
/// A shortcoming of this is that [`serde_json::Value`] doesn't contain
/// variants to differentiate between a DynamoDB [list][1] and a [set][2].
/// The result is that a [`serde_json::Value::Array`] becomes a
/// [`Value::List`].
///
/// [1]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.Document.List
/// [2]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.SetTypes
fn from(value: serde_json::Value) -> Self {
match value {
serde_json::Value::Null => Scalar::Null.into(),
serde_json::Value::Bool(value) => Scalar::Bool(value).into(),
serde_json::Value::Number(value) => Num {
n: value.to_string(),
}
.into(),
serde_json::Value::String(value) => Scalar::String(value).into(),
serde_json::Value::Array(value) => {
List::from_iter(value.into_iter().map(Value::from)).into()
}
serde_json::Value::Object(value) => {
Map::from_iter(value.into_iter().map_values(Value::from)).into()
}
}
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Scalar(value) => value.fmt(f),
Self::Set(value) => value.fmt(f),
Self::Map(value) => value.fmt(f),
Self::List(value) => value.fmt(f),
}
}
}
/// Produces base64 the way DynamoDB wants it.
pub(crate) fn base64<T>(b: T) -> String
where
T: AsRef<[u8]>,
{
general_purpose::STANDARD.encode(b)
}
#[cfg(test)]
mod test {
use aws_sdk_dynamodb::types::AttributeValue;
use pretty_assertions::assert_eq;
use serde_json::json;
use crate::value::{List, Map, Num};
use super::Value;
#[test]
fn display() {
assert_eq!(r#""a""#, Value::new_string("a").to_string());
assert_eq!(r#"1000"#, Value::new_num(1000).to_string());
assert_eq!(r#"1e3"#, Value::new_num_lower_exp(1000).to_string());
assert_eq!(r#"1E3"#, Value::new_num_upper_exp(1000).to_string());
assert_eq!(r#""YQ==""#, Value::new_binary("a").to_string());
assert_eq!("true", Value::new_bool(true).to_string());
assert_eq!("NULL", Value::new_null().to_string());
// Sets are unordered
assert_eq!(
r#"["a", "b", "c"]"#,
Value::new_string_set(["a", "c", "b"]).to_string()
);
assert_eq!(
r#"[-7, 1e3, 42]"#,
Value::new_num_set([Num::new_lower_exp(1000), Num::new(42), Num::new(-7)]).to_string()
);
assert_eq!(
r#"["YQ==", "Yg==", "Yw=="]"#,
Value::new_binary_set([b"a", b"b", b"c"]).to_string()
);
assert_eq!(
r#"[NULL, 8, "a string"]"#,
Value::new_list([
Value::new_null(),
Value::new_num(8),
Value::new_string("a string")
])
.to_string()
);
assert_eq!(
r#"{n: 8, null: NULL, s: "a string"}"#,
Value::new_map([
(String::from("s"), Value::new_string("a string")),
(String::from("n"), Value::new_num(8)),
(String::from("null"), Value::new_null()),
])
.to_string()
);
}
#[test]
fn from_json() {
assert_eq!(
Value::new_map([
(String::from("s"), Value::new_string("a string")),
(String::from("int"), Value::new_num(8)),
(String::from("float"), Value::new_num(4.276)),
(String::from("null"), Value::new_null()),
(String::from("yes"), Value::new_bool(true)),
(String::from("no"), Value::new_bool(false)),
(
String::from("list"),
Value::new_list([
Value::new_string("foo"),
Value::new_num(42),
Value::new_null(),
])
),
]),
Value::from(json!({
"s": "a string",
"int": 8,
"float": 4.276,
"null": null,
"yes": true,
"no": false,
"list": ["foo", 42, null],
})),
);
}
#[test]
fn from_attribute_value() {
// TODO: Test all of the variants. Currently missing:
// AttributeValue::B
// AttributeValue::Bs
// AttributeValue::Ns
// AttributeValue::Ss
assert_eq!(
Value::from(Map::from([
("s", Value::from("a string")),
("int", Value::from(Num::from(8))),
("null", Value::from(())),
("yes", Value::from(true)),
("no", Value::from(false)),
(
"list",
List::from([
Value::from("foo"),
Value::from(Num::from(42)),
Value::from(()),
])
.into(),
),
])),
Value::try_from(AttributeValue::M(
[
("s".to_string(), AttributeValue::S("a string".to_string())),
("int".to_string(), AttributeValue::N("8".to_string())),
("null".to_string(), AttributeValue::Null(true)),
("yes".to_string(), AttributeValue::Bool(true)),
("no".to_string(), AttributeValue::Bool(false)),
(
"list".to_string(),
AttributeValue::L(vec![
AttributeValue::S("foo".to_string()),
AttributeValue::N("42".to_string()),
AttributeValue::Null(true),
]),
),
]
.into_iter()
.collect(),
))
.expect("Could not convert AttributeValue to Value"),
);
}
}