1#![allow(deprecated)] use std::collections::HashMap;
3use std::time::Instant;
4
5use type_bridge_core_lib::_schema::TypeSchema;
6use type_bridge_core_lib::ast::Clause;
7use type_bridge_core_lib::compiler::QueryCompiler;
8use type_bridge_core_lib::validation::ValidationEngine;
9
10use crate::error::PipelineError;
11use crate::executor::QueryExecutor;
12use crate::interceptor::crud_interceptor::{CrudInterceptor, CrudInterceptorAdapter};
13use crate::interceptor::{Interceptor, InterceptorChain, RequestContext};
14#[cfg(feature = "v2-query")]
15use crate::interceptor::{V2PolicyOutcome, V2PolicyRequest, V3CommitOutcome, V3PolicyPlan};
16use crate::schema_source::SchemaSource;
17
18pub(crate) const UNAUTHENTICATED_CLIENT_ID: &str = "unknown";
21
22pub struct QueryInput {
24 pub database: Option<String>,
26 pub transaction_type: String,
28 pub clauses: Vec<Clause>,
30 pub metadata: HashMap<String, serde_json::Value>,
32}
33
34pub struct ValidateInput {
36 pub clauses: Vec<Clause>,
38}
39
40#[derive(Debug)]
42pub struct QueryOutput {
43 pub results: serde_json::Value,
45 pub request_id: String,
47 pub execution_time_ms: u64,
49 pub interceptors_applied: Vec<String>,
51}
52
53#[derive(Debug)]
55pub struct ValidateOutput {
56 pub is_valid: bool,
58 pub errors: Vec<ValidationErrorDetail>,
60}
61
62#[derive(Debug)]
64pub struct ValidationErrorDetail {
65 pub code: String,
67 pub message: String,
69 pub path: String,
71}
72
73#[cfg_attr(coverage_nightly, coverage(off))]
74fn log_query_execution(database: &str, transaction_type: &str, typeql: &str) {
75 tracing::info!(database, transaction_type, "Executing query");
76 tracing::debug!(typeql, "Compiled TypeQL");
77}
78
79pub struct QueryPipeline {
100 schema: Option<TypeSchema>,
101 validation_engine: ValidationEngine,
102 interceptor_chain: InterceptorChain,
103 default_database: String,
104 executor: Box<dyn QueryExecutor>,
105 skip_validation: bool,
106}
107
108impl QueryPipeline {
109 #[cfg(feature = "v2-query")]
115 pub fn validate_v2_coverage(&self) -> Result<(), PipelineError> {
116 self.interceptor_chain
117 .ensure_v2_coverage()
118 .map_err(|error| PipelineError::Interceptor(error.to_string()))
119 }
120
121 #[cfg(feature = "v2-query")]
124 pub fn v2_request_context(
125 &self,
126 metadata: HashMap<String, serde_json::Value>,
127 ) -> Result<RequestContext, PipelineError> {
128 self.validate_v2_coverage()?;
129 Ok(RequestContext {
130 request_id: uuid::Uuid::new_v4().to_string(),
131 client_id: UNAUTHENTICATED_CLIENT_ID.to_owned(),
132 database: self.default_database.clone(),
133 transaction_type: "read".to_owned(),
134 metadata,
135 timestamp: chrono::Utc::now(),
136 crud_info: None,
137 })
138 }
139
140 #[cfg(feature = "v2-query")]
146 pub fn validate_v3_coverage(&self) -> Result<(), PipelineError> {
147 self.interceptor_chain
148 .ensure_v3_coverage()
149 .map_err(|error| PipelineError::Interceptor(error.to_string()))
150 }
151
152 #[cfg(feature = "v2-query")]
155 pub fn v3_request_context(
156 &self,
157 metadata: HashMap<String, serde_json::Value>,
158 ) -> Result<RequestContext, PipelineError> {
159 self.validate_v3_coverage()?;
160 self.v2_request_context(metadata)
161 }
162
163 #[cfg(feature = "v2-query")]
166 pub async fn begin_v2_request(
167 &self,
168 context: &mut RequestContext,
169 ) -> Result<(), PipelineError> {
170 self.interceptor_chain
171 .execute_v2_transport(context)
172 .await
173 .map_err(|error| PipelineError::Interceptor(error.to_string()))
174 }
175
176 #[cfg(feature = "v2-query")]
178 pub async fn authorize_v2_request(
179 &self,
180 request: &V2PolicyRequest<'_>,
181 context: &mut RequestContext,
182 ) -> Result<(), PipelineError> {
183 self.interceptor_chain
184 .execute_v2_request(request, context)
185 .await
186 .map_err(|error| PipelineError::Interceptor(error.to_string()))
187 }
188
189 #[cfg(feature = "v2-query")]
192 pub async fn authorize_v3_write(
193 &self,
194 context: &RequestContext,
195 ) -> Result<bool, PipelineError> {
196 self.interceptor_chain
197 .execute_v3_write_authority(context)
198 .await
199 .map_err(|error| PipelineError::Interceptor(error.to_string()))
200 }
201
202 #[cfg(feature = "v2-query")]
205 pub async fn authorize_v3_plan(
206 &self,
207 index: usize,
208 plan: V3PolicyPlan<'_>,
209 context: &RequestContext,
210 ) -> Result<(), PipelineError> {
211 self.interceptor_chain
212 .execute_v3_plan(index, plan, context)
213 .await
214 .map_err(|error| PipelineError::Interceptor(error.to_string()))
215 }
216
217 #[cfg(feature = "v2-query")]
219 pub async fn observe_v3_commit(&self, outcome: &V3CommitOutcome<'_>, context: &RequestContext) {
220 self.interceptor_chain
221 .execute_v3_commit(outcome, context)
222 .await;
223 }
224
225 #[cfg(feature = "v2-query")]
227 pub async fn finish_v2_request(
228 &self,
229 outcome: &V2PolicyOutcome<'_>,
230 context: &RequestContext,
231 ) -> Result<(), PipelineError> {
232 self.interceptor_chain
233 .execute_v2_response(outcome, context)
234 .await
235 .map_err(|error| PipelineError::Interceptor(error.to_string()))
236 }
237
238 pub async fn execute_query(&self, input: QueryInput) -> Result<QueryOutput, PipelineError> {
240 let start = Instant::now();
241 let request_id = uuid::Uuid::new_v4().to_string();
242 let database = input
243 .database
244 .unwrap_or_else(|| self.default_database.clone());
245
246 let mut ctx = RequestContext {
247 request_id: request_id.clone(),
248 client_id: UNAUTHENTICATED_CLIENT_ID.to_owned(),
249 database: database.clone(),
250 transaction_type: input.transaction_type.clone(),
251 metadata: input.metadata,
252 timestamp: chrono::Utc::now(),
253 crud_info: None,
254 };
255
256 if !self.skip_validation
258 && let Some(schema) = &self.schema
259 {
260 let result = self
261 .validation_engine
262 .validate_query(&input.clauses, schema);
263 if !result.is_valid {
264 return Err(PipelineError::Validation(format!(
265 "{} validation error(s)",
266 result.errors.len()
267 )));
268 }
269 }
270
271 let clauses = self
273 .interceptor_chain
274 .execute_request(input.clauses, &mut ctx)
275 .await
276 .map_err(|e| PipelineError::Interceptor(e.to_string()))?;
277
278 let compiler = QueryCompiler::new();
280 let typeql = compiler
281 .try_compile(&clauses)
282 .map_err(|error| PipelineError::Validation(error.to_string()))?;
283 ctx.metadata.insert(
284 "compiled_typeql".to_string(),
285 serde_json::Value::String(typeql.clone()),
286 );
287
288 log_query_execution(&database, &input.transaction_type, &typeql);
290
291 let results = self
292 .executor
293 .execute(&database, &typeql, &input.transaction_type)
294 .await?;
295
296 self.interceptor_chain
298 .execute_response(&results, &ctx)
299 .await
300 .map_err(|e| PipelineError::Interceptor(e.to_string()))?;
301
302 let elapsed = start.elapsed().as_millis() as u64;
303
304 Ok(QueryOutput {
305 results,
306 request_id,
307 execution_time_ms: elapsed,
308 interceptors_applied: self
309 .interceptor_chain
310 .interceptor_names()
311 .into_iter()
312 .map(String::from)
313 .collect(),
314 })
315 }
316
317 pub fn validate(&self, input: &ValidateInput) -> Result<ValidateOutput, PipelineError> {
319 let schema = self
320 .schema
321 .as_ref()
322 .ok_or_else(|| PipelineError::Schema("No schema loaded".to_string()))?;
323
324 let result = self
325 .validation_engine
326 .validate_query(&input.clauses, schema);
327
328 let errors = result
329 .errors
330 .iter()
331 .map(|e| ValidationErrorDetail {
332 code: e.code.clone(),
333 message: e.message.clone(),
334 path: e.path.clone(),
335 })
336 .collect();
337
338 Ok(ValidateOutput {
339 is_valid: result.is_valid,
340 errors,
341 })
342 }
343
344 pub fn schema(&self) -> Option<&TypeSchema> {
346 self.schema.as_ref()
347 }
348
349 pub fn is_connected(&self) -> bool {
351 self.executor.is_connected()
352 }
353
354 pub fn default_database(&self) -> &str {
356 &self.default_database
357 }
358}
359
360pub struct PipelineBuilder {
377 executor: Box<dyn QueryExecutor>,
378 schema_source: Option<Box<dyn SchemaSource>>,
379 interceptors: Vec<Box<dyn Interceptor>>,
380 default_database: String,
381 skip_validation: bool,
382}
383
384impl PipelineBuilder {
385 pub fn new(executor: impl QueryExecutor + 'static) -> Self {
387 Self {
388 executor: Box::new(executor),
389 schema_source: None,
390 interceptors: Vec::new(),
391 default_database: String::new(),
392 skip_validation: false,
393 }
394 }
395
396 pub fn with_schema_source(mut self, source: impl SchemaSource + 'static) -> Self {
398 self.schema_source = Some(Box::new(source));
399 self
400 }
401
402 pub fn with_interceptor(mut self, interceptor: impl Interceptor + 'static) -> Self {
404 self.interceptors.push(Box::new(interceptor));
405 self
406 }
407
408 pub fn with_default_database(mut self, database: impl Into<String>) -> Self {
410 self.default_database = database.into();
411 self
412 }
413
414 pub fn with_crud_interceptor(self, interceptor: impl CrudInterceptor + 'static) -> Self {
420 self.with_interceptor(CrudInterceptorAdapter::new(interceptor))
421 }
422
423 pub fn with_skip_validation(mut self) -> Self {
428 self.skip_validation = true;
429 self
430 }
431
432 pub fn build(self) -> Result<QueryPipeline, PipelineError> {
434 let schema = match self.schema_source {
435 Some(source) => Some(source.load()?),
436 None => None,
437 };
438
439 Ok(QueryPipeline {
440 schema,
441 validation_engine: ValidationEngine::new(),
442 interceptor_chain: InterceptorChain::new(self.interceptors),
443 default_database: self.default_database,
444 executor: self.executor,
445 skip_validation: self.skip_validation,
446 })
447 }
448}
449
450#[cfg(test)]
451#[cfg_attr(coverage_nightly, coverage(off))]
452mod tests {
453 use std::future::Future;
454 use std::pin::Pin;
455 use std::sync::Arc;
456 use std::sync::atomic::{AtomicUsize, Ordering};
457
458 use type_bridge_core_lib::ast::{Constraint, Pattern, Value};
459
460 use super::*;
461 use crate::interceptor::traits::InterceptError;
462 use crate::test_helpers::{MockExecutor, make_pipeline, make_simple_clauses};
463
464 fn init_tracing() -> tracing::subscriber::DefaultGuard {
465 let subscriber = tracing_subscriber::fmt()
466 .with_max_level(tracing::Level::DEBUG)
467 .with_test_writer()
468 .finish();
469 tracing::subscriber::set_default(subscriber)
470 }
471
472 struct PassthroughInterceptor {
475 name: String,
476 }
477
478 impl Interceptor for PassthroughInterceptor {
479 fn name(&self) -> &str {
480 &self.name
481 }
482 fn on_request<'a>(
483 &'a self,
484 clauses: Vec<Clause>,
485 _ctx: &'a mut RequestContext,
486 ) -> Pin<Box<dyn Future<Output = Result<Vec<Clause>, InterceptError>> + Send + 'a>>
487 {
488 Box::pin(async move { Ok(clauses) })
489 }
490 }
491
492 struct RejectingRequestInterceptor;
493
494 impl Interceptor for RejectingRequestInterceptor {
495 fn name(&self) -> &str {
496 "rejector"
497 }
498 fn on_request<'a>(
499 &'a self,
500 _clauses: Vec<Clause>,
501 _ctx: &'a mut RequestContext,
502 ) -> Pin<Box<dyn Future<Output = Result<Vec<Clause>, InterceptError>> + Send + 'a>>
503 {
504 Box::pin(async {
505 Err(InterceptError::AccessDenied {
506 reason: "test rejection".into(),
507 })
508 })
509 }
510
511 #[cfg(feature = "v2-query")]
512 fn supports_v2(&self) -> bool {
513 true
514 }
515
516 #[cfg(feature = "v2-query")]
517 fn on_v2_transport<'a>(
518 &'a self,
519 _ctx: &'a mut RequestContext,
520 ) -> Pin<Box<dyn Future<Output = Result<(), InterceptError>> + Send + 'a>> {
521 Box::pin(async {
522 Err(InterceptError::AccessDenied {
523 reason: "test rejection".into(),
524 })
525 })
526 }
527 }
528
529 struct RejectingResponseInterceptor;
530
531 impl Interceptor for RejectingResponseInterceptor {
532 fn name(&self) -> &str {
533 "resp-rejector"
534 }
535 fn on_request<'a>(
536 &'a self,
537 clauses: Vec<Clause>,
538 _ctx: &'a mut RequestContext,
539 ) -> Pin<Box<dyn Future<Output = Result<Vec<Clause>, InterceptError>> + Send + 'a>>
540 {
541 Box::pin(async move { Ok(clauses) })
542 }
543 fn on_response<'a>(
544 &'a self,
545 _result: &'a serde_json::Value,
546 _ctx: &'a RequestContext,
547 ) -> Pin<Box<dyn Future<Output = Result<(), InterceptError>> + Send + 'a>> {
548 Box::pin(async { Err(InterceptError::Internal("response rejected".into())) })
549 }
550 }
551
552 struct CountingInterceptor {
553 name: String,
554 count: Arc<AtomicUsize>,
555 }
556
557 impl Interceptor for CountingInterceptor {
558 fn name(&self) -> &str {
559 &self.name
560 }
561 fn on_request<'a>(
562 &'a self,
563 clauses: Vec<Clause>,
564 _ctx: &'a mut RequestContext,
565 ) -> Pin<Box<dyn Future<Output = Result<Vec<Clause>, InterceptError>> + Send + 'a>>
566 {
567 Box::pin(async move {
568 self.count.fetch_add(1, Ordering::SeqCst);
569 Ok(clauses)
570 })
571 }
572 }
573
574 struct FailingSchemaSource;
576
577 impl crate::schema_source::SchemaSource for FailingSchemaSource {
578 fn load(&self) -> Result<TypeSchema, PipelineError> {
579 Err(PipelineError::Schema("source failed".into()))
580 }
581 }
582
583 fn make_query_input(clauses: Vec<Clause>) -> QueryInput {
584 QueryInput {
585 database: None,
586 transaction_type: "read".to_string(),
587 clauses,
588 metadata: HashMap::new(),
589 }
590 }
591
592 fn make_query_input_with_db(clauses: Vec<Clause>, db: &str) -> QueryInput {
593 QueryInput {
594 database: Some(db.to_string()),
595 transaction_type: "read".to_string(),
596 clauses,
597 metadata: HashMap::new(),
598 }
599 }
600
601 #[test]
606 fn builder_without_schema_source() {
607 let pipeline = PipelineBuilder::new(MockExecutor::new()).build().unwrap();
608 assert!(pipeline.schema().is_none());
609 }
610
611 #[test]
612 fn builder_with_valid_schema_source() {
613 let pipeline = make_pipeline(MockExecutor::new(), true);
614 assert!(pipeline.schema().is_some());
615 let schema = pipeline.schema().unwrap();
616 assert!(schema.entities.contains_key("person"));
617 }
618
619 #[test]
620 fn builder_with_failing_schema_source() {
621 let result = PipelineBuilder::new(MockExecutor::new())
622 .with_schema_source(FailingSchemaSource)
623 .build();
624 let err = result.err().expect("Expected build error");
625 assert!(matches!(&err, PipelineError::Schema(msg) if msg.contains("source failed")));
626 }
627
628 #[test]
629 fn builder_with_default_database() {
630 let pipeline = PipelineBuilder::new(MockExecutor::new())
631 .with_default_database("mydb")
632 .build()
633 .unwrap();
634 assert_eq!(pipeline.default_database(), "mydb");
635 }
636
637 #[test]
638 fn builder_default_empty_database() {
639 let pipeline = PipelineBuilder::new(MockExecutor::new()).build().unwrap();
640 assert_eq!(pipeline.default_database(), "");
641 }
642
643 #[tokio::test]
644 async fn builder_with_interceptors() {
645 let pipeline = PipelineBuilder::new(MockExecutor::new())
646 .with_interceptor(PassthroughInterceptor {
647 name: "first".into(),
648 })
649 .with_interceptor(PassthroughInterceptor {
650 name: "second".into(),
651 })
652 .build()
653 .unwrap();
654 assert!(pipeline.schema().is_none());
655
656 let input = make_query_input(vec![]);
657 let output = pipeline.execute_query(input).await.unwrap();
658 assert_eq!(output.interceptors_applied, vec!["first", "second"]);
659 }
660
661 #[tokio::test]
662 #[cfg(feature = "v2-query")]
663 async fn v2_policy_rejection_is_fail_closed() {
664 let pipeline = PipelineBuilder::new(MockExecutor::new())
665 .with_interceptor(RejectingRequestInterceptor)
666 .build()
667 .unwrap();
668 let mut context = pipeline
669 .v2_request_context(HashMap::from([(
670 "transport".to_owned(),
671 serde_json::json!("v2"),
672 )]))
673 .expect("V2-aware policy coverage");
674 let error = pipeline
675 .begin_v2_request(&mut context)
676 .await
677 .expect_err("the same request policy must gate V2 envelopes");
678 assert!(
679 matches!(error, PipelineError::Interceptor(message) if message.contains("test rejection"))
680 );
681 }
682
683 #[cfg(feature = "v2-query")]
684 struct RewritingInterceptor;
685
686 #[cfg(feature = "v2-query")]
687 impl Interceptor for RewritingInterceptor {
688 fn name(&self) -> &str {
689 "rewriter"
690 }
691
692 fn on_request<'a>(
693 &'a self,
694 _clauses: Vec<Clause>,
695 _ctx: &'a mut RequestContext,
696 ) -> Pin<Box<dyn Future<Output = Result<Vec<Clause>, InterceptError>> + Send + 'a>>
697 {
698 Box::pin(async { Ok(make_simple_clauses()) })
699 }
700 }
701
702 #[tokio::test]
703 #[cfg(feature = "v2-query")]
704 async fn v2_rejects_legacy_ast_policies_without_typed_coverage() {
705 let pipeline = PipelineBuilder::new(MockExecutor::new())
706 .with_interceptor(RewritingInterceptor)
707 .build()
708 .unwrap();
709 let startup_error = pipeline
710 .validate_v2_coverage()
711 .expect_err("startup must reject a legacy-only policy before routing");
712 assert!(
713 matches!(startup_error, PipelineError::Interceptor(message) if message.contains("does not declare typed V2 coverage"))
714 );
715 let error = pipeline
716 .v2_request_context(HashMap::new())
717 .expect_err("request admission must retain the defensive recheck");
718 assert!(
719 matches!(error, PipelineError::Interceptor(message) if message.contains("does not declare typed V2 coverage"))
720 );
721 }
722
723 #[tokio::test]
728 async fn execute_query_uses_input_database() {
729 let executor = MockExecutor::new();
730 let calls = executor.calls.clone();
731 let pipeline = make_pipeline(executor, false);
732
733 let input = make_query_input_with_db(vec![], "custom_db");
734 pipeline.execute_query(input).await.unwrap();
735
736 let recorded = calls.lock().unwrap();
737 assert_eq!(recorded[0].0, "custom_db");
738 }
739
740 #[tokio::test]
741 async fn execute_query_uses_default_database_when_none() {
742 let executor = MockExecutor::new();
743 let calls = executor.calls.clone();
744 let pipeline = make_pipeline(executor, false);
745
746 let input = make_query_input(vec![]);
747 pipeline.execute_query(input).await.unwrap();
748
749 let recorded = calls.lock().unwrap();
750 assert_eq!(recorded[0].0, "test_db"); }
752
753 #[tokio::test]
754 async fn execute_query_skips_validation_when_no_schema() {
755 let pipeline = make_pipeline(MockExecutor::new(), false);
756 let clauses = vec![Clause::Match(vec![Pattern::Entity {
757 variable: "x".to_string(),
758 type_name: "nonexistent_type".to_string(),
759 constraints: vec![],
760 is_strict: false,
761 }])];
762 let input = make_query_input(clauses);
763 let result = pipeline.execute_query(input).await;
764 assert!(result.is_ok());
765 }
766
767 #[tokio::test]
768 async fn execute_query_validates_when_schema_present_valid() {
769 let pipeline = make_pipeline(MockExecutor::new(), true);
770 let input = make_query_input(make_simple_clauses());
771 let result = pipeline.execute_query(input).await;
772 assert!(result.is_ok());
773 }
774
775 #[tokio::test]
776 async fn execute_query_validates_when_schema_present_invalid() {
777 let pipeline = make_pipeline(MockExecutor::new(), true);
778 let clauses = vec![Clause::Match(vec![Pattern::Entity {
779 variable: "p".to_string(),
780 type_name: "person".to_string(),
781 constraints: vec![Constraint::Has {
782 attr_name: "nonexistent_attr".to_string(),
783 value: Value::Literal(type_bridge_core_lib::ast::LiteralValue {
784 value: serde_json::json!("val"),
785 value_type: "string".to_string(),
786 }),
787 }],
788 is_strict: false,
789 }])];
790 let input = make_query_input(clauses);
791 let result = pipeline.execute_query(input).await;
792 let err = result.unwrap_err();
793 assert!(matches!(&err, PipelineError::Validation(msg) if msg.contains("validation error")));
794 }
795
796 #[tokio::test]
797 async fn execute_query_request_interceptor_failure() {
798 assert_eq!(RejectingRequestInterceptor.name(), "rejector");
799 let pipeline = PipelineBuilder::new(MockExecutor::new())
800 .with_interceptor(RejectingRequestInterceptor)
801 .build()
802 .unwrap();
803 let input = make_query_input(vec![]);
804 let result = pipeline.execute_query(input).await;
805 let err = result.unwrap_err();
806 assert!(matches!(&err, PipelineError::Interceptor(msg) if msg.contains("test rejection")));
807 }
808
809 #[tokio::test]
810 async fn execute_query_executor_failure() {
811 let pipeline = make_pipeline(MockExecutor::failing("db crash"), false);
812 let input = make_query_input(vec![]);
813 let result = pipeline.execute_query(input).await;
814 let err = result.unwrap_err();
815 assert!(matches!(&err, PipelineError::QueryExecution(msg) if msg.contains("db crash")));
816 }
817
818 #[tokio::test]
819 async fn execute_query_response_interceptor_failure() {
820 assert_eq!(RejectingResponseInterceptor.name(), "resp-rejector");
821 let pipeline = PipelineBuilder::new(MockExecutor::new())
822 .with_interceptor(RejectingResponseInterceptor)
823 .build()
824 .unwrap();
825 let input = make_query_input(vec![]);
826 let result = pipeline.execute_query(input).await;
827 let err = result.unwrap_err();
828 assert!(
829 matches!(&err, PipelineError::Interceptor(msg) if msg.contains("response rejected"))
830 );
831 }
832
833 #[tokio::test]
834 async fn execute_query_success_output_fields() {
835 let _guard = init_tracing();
836 let count = Arc::new(AtomicUsize::new(0));
837 let pipeline =
838 PipelineBuilder::new(MockExecutor::with_result(serde_json::json!({"ok": true})))
839 .with_default_database("test_db")
840 .with_interceptor(CountingInterceptor {
841 name: "counter".into(),
842 count: count.clone(),
843 })
844 .build()
845 .unwrap();
846
847 let input = make_query_input(vec![]);
848 let output = pipeline.execute_query(input).await.unwrap();
849
850 assert!(!output.request_id.is_empty());
851 assert_eq!(output.results, serde_json::json!({"ok": true}));
852 assert_eq!(output.interceptors_applied, vec!["counter"]);
853 assert_eq!(count.load(Ordering::SeqCst), 1);
854 }
855
856 #[tokio::test]
857 async fn execute_query_empty_clauses_success() {
858 let pipeline = make_pipeline(MockExecutor::new(), false);
859 let input = make_query_input(vec![]);
860 let result = pipeline.execute_query(input).await;
861 assert!(result.is_ok());
862 }
863
864 #[tokio::test]
865 async fn execute_query_compiled_typeql_in_metadata() {
866 let executor = MockExecutor::new();
867 let calls = executor.calls.clone();
868 let pipeline = make_pipeline(executor, false);
869
870 let clauses = make_simple_clauses();
871 let input = make_query_input(clauses);
872 pipeline.execute_query(input).await.unwrap();
873
874 let recorded = calls.lock().unwrap();
875 assert!(!recorded[0].1.is_empty());
876 }
877
878 #[tokio::test]
879 async fn execute_query_passes_transaction_type() {
880 let executor = MockExecutor::new();
881 let calls = executor.calls.clone();
882 let pipeline = make_pipeline(executor, false);
883
884 let input = QueryInput {
885 database: None,
886 transaction_type: "write".to_string(),
887 clauses: vec![],
888 metadata: HashMap::new(),
889 };
890 pipeline.execute_query(input).await.unwrap();
891
892 let recorded = calls.lock().unwrap();
893 assert_eq!(recorded[0].2, "write");
894 }
895
896 #[test]
901 fn validate_no_schema_returns_error() {
902 let pipeline = make_pipeline(MockExecutor::new(), false);
903 let input = ValidateInput { clauses: vec![] };
904 let result = pipeline.validate(&input);
905 let err = result.unwrap_err();
906 assert!(matches!(&err, PipelineError::Schema(msg) if msg.contains("No schema loaded")));
907 }
908
909 #[test]
910 fn validate_valid_clauses() {
911 let pipeline = make_pipeline(MockExecutor::new(), true);
912 let input = ValidateInput {
913 clauses: make_simple_clauses(),
914 };
915 let result = pipeline.validate(&input).unwrap();
916 assert!(result.is_valid);
917 assert!(result.errors.is_empty());
918 }
919
920 #[test]
921 fn validate_invalid_clauses() {
922 let pipeline = make_pipeline(MockExecutor::new(), true);
923 let input = ValidateInput {
924 clauses: vec![Clause::Match(vec![Pattern::Entity {
925 variable: "p".to_string(),
926 type_name: "person".to_string(),
927 constraints: vec![Constraint::Has {
928 attr_name: "nonexistent_attr".to_string(),
929 value: Value::Literal(type_bridge_core_lib::ast::LiteralValue {
930 value: serde_json::json!("val"),
931 value_type: "string".to_string(),
932 }),
933 }],
934 is_strict: false,
935 }])],
936 };
937 let result = pipeline.validate(&input).unwrap();
938 assert!(!result.is_valid);
939 assert!(!result.errors.is_empty());
940 }
941
942 #[test]
943 fn validate_error_detail_fields() {
944 let pipeline = make_pipeline(MockExecutor::new(), true);
945 let input = ValidateInput {
946 clauses: vec![Clause::Match(vec![Pattern::Entity {
947 variable: "x".to_string(),
948 type_name: "person".to_string(),
949 constraints: vec![Constraint::Has {
950 attr_name: "nonexistent_attr".to_string(),
951 value: Value::Literal(type_bridge_core_lib::ast::LiteralValue {
952 value: serde_json::json!("val"),
953 value_type: "string".to_string(),
954 }),
955 }],
956 is_strict: false,
957 }])],
958 };
959 let result = pipeline.validate(&input).unwrap();
960 assert!(!result.is_valid);
961 let error = &result.errors[0];
962 assert!(!error.code.is_empty());
963 assert!(!error.message.is_empty());
964 }
965
966 #[test]
967 fn validate_empty_clauses_with_schema() {
968 let pipeline = make_pipeline(MockExecutor::new(), true);
969 let input = ValidateInput { clauses: vec![] };
970 let result = pipeline.validate(&input).unwrap();
971 assert!(result.is_valid);
972 }
973
974 #[test]
979 fn schema_returns_some_when_loaded() {
980 let pipeline = make_pipeline(MockExecutor::new(), true);
981 assert!(pipeline.schema().is_some());
982 }
983
984 #[test]
985 fn schema_returns_none_when_not_loaded() {
986 let pipeline = make_pipeline(MockExecutor::new(), false);
987 assert!(pipeline.schema().is_none());
988 }
989
990 #[test]
991 fn is_connected_delegates_to_executor() {
992 let executor = MockExecutor::new();
993 *executor.connected.lock().unwrap() = true;
994 let pipeline = make_pipeline(executor, false);
995 assert!(pipeline.is_connected());
996 }
997
998 #[test]
999 fn is_connected_false_when_executor_disconnected() {
1000 let executor = MockExecutor::new();
1001 *executor.connected.lock().unwrap() = false;
1002 let pipeline = make_pipeline(executor, false);
1003 assert!(!pipeline.is_connected());
1004 }
1005
1006 #[test]
1007 fn default_database_returns_configured_value() {
1008 let pipeline = PipelineBuilder::new(MockExecutor::new())
1009 .with_default_database("my_database")
1010 .build()
1011 .unwrap();
1012 assert_eq!(pipeline.default_database(), "my_database");
1013 }
1014
1015 #[test]
1016 fn default_database_empty_when_not_set() {
1017 let pipeline = PipelineBuilder::new(MockExecutor::new()).build().unwrap();
1018 assert_eq!(pipeline.default_database(), "");
1019 }
1020}