Skip to content

Commit

Permalink
fix: keys composite clause (#2798)
Browse files Browse the repository at this point in the history
* fix: keys composite clause

* count

* c

* f
  • Loading branch information
Larkooo authored and kariy committed Dec 13, 2024
1 parent bdb1639 commit 0eeb8ae
Showing 1 changed file with 39 additions and 11 deletions.
50 changes: 39 additions & 11 deletions crates/torii/grpc/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -764,16 +764,31 @@ impl DojoWorld {
let (where_clause, having_clause, join_clause, bind_values) =
build_composite_clause(table, model_relation_table, &composite)?;

let count_query = format!(
r#"
SELECT COUNT(DISTINCT [{table}].id)
FROM [{table}]
JOIN {model_relation_table} ON [{table}].id = {model_relation_table}.entity_id
{join_clause}
{where_clause}
{having_clause}
"#,
);
let count_query = if !having_clause.is_empty() {
format!(
r#"
SELECT COUNT(*) FROM (
SELECT [{table}].id
FROM [{table}]
JOIN {model_relation_table} ON [{table}].id = {model_relation_table}.entity_id
{join_clause}
{where_clause}
GROUP BY [{table}].id
{having_clause}
) as filtered_count
"#
)
} else {
format!(
r#"
SELECT COUNT(DISTINCT [{table}].id)
FROM [{table}]
JOIN {model_relation_table} ON [{table}].id = {model_relation_table}.entity_id
{join_clause}
{where_clause}
"#
)
};

let mut count_query = sqlx::query_scalar::<_, u32>(&count_query);
for value in &bind_values {
Expand Down Expand Up @@ -1146,7 +1161,7 @@ fn build_keys_pattern(clause: &proto::types::KeysClause) -> Result<String, Error
let mut keys_pattern = format!("^{}", keys.join("/"));

if clause.pattern_matching == proto::types::PatternMatching::VariableLen as i32 {
keys_pattern += &format!("({})*", KEY_PATTERN);
keys_pattern += &format!("/({})*", KEY_PATTERN);
}
keys_pattern += "/$";

Expand Down Expand Up @@ -1184,6 +1199,19 @@ fn build_composite_clause(
let keys_pattern = build_keys_pattern(keys)?;
bind_values.push(keys_pattern);
where_clauses.push(format!("{table}.keys REGEXP ?"));

// Add model checks for specified models
for model in &keys.models {
let (namespace, model_name) = model
.split_once('-')
.ok_or(QueryError::InvalidNamespacedModel(model.clone()))?;
let model_id = compute_selector_from_names(namespace, model_name);

having_clauses.push(format!(
"INSTR(group_concat({model_relation_table}.model_id), '{:#x}') > 0",
model_id
));
}
}
ClauseType::Member(member) => {
let comparison_operator = ComparisonOperator::from_repr(member.operator as usize)
Expand Down

0 comments on commit 0eeb8ae

Please sign in to comment.