Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions crates/core/src/expression/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

//! Expression AST types for condition and update expressions.

use super::resolver::{ExpressionMaps, resolve_name_ref};
use crate::types::KeySchemaElement;

/// A single element in a document path.
#[derive(Debug, Clone, PartialEq)]
pub enum PathElement {
Expand Down Expand Up @@ -104,6 +107,62 @@ pub fn removes_only(actions: &[UpdateAction]) -> bool {
!actions.is_empty() && actions.iter().all(UpdateAction::removes_only)
}

/// Whether `condition` holds exactly when the item does not exist.
///
/// Every stored item carries its key attributes. So `attribute_not_exists` on
/// a key attribute holds against no item and fails against every item,
/// whatever else the item holds, and `attribute_exists` on one is its
/// opposite. `AND`, `OR` and `NOT` of such terms keep that property when their
/// operands agree, for example `attribute_not_exists(pk) AND
/// attribute_not_exists(sk)` or `NOT attribute_exists(pk)`. A backend can
/// decide such a condition by whether the key is taken, without reading the
/// item. A `#name` that does not resolve answers false, so that the request
/// takes the path that reports the validation error.
#[must_use]
pub fn requires_absent_item(
condition: &Expr,
key_schema: &[KeySchemaElement],
maps: &ExpressionMaps,
) -> bool {
holds_when_absent(condition, key_schema, maps) == Some(true)
}

/// `Some(true)` when `condition` holds exactly when the item does not exist,
/// `Some(false)` when it holds exactly when the item exists, and `None` when
/// the key alone does not decide it.
fn holds_when_absent(
condition: &Expr,
key_schema: &[KeySchemaElement],
maps: &ExpressionMaps,
) -> Option<bool> {
match condition {
Expr::And(a, b) | Expr::Or(a, b) => {
let a = holds_when_absent(a, key_schema, maps)?;
(holds_when_absent(b, key_schema, maps)? == a).then_some(a)
}
Expr::Not(e) => holds_when_absent(e, key_schema, maps).map(|absent| !absent),
Expr::Function { name, args } => {
let absent = match name.as_str() {
"attribute_not_exists" => true,
"attribute_exists" => false,
_ => return None,
};
let [Expr::Path(path)] = args.as_slice() else {
return None;
};
let [PathElement::Attribute(attr)] = path.as_slice() else {
return None;
};
let attr = resolve_name_ref(attr, maps).ok()?;
key_schema
.iter()
.any(|k| k.attribute_name == attr.as_ref())
.then_some(absent)
}
_ => None,
}
}

#[cfg(test)]
mod tests {
use super::removes_only;
Expand Down Expand Up @@ -132,3 +191,80 @@ mod tests {
assert!(!removes_only(&actions("DELETE s :v ADD n :w")));
}
}

#[cfg(test)]
mod requires_absent_item_tests {
use super::requires_absent_item;
use crate::expression::parser::parse_condition;
use crate::expression::resolver::ExpressionMaps;
use crate::expression::tokenizer::tokenize;
use crate::types::{KeySchemaElement, KeyType};

fn check(expr: &str, names: &[(&str, &str)]) -> bool {
let schema = [
KeySchemaElement {
attribute_name: "pk".to_owned(),
key_type: KeyType::Hash,
},
KeySchemaElement {
attribute_name: "sk".to_owned(),
key_type: KeyType::Range,
},
];
let cond = parse_condition(&tokenize(expr).expect("tokens")).expect("condition");
let mut maps = ExpressionMaps::default();
for (k, v) in names {
maps.names.insert((*k).to_owned(), (*v).to_owned());
}
requires_absent_item(&cond, &schema, &maps)
}

#[test]
fn terms_on_key_attributes_that_agree_require_an_absent_item() {
assert!(check("attribute_not_exists(pk)", &[]));
assert!(check("attribute_not_exists(sk)", &[]));
assert!(check("attribute_not_exists(#k)", &[("k", "pk")]));
assert!(check(
"attribute_not_exists(pk) AND attribute_not_exists(sk)",
&[]
));
assert!(check(
"attribute_not_exists(pk) OR attribute_not_exists(sk)",
&[]
));
assert!(check("NOT attribute_exists(pk)", &[]));
assert!(check(
"(NOT attribute_exists(pk)) AND (attribute_not_exists(sk))",
&[]
));
assert!(check(
"NOT (attribute_exists(pk) OR attribute_exists(sk))",
&[]
));
}

#[test]
fn other_conditions_do_not() {
assert!(!check("attribute_exists(pk)", &[]));
assert!(!check("NOT attribute_not_exists(pk)", &[]));
assert!(!check("attribute_not_exists(other)", &[]));
assert!(!check("attribute_not_exists(#k)", &[("k", "other")]));
assert!(!check("attribute_not_exists(#missing)", &[]));
assert!(!check("attribute_not_exists(pk.x)", &[]));
assert!(!check("attribute_not_exists(pk[0])", &[]));
assert!(!check(
"attribute_not_exists(pk) AND attribute_not_exists(other)",
&[]
));
assert!(!check(
"attribute_not_exists(pk) AND attribute_exists(sk)",
&[]
));
assert!(!check(
"attribute_not_exists(pk) OR attribute_exists(sk)",
&[]
));
assert!(!check("attribute_type(pk, :t)", &[]));
assert!(!check("pk = :v", &[]));
}
}
4 changes: 3 additions & 1 deletion crates/core/src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ mod tokenizer;
mod update_evaluator;
mod update_parser;

pub use ast::{ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only};
pub use ast::{
ArithOp, CompareOp, Expr, PathElement, UpdateAction, removes_only, requires_absent_item,
};
pub use evaluator::evaluate_condition;
pub use key_condition::{
KeyClauseOperand, KeyCondition, SortKeyCondition, key_condition_clause_operands,
Expand Down
3 changes: 2 additions & 1 deletion crates/storage-postgres/src/bootstrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,8 @@ impl Bootstrapper for PostgresBootstrapper {
r#"[storage.postgres]
connection_string = "{}"
# pool_size = 20 # Max connections for data operations (default 20, min 10)
# catalog_pool_size = # Max connections for management/catalog ops (defaults to pool_size, min 10)"#,
# catalog_pool_size = # Max connections for management/catalog ops (defaults to pool_size, min 10)
# create_only_puts = true # A PutItem with only attribute_not_exists on the key is one INSERT, no transaction"#,
self.catalog_connection_url()
)
}
Expand Down
34 changes: 34 additions & 0 deletions crates/storage-postgres/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ pub struct PostgresStorageConfig {
deserialize_with = "extenddb_storage::config::string_coerce::opt_u32"
)]
pub catalog_pool_size: Option<u32>,
/// Write a `PutItem` whose condition only says that the item must not
/// exist (`attribute_not_exists` on a key attribute) as one autocommit
/// `INSERT ... ON CONFLICT DO NOTHING`, when the table has no index and no
/// stream to maintain and the write is not already slow. `false` keeps
/// such puts on the transaction path. The answers are the same either
/// way.
#[serde(
default = "default_create_only_puts",
deserialize_with = "extenddb_storage::config::string_coerce::bool"
)]
pub create_only_puts: bool,
}

