Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: keys composite clause #2798

Merged
merged 4 commits into from
Dec 12, 2024
Merged
Changes from 2 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
44 changes: 33 additions & 11 deletions crates/torii/grpc/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -742,16 +742,25 @@ 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!(
"SELECT COUNT(*) FROM (
SELECT {table}.id
FROM {table}
{join_clause}
{where_clause}
GROUP BY {table}.id
{having_clause}
) as filtered_count",
)
} else {
format!(
"SELECT COUNT(DISTINCT {table}.id)
FROM {table}
{join_clause}
{where_clause}",
)
};

let mut count_query = sqlx::query_scalar::<_, u32>(&count_query);
for value in &bind_values {
Expand Down Expand Up @@ -1124,7 +1133,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 @@ -1162,6 +1171,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
Loading