| 1 | + | use std::collections::BTreeMap; |
| 2 | + | |
| 3 | + | use hasura_authn_core::SessionVariables; |
| 4 | + | use lang_graphql::normalized_ast::{self, Field}; |
| 5 | + | use open_dds::{ |
| 6 | + | relationships::{RelationshipName, RelationshipType}, |
| 7 | + | types::{CustomTypeName, FieldName}, |
| 8 | + | }; |
| 9 | + | |
| 10 | + | use ndc_client as ndc; |
| 11 | + | use serde::Serialize; |
| 12 | + | |
| 13 | + | use super::filter::resolve_filter_expression; |
| 14 | + | use super::model_selection::model_selection_ir; |
| 15 | + | use super::order_by::build_ndc_order_by; |
| 16 | + | use super::permissions; |
| 17 | + | use super::selection_set::FieldSelection; |
| 18 | + | use crate::execute::error; |
| 19 | + | use crate::execute::model_tracking::{count_model, UsagesCounts}; |
| 20 | + | use crate::metadata::resolved::subgraph::serialize_qualified_btreemap; |
| 21 | + | use crate::schema::types::output_type::relationship::{ |
| 22 | + | ModelRelationshipAnnotation, ModelTargetSource, |
| 23 | + | }; |
| 24 | + | use crate::{ |
| 25 | + | metadata::resolved::{self, subgraph::Qualified}, |
| 26 | + | schema::{ |
| 27 | + | types::{Annotation, InputAnnotation, ModelInputAnnotation}, |
| 28 | + | GDS, |
| 29 | + | }, |
| 30 | + | }; |
| 31 | + | |
| 32 | + | #[derive(Debug, Serialize)] |
| 33 | + | pub(crate) struct RelationshipInfo<'s> { |
| 34 | + | pub annotation: &'s ModelRelationshipAnnotation, |
| 35 | + | pub source_data_connector: &'s resolved::data_connector::DataConnector, |
| 36 | + | #[serde(serialize_with = "serialize_qualified_btreemap")] |
| 37 | + | pub source_type_mappings: &'s BTreeMap<Qualified<CustomTypeName>, resolved::types::TypeMapping>, |
| 38 | + | pub target_source: &'s ModelTargetSource, |
| 39 | + | } |
| 40 | + | |
| 41 | + | #[derive(Debug, Clone, Serialize)] |
| 42 | + | pub struct RemoteRelationshipInfo<'s> { |
| 43 | + | pub annotation: &'s ModelRelationshipAnnotation, |
| 44 | + | /// This contains processed information about the mappings. |
| 45 | + | /// `RelationshipMapping` only contains mapping of field names. This |
| 46 | + | /// contains mapping of field names and `resolved::types::FieldMapping`. |
| 47 | + | /// Also see `build_remote_relationship`. |
| 48 | + | pub join_mapping: Vec<(SourceField, TargetField)>, |
| 49 | + | } |
| 50 | + | |
| 51 | + | pub type SourceField = (FieldName, resolved::types::FieldMapping); |
| 52 | + | pub type TargetField = (FieldName, resolved::types::FieldMapping); |
| 53 | + | |
| 54 | + | pub(crate) fn process_relationship_definition( |
| 55 | + | relationship_info: &RelationshipInfo, |
| 56 | + | ) -> Result<ndc::models::Relationship, error::Error> { |
| 57 | + | let &RelationshipInfo { |
| 58 | + | annotation, |
| 59 | + | source_data_connector, |
| 60 | + | source_type_mappings, |
| 61 | + | target_source, |
| 62 | + | } = relationship_info; |
| 63 | + | |
| 64 | + | let mut column_mapping = BTreeMap::new(); |
| 65 | + | for resolved::relationship::RelationshipModelMapping { |
| 66 | + | source_field: source_field_path, |
| 67 | + | target_field: target_field_path, |
| 68 | + | } in annotation.mappings.iter() |
| 69 | + | { |
| 70 | + | if !matches!( |
| 71 | + | relationship_execution_category(target_source, source_data_connector), |
| 72 | + | RelationshipExecutionCategory::Local |
| 73 | + | ) { |
| 74 | + | Err(error::InternalEngineError::RemoteRelationshipsAreNotSupported)? |
| 75 | + | } else { |
| 76 | + | let source_column = get_field_mapping_of_field_name( |
| 77 | + | source_type_mappings, |
| 78 | + | &annotation.source_type, |
| 79 | + | &annotation.relationship_name, |
| 80 | + | &source_field_path.field_name, |
| 81 | + | )?; |
| 82 | + | let target_column = get_field_mapping_of_field_name( |
| 83 | + | &target_source.model.type_mappings, |
| 84 | + | &annotation.target_type, |
| 85 | + | &annotation.relationship_name, |
| 86 | + | &target_field_path.field_name, |
| 87 | + | )?; |
| 88 | + | |
| 89 | + | if column_mapping |
| 90 | + | .insert(source_column.column, target_column.column) |
| 91 | + | .is_some() |
| 92 | + | { |
| 93 | + | Err(error::InternalEngineError::MappingExistsInRelationship { |
| 94 | + | source_column: source_field_path.field_name.clone(), |
| 95 | + | relationship_name: annotation.relationship_name.clone(), |
| 96 | + | })? |
| 97 | + | } |
| 98 | + | } |
| 99 | + | } |
| 100 | + | let ndc_relationship = ndc_client::models::Relationship { |
| 101 | + | column_mapping, |
| 102 | + | relationship_type: { |
| 103 | + | match annotation.relationship_type { |
| 104 | + | RelationshipType::Object => ndc_client::models::RelationshipType::Object, |
| 105 | + | RelationshipType::Array => ndc_client::models::RelationshipType::Array, |
| 106 | + | } |
| 107 | + | }, |
| 108 | + | target_collection: target_source.model.collection.to_string(), |
| 109 | + | arguments: BTreeMap::new(), |
| 110 | + | }; |
| 111 | + | Ok(ndc_relationship) |
| 112 | + | } |
| 113 | + | |
| 114 | + | enum RelationshipExecutionCategory { |
| 115 | + | // Push down relationship definition to the data connector |
| 116 | + | Local, |
| 117 | + | // Use foreach in the data connector to fetch related rows for multiple objects in a single request |
| 118 | + | RemoteForEach, |
| 119 | + | } |
| 120 | + | |
| 121 | + | #[allow(clippy::match_single_binding)] |
| 122 | + | fn relationship_execution_category( |
| 123 | + | target_source: &ModelTargetSource, |
| 124 | + | source_connector: &resolved::data_connector::DataConnector, |
| 125 | + | ) -> RelationshipExecutionCategory { |
| 126 | + | // It's a local relationship if the source and target connectors are the same and |
| 127 | + | // the connector supports relationships. |
| 128 | + | if target_source.model.data_connector.name == source_connector.name |
| 129 | + | && target_source.capabilities.relationships |
| 130 | + | { |
| 131 | + | RelationshipExecutionCategory::Local |
| 132 | + | } else { |
| 133 | + | match target_source.capabilities.foreach { |
| 134 | + | // TODO: When we support naive relationships for connectors not implementing foreach, |
| 135 | + | // add another match arm / return enum variant |
| 136 | + | () => RelationshipExecutionCategory::RemoteForEach, |
| 137 | + | } |
| 138 | + | } |
| 139 | + | } |
| 140 | + | |
| 141 | + | pub(crate) fn generate_relationship_ir<'s>( |
| 142 | + | field: &Field<'s, GDS>, |
| 143 | + | annotation: &'s ModelRelationshipAnnotation, |
| 144 | + | data_connector: &'s resolved::data_connector::DataConnector, |
| 145 | + | type_mappings: &'s BTreeMap<Qualified<CustomTypeName>, resolved::types::TypeMapping>, |
| 146 | + | session_variables: &SessionVariables, |
| 147 | + | usage_counts: &mut UsagesCounts, |
| 148 | + | ) -> Result<FieldSelection<'s>, error::Error> { |
| 149 | + | // Add the target model being used in the usage counts |
| 150 | + | count_model(annotation.model_name.clone(), usage_counts); |
| 151 | + | let field_call = field.field_call()?; |
| 152 | + | |
| 153 | + | let mut limit = None; |
| 154 | + | let mut offset = None; |
| 155 | + | let mut filter_clause = Vec::new(); |
| 156 | + | let mut order_by = None; |
| 157 | + | |
| 158 | + | for argument in field_call.arguments.values() { |
| 159 | + | match argument.info.generic { |
| 160 | + | annotation @ Annotation::Input(argument_annotation) => match argument_annotation { |
| 161 | + | InputAnnotation::Model(model_argument_annotation) => { |
| 162 | + | match model_argument_annotation { |
| 163 | + | ModelInputAnnotation::ModelLimitArgument => { |
| 164 | + | limit = Some(argument.value.as_int_u32()?) |
| 165 | + | } |
| 166 | + | ModelInputAnnotation::ModelOffsetArgument => { |
| 167 | + | offset = Some(argument.value.as_int_u32()?) |
| 168 | + | } |
| 169 | + | ModelInputAnnotation::ModelFilterExpression => { |
| 170 | + | filter_clause = resolve_filter_expression(argument.value.as_object()?)? |
| 171 | + | } |
| 172 | + | ModelInputAnnotation::ModelOrderByExpression => { |
| 173 | + | order_by = Some(build_ndc_order_by(argument)?) |
| 174 | + | } |
| 175 | + | _ => { |
| 176 | + | return Err(error::InternalEngineError::UnexpectedAnnotation { |
| 177 | + | annotation: annotation.clone(), |
| 178 | + | })? |
| 179 | + | } |
| 180 | + | } |
| 181 | + | } |
| 182 | + | _ => { |
| 183 | + | return Err(error::InternalEngineError::UnexpectedAnnotation { |
| 184 | + | annotation: annotation.clone(), |
| 185 | + | })? |
| 186 | + | } |
| 187 | + | }, |
| 188 | + | |
| 189 | + | annotation => { |
| 190 | + | return Err(error::InternalEngineError::UnexpectedAnnotation { |
| 191 | + | annotation: annotation.clone(), |
| 192 | + | })? |
| 193 | + | } |
| 194 | + | } |
| 195 | + | } |
| 196 | + | |
| 197 | + | let target_source = |
| 198 | + | annotation |
| 199 | + | .target_source |
| 200 | + | .as_ref() |
| 201 | + | .ok_or_else(|| match &field.selection_set.type_name { |
| 202 | + | Some(type_name) => { |
| 203 | + | error::Error::from(error::InternalDeveloperError::NoSourceDataConnector { |
| 204 | + | type_name: type_name.clone(), |
| 205 | + | field_name: field_call.name.clone(), |
| 206 | + | }) |
| 207 | + | } |
| 208 | + | None => error::Error::from(normalized_ast::Error::NoTypenameFound), |
| 209 | + | })?; |
| 210 | + | match relationship_execution_category(target_source, data_connector) { |
| 211 | + | RelationshipExecutionCategory::Local => build_local_relationship( |
| 212 | + | field, |
| 213 | + | field_call, |
| 214 | + | annotation, |
| 215 | + | data_connector, |
| 216 | + | type_mappings, |
| 217 | + | target_source, |
| 218 | + | filter_clause, |
| 219 | + | limit, |
| 220 | + | offset, |
| 221 | + | order_by, |
| 222 | + | session_variables, |
| 223 | + | usage_counts, |
| 224 | + | ), |
| 225 | + | RelationshipExecutionCategory::RemoteForEach => build_remote_relationship( |
| 226 | + | field, |
| 227 | + | field_call, |
| 228 | + | annotation, |
| 229 | + | type_mappings, |
| 230 | + | target_source, |
| 231 | + | filter_clause, |
| 232 | + | limit, |
| 233 | + | offset, |
| 234 | + | order_by, |
| 235 | + | session_variables, |
| 236 | + | usage_counts, |
| 237 | + | ), |
| 238 | + | } |
| 239 | + | } |
| 240 | + | |
| 241 | + | #[allow(clippy::too_many_arguments)] |
| 242 | + | pub(crate) fn build_local_relationship<'s>( |
| 243 | + | field: &normalized_ast::Field<'s, GDS>, |
| 244 | + | field_call: &normalized_ast::FieldCall<'s, GDS>, |
| 245 | + | annotation: &'s ModelRelationshipAnnotation, |
| 246 | + | data_connector: &'s resolved::data_connector::DataConnector, |
| 247 | + | type_mappings: &'s BTreeMap<Qualified<CustomTypeName>, resolved::types::TypeMapping>, |
| 248 | + | target_source: &'s ModelTargetSource, |
| 249 | + | filter_clause: Vec<ndc::models::Expression>, |
| 250 | + | limit: Option<u32>, |
| 251 | + | offset: Option<u32>, |
| 252 | + | order_by: Option<ndc::models::OrderBy>, |
| 253 | + | session_variables: &SessionVariables, |
| 254 | + | usage_counts: &mut UsagesCounts, |
| 255 | + | ) -> Result<FieldSelection<'s>, error::Error> { |
| 256 | + | let relationships_ir = model_selection_ir( |
| 257 | + | &field.selection_set, |
| 258 | + | &annotation.target_type, |
| 259 | + | &target_source.model, |
| 260 | + | BTreeMap::new(), |
| 261 | + | filter_clause, |
| 262 | + | permissions::get_select_filter_predicate(field_call)?, |
| 263 | + | limit, |
| 264 | + | offset, |
| 265 | + | order_by, |
| 266 | + | session_variables, |
| 267 | + | usage_counts, |
| 268 | + | )?; |
| 269 | + | let rel_info = RelationshipInfo { |
| 270 | + | annotation, |
| 271 | + | source_data_connector: data_connector, |
| 272 | + | source_type_mappings: type_mappings, |
| 273 | + | target_source, |
| 274 | + | }; |
| 275 | + | |
| 276 | + | // Relationship names needs to be unique across the IR. This is so that, the |
| 277 | + | // NDC can use these names to figure out what joins to use. |
| 278 | + | // A single "source type" can have only one relationship with a given name, |
| 279 | + | // hence the relationship name in the IR is a tuple between the source type |
| 280 | + | // and the relationship name. |
| 281 | + | // Relationship name = (source_type, relationship_name) |
| 282 | + | let relationship_name = |
| 283 | + | serde_json::to_string(&(&annotation.source_type, &annotation.relationship_name))?; |
| 284 | + | |
| 285 | + | Ok(FieldSelection::LocalRelationship { |
| 286 | + | query: relationships_ir, |
| 287 | + | name: relationship_name, |
| 288 | + | relationship_info: rel_info, |
| 289 | + | }) |
| 290 | + | } |
| 291 | + | |
| 292 | + | #[allow(clippy::too_many_arguments)] |
| 293 | + | pub(crate) fn build_remote_relationship<'n, 's>( |
| 294 | + | field: &'n normalized_ast::Field<'s, GDS>, |
| 295 | + | field_call: &'n normalized_ast::FieldCall<'s, GDS>, |
| 296 | + | annotation: &'s ModelRelationshipAnnotation, |
| 297 | + | type_mappings: &'s BTreeMap<Qualified<CustomTypeName>, resolved::types::TypeMapping>, |
| 298 | + | target_source: &'s ModelTargetSource, |
| 299 | + | filter_clause: Vec<ndc::models::Expression>, |
| 300 | + | limit: Option<u32>, |
| 301 | + | offset: Option<u32>, |
| 302 | + | order_by: Option<ndc::models::OrderBy>, |
| 303 | + | session_variables: &SessionVariables, |
| 304 | + | usage_counts: &mut UsagesCounts, |
| 305 | + | ) -> Result<FieldSelection<'s>, error::Error> { |
| 306 | + | let mut join_mapping: Vec<(SourceField, TargetField)> = vec![]; |
| 307 | + | for resolved::relationship::RelationshipModelMapping { |
| 308 | + | source_field: source_field_path, |
| 309 | + | target_field: target_field_path, |
| 310 | + | } in annotation.mappings.iter() |
| 311 | + | { |
| 312 | + | let source_column = get_field_mapping_of_field_name( |
| 313 | + | type_mappings, |
| 314 | + | &annotation.source_type, |
| 315 | + | &annotation.relationship_name, |
| 316 | + | &source_field_path.field_name, |
| 317 | + | )?; |
| 318 | + | let target_column = get_field_mapping_of_field_name( |
| 319 | + | &target_source.model.type_mappings, |
| 320 | + | &annotation.target_type, |
| 321 | + | &annotation.relationship_name, |
| 322 | + | &target_field_path.field_name, |
| 323 | + | )?; |
| 324 | + | |
| 325 | + | let source_field = (source_field_path.field_name.clone(), source_column); |
| 326 | + | let target_field = (target_field_path.field_name.clone(), target_column); |
| 327 | + | join_mapping.push((source_field, target_field)); |
| 328 | + | } |
| 329 | + | let mut remote_relationships_ir = model_selection_ir( |
| 330 | + | &field.selection_set, |
| 331 | + | &annotation.target_type, |
| 332 | + | &target_source.model, |
| 333 | + | BTreeMap::new(), |
| 334 | + | filter_clause, |
| 335 | + | permissions::get_select_filter_predicate(field_call)?, |
| 336 | + | limit, |
| 337 | + | offset, |
| 338 | + | order_by, |
| 339 | + | session_variables, |
| 340 | + | usage_counts, |
| 341 | + | )?; |
| 342 | + | |
| 343 | + | // modify `ModelSelection` to include the join condition in `where` with a variable |
| 344 | + | for (_source, (_field_name, field)) in &join_mapping { |
| 345 | + | let target_value_variable = format!("${}", &field.column); |
| 346 | + | let comparison_exp = ndc::models::Expression::BinaryComparisonOperator { |
| 347 | + | column: ndc::models::ComparisonTarget::Column { |
| 348 | + | name: field.column.clone(), |
| 349 | + | path: vec![], |
| 350 | + | }, |
| 351 | + | operator: ndc::models::BinaryComparisonOperator::Equal, |
| 352 | + | value: ndc::models::ComparisonValue::Variable { |
| 353 | + | name: target_value_variable, |
| 354 | + | }, |
| 355 | + | }; |
| 356 | + | remote_relationships_ir.filter_clause.push(comparison_exp); |
| 357 | + | } |
| 358 | + | let rel_info = RemoteRelationshipInfo { |
| 359 | + | annotation, |
| 360 | + | join_mapping, |
| 361 | + | }; |
| 362 | + | Ok(FieldSelection::RemoteRelationship { |
| 363 | + | ir: remote_relationships_ir, |
| 364 | + | relationship_info: rel_info, |
| 365 | + | }) |
| 366 | + | } |
| 367 | + | |
| 368 | + | fn get_field_mapping_of_field_name( |
| 369 | + | type_mappings: &BTreeMap<Qualified<CustomTypeName>, resolved::types::TypeMapping>, |
| 370 | + | type_name: &Qualified<CustomTypeName>, |
| 371 | + | relationship_name: &RelationshipName, |
| 372 | + | field_name: &FieldName, |
| 373 | + | ) -> Result<resolved::types::FieldMapping, error::Error> { |
| 374 | + | let type_mapping = type_mappings.get(type_name).ok_or_else(|| { |
| 375 | + | error::InternalDeveloperError::TypeMappingNotFoundForRelationship { |
| 376 | + | type_name: type_name.clone(), |
| 377 | + | relationship_name: relationship_name.clone(), |
| 378 | + | } |
| 379 | + | })?; |
| 380 | + | match type_mapping { |
| 381 | + | resolved::types::TypeMapping::Object { field_mappings } => Ok(field_mappings |
| 382 | + | .get(field_name) |
| 383 | + | .ok_or_else( |
| 384 | + | || error::InternalDeveloperError::FieldMappingNotFoundForRelationship { |
| 385 | + | type_name: type_name.clone(), |
| 386 | + | relationship_name: relationship_name.clone(), |
| 387 | + | field_name: field_name.clone(), |
| 388 | + | }, |
| 389 | + | )? |
| 390 | + | .clone()), |
| 391 | + | } |
| 392 | + | } |
| 393 | + | |