impl Default for PostgresStorageConfig {
Expand All @@ -33,6 +44,7 @@ impl Default for PostgresStorageConfig {
connection_string: default_connection_string(),
pool_size: default_pool_size(),
catalog_pool_size: None,
create_only_puts: default_create_only_puts(),
}
}
}
Expand All @@ -45,6 +57,10 @@ fn default_pool_size() -> u32 {
20
}

fn default_create_only_puts() -> bool {
true
}

/// Parsed components of a `PostgreSQL` connection string.
pub struct ConnParts {
pub user: String,
Expand Down Expand Up @@ -172,6 +188,24 @@ catalog_pool_size = 10"#,
assert_eq!(cfg.pool_size, 25);
assert_eq!(cfg.catalog_pool_size, Some(10));
}

/// `create_only_puts` is on when omitted, and an environment override
/// (`EXTENDDB__STORAGE__POSTGRES__CREATE_ONLY_PUTS=false`) arrives as a
/// string.
#[test]
fn create_only_puts_defaults_on_and_accepts_both_forms() {
let conn = r#"connection_string = "postgresql://u:p@localhost:5432/db""#;
for (extra, expected) in [
("", true),
("create_only_puts = false", false),
("create_only_puts = \"false\"", false),
("create_only_puts = \"true\"", true),
] {
let cfg: PostgresStorageConfig =
toml::from_str(&format!("{conn}\n{extra}")).expect("the config must deserialize");
assert_eq!(cfg.create_only_puts, expected, "{extra:?}");
}
}
}

#[cfg(test)]
Expand Down
Loading