fraiseql-core 2.12.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
#![allow(clippy::iter_on_single_items)] // Reason: test uses single-element iter for clarity

use async_trait::async_trait;
use fraiseql_db::ViewName;
use serde_json::json;

use super::*;
use crate::{
    cache::{CacheConfig, FactTableVersionStrategy},
    db::WhereOperator,
    schema::CompiledSchema,
};

/// Mock database adapter for testing.
struct MockAdapter {
    /// Number of times `execute_where_query` was called.
    call_count:     std::sync::atomic::AtomicU32,
    /// Number of times `execute_raw_query` was called.
    raw_call_count: std::sync::atomic::AtomicU32,
}

impl MockAdapter {
    fn new() -> Self {
        Self {
            call_count:     std::sync::atomic::AtomicU32::new(0),
            raw_call_count: std::sync::atomic::AtomicU32::new(0),
        }
    }

    fn call_count(&self) -> u32 {
        // Return sum of both call counts for backward compatibility
        self.call_count.load(std::sync::atomic::Ordering::SeqCst)
            + self.raw_call_count.load(std::sync::atomic::Ordering::SeqCst)
    }
}

// Reason: DatabaseAdapter is defined with #[async_trait]; all implementations must match
// its transformed method signatures to satisfy the trait contract
// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
#[async_trait]
impl DatabaseAdapter for MockAdapter {
    async fn execute_with_projection(
        &self,
        _view: &str,
        _projection: Option<&crate::schema::SqlProjectionHint>,
        _where_clause: Option<&WhereClause>,
        _limit: Option<u32>,
        _offset: Option<u32>,
        _order_by: Option<&[OrderByClause]>,
    ) -> Result<Vec<JsonbValue>> {
        self.call_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

        // Return mock data (same as execute_where_query)
        Ok(vec![
            JsonbValue::new(json!({"id": 1, "name": "Alice"})),
            JsonbValue::new(json!({"id": 2, "name": "Bob"})),
        ])
    }

    async fn execute_where_query(
        &self,
        _view: &str,
        _where_clause: Option<&WhereClause>,
        _limit: Option<u32>,
        _offset: Option<u32>,
        _order_by: Option<&[OrderByClause]>,
    ) -> Result<Vec<JsonbValue>> {
        self.call_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

        // Return mock data
        Ok(vec![
            JsonbValue::new(json!({"id": 1, "name": "Alice"})),
            JsonbValue::new(json!({"id": 2, "name": "Bob"})),
        ])
    }

    fn database_type(&self) -> DatabaseType {
        DatabaseType::PostgreSQL
    }

    async fn health_check(&self) -> Result<()> {
        Ok(())
    }

    fn pool_metrics(&self) -> PoolMetrics {
        PoolMetrics {
            total_connections:  10,
            idle_connections:   5,
            active_connections: 3,
            waiting_requests:   0,
        }
    }

    async fn execute_raw_query(
        &self,
        _sql: &str,
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        self.raw_call_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        // Return mock aggregation data
        let mut row = std::collections::HashMap::new();
        row.insert("count".to_string(), json!(42));
        Ok(vec![row])
    }

    async fn execute_parameterized_aggregate(
        &self,
        _sql: &str,
        _params: &[serde_json::Value],
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        self.raw_call_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let mut row = std::collections::HashMap::new();
        row.insert("count".to_string(), json!(42));
        Ok(vec![row])
    }

    async fn execute_function_call(
        &self,
        _function_name: &str,
        _args: &[serde_json::Value],
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        Ok(vec![])
    }
}

impl SupportsMutations for MockAdapter {}

#[tokio::test]
async fn test_cache_miss_then_hit() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    // WHERE clause present (exercises the cache path)
    let where_clause = WhereClause::Field {
        path:     vec!["active".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(true),
    };

    // First query - cache miss
    let result1 = adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .expect("mock adapter must not fail on first query");
    assert_eq!(result1.len(), 2);
    assert_eq!(adapter.inner().call_count(), 1);

    // Second query - cache hit
    let result2 = adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .expect("mock adapter must not fail on second query");
    assert_eq!(result2.len(), 2);
    assert_eq!(adapter.inner().call_count(), 1); // Still 1 - cache hit!
}

#[tokio::test]
async fn test_different_where_clauses_produce_different_cache_entries() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    let where1 = WhereClause::Field {
        path:     vec!["id".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(1),
    };

    let where2 = WhereClause::Field {
        path:     vec!["id".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(2),
    };

    // Query 1
    adapter
        .execute_where_query("v_user", Some(&where1), None, None, None)
        .await
        .expect("mock adapter must not fail");
    assert_eq!(adapter.inner().call_count(), 1);

    // Query 2 - different WHERE - should miss cache
    adapter
        .execute_where_query("v_user", Some(&where2), None, None, None)
        .await
        .expect("mock adapter must not fail");
    assert_eq!(adapter.inner().call_count(), 2);
}

#[tokio::test]
async fn test_invalidation_clears_cache() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    // WHERE clause present (exercises the cache path)
    let where_clause = WhereClause::Field {
        path:     vec!["status".to_string()],
        operator: WhereOperator::Eq,
        value:    json!("active"),
    };

    // Query 1 - cache miss
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Query 2 - cache hit
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Invalidate
    let invalidated = adapter
        .invalidate_views(&[ViewName::from("v_user")])
        .expect("invalidate_views must succeed");
    assert_eq!(invalidated, 1);

    // Query 3 - cache miss again (was invalidated)
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 2);
}

#[tokio::test]
async fn test_different_limits_produce_different_cache_entries() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    // Query with limit 10
    adapter
        .execute_where_query("v_user", None, Some(10), None, None)
        .await
        .expect("mock adapter must not fail");
    assert_eq!(adapter.inner().call_count(), 1);

    // Query with limit 20 - should miss cache
    adapter.execute_where_query("v_user", None, Some(20), None, None).await.unwrap();
    assert_eq!(adapter.inner().call_count(), 2);
}

#[tokio::test]
async fn test_cache_disabled() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::disabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    // WHERE clause present (exercises the cache path)
    let where_clause = WhereClause::Field {
        path:     vec!["status".to_string()],
        operator: WhereOperator::Eq,
        value:    json!("active"),
    };

    // First query
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second query - should NOT hit cache (cache disabled)
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 2);
}

/// Test that ALL queries are cached — including those with no WHERE clause or small LIMIT.
///
/// The previous "simple query bypass" (Issue #40 workaround) was removed.
/// It skipped caching for `where_clause.is_none() && limit <= 1000`, which
/// prevented caching for public / unauthenticated endpoints.  The cache
/// overhead (ahash + LRU lookup) is negligible relative to a
/// database round-trip; the bypass was a premature optimisation.
#[tokio::test]
async fn test_all_queries_are_cached() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    // Query with no WHERE, no LIMIT — first call misses the cache
    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Identical query — now a cache hit, DB not called again
    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(adapter.inner().call_count(), 1); // Still 1 - cache hit!

    // Query with small LIMIT — different cache key (different limit), so a miss
    adapter
        .execute_where_query("v_user", None, Some(1000), None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 2);

    // Identical small-limit query — cache hit
    adapter
        .execute_where_query("v_user", None, Some(1000), None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 2); // Still 2 - cache hit!

    // Query with WHERE clause — cached normally
    let where_clause = WhereClause::Field {
        path:     vec!["id".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(1),
    };
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 3);

    // Identical WHERE query — cache hit
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 3); // Still 3 - cache hit!
}

#[tokio::test]
async fn test_schema_version_change_invalidates_cache() {
    let cache = Arc::new(QueryResultCache::new(CacheConfig::enabled()));
    let version_provider = Arc::new(FactTableVersionProvider::default());

    // Adapter with version 1.0.0
    let mock1 = MockAdapter::new();
    let adapter_v1 = CachedDatabaseAdapter {
        adapter:             mock1,
        cache:               Arc::clone(&cache),
        schema_version:      "1.0.0".to_string(),
        view_ttl_overrides:  HashMap::new(),
        cacheable_views:     std::collections::HashSet::new(),
        opt_in_mode:         false,
        has_rls:             false,
        fact_table_config:   FactTableCacheConfig::default(),
        version_provider:    Arc::clone(&version_provider),
        cascade_invalidator: None,
    };

    // Query with v1
    adapter_v1.execute_where_query("v_user", None, None, None, None).await.unwrap();

    // Create new adapter with version 2.0.0 (same cache!)
    let mock2 = MockAdapter::new();
    let adapter_v2 = CachedDatabaseAdapter {
        adapter:             mock2,
        cache:               Arc::clone(&cache),
        schema_version:      "2.0.0".to_string(),
        view_ttl_overrides:  HashMap::new(),
        cacheable_views:     std::collections::HashSet::new(),
        opt_in_mode:         false,
        has_rls:             false,
        fact_table_config:   FactTableCacheConfig::default(),
        version_provider:    Arc::clone(&version_provider),
        cascade_invalidator: None,
    };

    // Query with v2 - should miss cache (different schema version)
    adapter_v2.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(adapter_v2.inner().call_count(), 1); // Cache miss
}

#[tokio::test]
async fn test_forwards_database_type() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    assert_eq!(adapter.database_type(), DatabaseType::PostgreSQL);
}

#[tokio::test]
async fn test_forwards_health_check() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    adapter.health_check().await.unwrap();
}

#[tokio::test]
async fn test_forwards_pool_metrics() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    let metrics = adapter.pool_metrics();
    assert_eq!(metrics.total_connections, 10);
    assert_eq!(metrics.idle_connections, 5);
}

#[tokio::test]
async fn test_inner_and_cache_accessors() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    // Test inner()
    assert_eq!(adapter.inner().call_count(), 0);

    // Test cache()
    let cache_metrics = adapter.cache().metrics().unwrap();
    assert_eq!(cache_metrics.hits, 0);

    // Test schema_version()
    assert_eq!(adapter.schema_version(), "1.0.0");
}

// ===== Aggregation Caching Tests =====

#[test]
fn test_extract_fact_table_from_sql() {
    // Basic case
    assert_eq!(
        CachedDatabaseAdapter::<MockAdapter>::extract_fact_table_from_sql(
            "SELECT SUM(revenue) FROM tf_sales WHERE year = 2024"
        ),
        Some("tf_sales".to_string())
    );

    // With schema
    assert_eq!(
        CachedDatabaseAdapter::<MockAdapter>::extract_fact_table_from_sql(
            "SELECT COUNT(*) FROM   tf_page_views"
        ),
        Some("tf_page_views".to_string())
    );

    // Case insensitive
    assert_eq!(
        CachedDatabaseAdapter::<MockAdapter>::extract_fact_table_from_sql(
            "select sum(x) FROM TF_EVENTS"
        ),
        Some("tf_events".to_string())
    );

    // Not a fact table
    assert_eq!(
        CachedDatabaseAdapter::<MockAdapter>::extract_fact_table_from_sql(
            "SELECT * FROM users WHERE id = 1"
        ),
        None
    );

    // No FROM clause
    assert_eq!(
        CachedDatabaseAdapter::<MockAdapter>::extract_fact_table_from_sql("SELECT 1 + 1"),
        None
    );
}

#[test]
fn test_generate_aggregation_cache_key() {
    let key1 = CachedDatabaseAdapter::<MockAdapter>::generate_aggregation_cache_key(
        "SELECT SUM(x) FROM tf_sales",
        "1.0.0",
        Some("tv:42"),
    );

    let key2 = CachedDatabaseAdapter::<MockAdapter>::generate_aggregation_cache_key(
        "SELECT SUM(x) FROM tf_sales",
        "1.0.0",
        Some("tv:43"), // Different version
    );

    let key3 = CachedDatabaseAdapter::<MockAdapter>::generate_aggregation_cache_key(
        "SELECT SUM(x) FROM tf_sales",
        "2.0.0", // Different schema
        Some("tv:42"),
    );

    // Different versions/schema produce different keys
    assert_ne!(key1, key2);
    assert_ne!(key1, key3);
    assert_ne!(key2, key3);
}

#[tokio::test]
async fn test_aggregation_caching_time_based() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());

    // Configure time-based caching for tf_sales
    let mut ft_config = FactTableCacheConfig::default();
    ft_config.set_strategy("tf_sales", FactTableVersionStrategy::TimeBased { ttl_seconds: 300 });

    let adapter =
        CachedDatabaseAdapter::with_fact_table_config(mock, cache, "1.0.0".to_string(), ft_config);

    // First query - cache miss
    let _ = adapter
        .execute_aggregation_query("SELECT SUM(revenue) FROM tf_sales")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second query - cache hit (same time bucket)
    let _ = adapter
        .execute_aggregation_query("SELECT SUM(revenue) FROM tf_sales")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1); // Still 1 - cache hit!
}

#[tokio::test]
async fn test_aggregation_caching_schema_version() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());

    // Configure schema version caching for tf_historical_rates
    let mut ft_config = FactTableCacheConfig::default();
    ft_config.set_strategy("tf_historical_rates", FactTableVersionStrategy::SchemaVersion);

    let adapter =
        CachedDatabaseAdapter::with_fact_table_config(mock, cache, "1.0.0".to_string(), ft_config);

    // First query - cache miss
    let _ = adapter
        .execute_aggregation_query("SELECT AVG(rate) FROM tf_historical_rates")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second query - cache hit
    let _ = adapter
        .execute_aggregation_query("SELECT AVG(rate) FROM tf_historical_rates")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1); // Cache hit!
}

#[tokio::test]
async fn test_aggregation_caching_disabled_by_default() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::default());

    // Default config has Disabled strategy
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    // First query - no caching
    let _ = adapter
        .execute_aggregation_query("SELECT SUM(revenue) FROM tf_sales")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second query - still no caching (disabled)
    let _ = adapter
        .execute_aggregation_query("SELECT SUM(revenue) FROM tf_sales")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 2); // No cache - hits DB again
}

#[tokio::test]
async fn test_aggregation_caching_non_fact_table() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());

    // Even with caching configured, non-fact tables bypass cache
    let ft_config = FactTableCacheConfig::with_default(FactTableVersionStrategy::SchemaVersion);
    let adapter =
        CachedDatabaseAdapter::with_fact_table_config(mock, cache, "1.0.0".to_string(), ft_config);

    // Query on regular table - never cached
    let _ = adapter.execute_aggregation_query("SELECT COUNT(*) FROM users").await.unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    let _ = adapter.execute_aggregation_query("SELECT COUNT(*) FROM users").await.unwrap();
    assert_eq!(adapter.inner().call_count(), 2); // No cache
}

#[tokio::test]
async fn test_aggregation_caching_different_queries() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());

    let mut ft_config = FactTableCacheConfig::default();
    ft_config.set_strategy("tf_sales", FactTableVersionStrategy::SchemaVersion);

    let adapter =
        CachedDatabaseAdapter::with_fact_table_config(mock, cache, "1.0.0".to_string(), ft_config);

    // Query 1
    let _ = adapter
        .execute_aggregation_query("SELECT SUM(revenue) FROM tf_sales WHERE year = 2024")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Query 2 - different query, different cache key
    let _ = adapter
        .execute_aggregation_query("SELECT SUM(revenue) FROM tf_sales WHERE year = 2023")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 2); // Cache miss - different query

    // Query 1 again - cache hit
    let _ = adapter
        .execute_aggregation_query("SELECT SUM(revenue) FROM tf_sales WHERE year = 2024")
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 2); // Cache hit
}

#[tokio::test]
async fn test_fact_table_config_accessor() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());

    let mut ft_config = FactTableCacheConfig::default();
    ft_config.set_strategy("tf_sales", FactTableVersionStrategy::VersionTable);

    let adapter =
        CachedDatabaseAdapter::with_fact_table_config(mock, cache, "1.0.0".to_string(), ft_config);

    // Verify config is accessible
    assert_eq!(
        adapter.fact_table_config().get_strategy("tf_sales"),
        &FactTableVersionStrategy::VersionTable
    );
    assert_eq!(
        adapter.fact_table_config().get_strategy("tf_other"),
        &FactTableVersionStrategy::Disabled
    );
}

// ===== Cascade Invalidator Tests =====

#[tokio::test]
async fn test_cascade_invalidator_expands_transitive_views() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());

    let mut cascade = CascadeInvalidator::new();
    cascade.add_dependency("v_user_stats", "v_user").unwrap();
    cascade.add_dependency("v_dashboard", "v_user_stats").unwrap();

    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string())
        .with_cascade_invalidator(cascade);

    let where_clause = WhereClause::Field {
        path:     vec!["id".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(1),
    };

    // Populate cache with all three views
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    adapter
        .execute_where_query("v_user_stats", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    adapter
        .execute_where_query("v_dashboard", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 3);

    // Invalidate only the base view; cascade should evict dependents too
    let count = adapter.invalidate_views(&[ViewName::from("v_user")]).unwrap();
    assert_eq!(count, 3, "All three views should be invalidated via cascade");

    // All three should now be cache misses
    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    adapter
        .execute_where_query("v_user_stats", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    adapter
        .execute_where_query("v_dashboard", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        6,
        "All three should be cache misses after cascade"
    );
}

#[tokio::test]
async fn test_no_cascade_invalidator_only_direct_views() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    // No cascade invalidator — only direct view invalidation
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    let where_clause = WhereClause::Field {
        path:     vec!["id".to_string()],
        operator: WhereOperator::Eq,
        value:    json!(1),
    };

    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    adapter
        .execute_where_query("v_user_stats", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 2);

    // Only v_user is invalidated — v_user_stats remains cached
    let count = adapter.invalidate_views(&[ViewName::from("v_user")]).unwrap();
    assert_eq!(count, 1);

    adapter
        .execute_where_query("v_user", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    adapter
        .execute_where_query("v_user_stats", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        3,
        "Only v_user should be a miss; v_user_stats is still cached"
    );
}

// ── bump_fact_table_versions tests ─────────────────────────────────────

/// Adapter whose `execute_function_call` simulates `bump_tf_version` by returning
/// the incremented version (starting at 2).
struct BumpAdapter {
    bump_call_count: std::sync::atomic::AtomicU32,
}

impl BumpAdapter {
    fn new() -> Self {
        Self {
            bump_call_count: std::sync::atomic::AtomicU32::new(0),
        }
    }

    fn bump_call_count(&self) -> u32 {
        self.bump_call_count.load(std::sync::atomic::Ordering::SeqCst)
    }
}

// Reason: DatabaseAdapter is defined with #[async_trait]; all implementations must match
// its transformed method signatures to satisfy the trait contract
// async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
#[async_trait]
impl DatabaseAdapter for BumpAdapter {
    async fn execute_where_query(
        &self,
        _view: &str,
        _where_clause: Option<&WhereClause>,
        _limit: Option<u32>,
        _offset: Option<u32>,
        _order_by: Option<&[OrderByClause]>,
    ) -> Result<Vec<JsonbValue>> {
        Ok(vec![])
    }

    async fn execute_with_projection(
        &self,
        _view: &str,
        _projection: Option<&crate::schema::SqlProjectionHint>,
        _where_clause: Option<&WhereClause>,
        _limit: Option<u32>,
        _offset: Option<u32>,
        _order_by: Option<&[OrderByClause]>,
    ) -> Result<Vec<JsonbValue>> {
        Ok(vec![])
    }

    fn database_type(&self) -> DatabaseType {
        DatabaseType::PostgreSQL
    }

    async fn health_check(&self) -> Result<()> {
        Ok(())
    }

    fn pool_metrics(&self) -> PoolMetrics {
        PoolMetrics {
            total_connections:  1,
            idle_connections:   1,
            active_connections: 0,
            waiting_requests:   0,
        }
    }

    async fn execute_raw_query(
        &self,
        _sql: &str,
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        Ok(vec![])
    }

    async fn execute_parameterized_aggregate(
        &self,
        _sql: &str,
        _params: &[serde_json::Value],
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        Ok(vec![])
    }

    async fn execute_function_call(
        &self,
        function_name: &str,
        _args: &[serde_json::Value],
    ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
        if function_name == "bump_tf_version" {
            let n = self.bump_call_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            let new_version = i64::from(n) + 2; // start at 2, then 3, 4, ...
            let mut row = std::collections::HashMap::new();
            row.insert("bump_tf_version".to_string(), json!(new_version));
            Ok(vec![row])
        } else {
            Ok(vec![])
        }
    }
}

#[tokio::test]
async fn test_bump_fact_table_versions_updates_version_cache() {
    let mut ft_config = FactTableCacheConfig::default();
    ft_config.set_strategy("tf_sales", FactTableVersionStrategy::VersionTable);

    let adapter = CachedDatabaseAdapter::with_fact_table_config(
        BumpAdapter::new(),
        QueryResultCache::new(CacheConfig::enabled()),
        "1.0.0".to_string(),
        ft_config,
    );

    // Version not yet cached
    assert!(adapter.version_provider().get_cached_version("tf_sales").is_none());

    // Bump
    adapter.bump_fact_table_versions(&["tf_sales".to_string()]).await.unwrap();

    // bump_tf_version was called once
    assert_eq!(adapter.inner().bump_call_count(), 1);

    // Version is now cached (inner returned 2)
    assert_eq!(adapter.version_provider().get_cached_version("tf_sales"), Some(2));
}

#[tokio::test]
async fn test_bump_fact_table_versions_skips_non_version_table_strategy() {
    let mut ft_config = FactTableCacheConfig::default();
    ft_config.set_strategy("tf_sales", FactTableVersionStrategy::VersionTable);
    ft_config.set_strategy("tf_events", FactTableVersionStrategy::TimeBased { ttl_seconds: 300 });
    ft_config.set_strategy("tf_hist", FactTableVersionStrategy::SchemaVersion);

    let adapter = CachedDatabaseAdapter::with_fact_table_config(
        BumpAdapter::new(),
        QueryResultCache::new(CacheConfig::enabled()),
        "1.0.0".to_string(),
        ft_config,
    );

    // Mix of strategies — only tf_sales should trigger a bump_tf_version call
    adapter
        .bump_fact_table_versions(&[
            "tf_sales".to_string(),
            "tf_events".to_string(),
            "tf_hist".to_string(),
        ])
        .await
        .unwrap();

    assert_eq!(
        adapter.inner().bump_call_count(),
        1,
        "Only VersionTable strategy calls bump_tf_version"
    );
    assert!(adapter.version_provider().get_cached_version("tf_sales").is_some());
    assert!(adapter.version_provider().get_cached_version("tf_events").is_none());
    assert!(adapter.version_provider().get_cached_version("tf_hist").is_none());
}

#[tokio::test]
async fn test_bump_fact_table_versions_empty_list_is_noop() {
    let adapter = CachedDatabaseAdapter::new(
        BumpAdapter::new(),
        QueryResultCache::new(CacheConfig::enabled()),
        "1.0.0".to_string(),
    );

    adapter.bump_fact_table_versions(&[]).await.unwrap();
    assert_eq!(adapter.inner().bump_call_count(), 0);
}

// =========================================================================
// view_name_to_entity_type
// =========================================================================

#[test]
fn test_view_name_to_entity_type_single_word() {
    use crate::cache::adapter::view_name_to_entity_type;
    assert_eq!(view_name_to_entity_type("v_user"), Some("User".to_string()));
    assert_eq!(view_name_to_entity_type("v_product"), Some("Product".to_string()));
}

#[test]
fn test_view_name_to_entity_type_multi_word() {
    use crate::cache::adapter::view_name_to_entity_type;
    assert_eq!(view_name_to_entity_type("v_order_item"), Some("OrderItem".to_string()));
    assert_eq!(view_name_to_entity_type("v_user_profile"), Some("UserProfile".to_string()));
    assert_eq!(view_name_to_entity_type("v_a_b_c"), Some("ABC".to_string()));
}

#[test]
fn test_view_name_to_entity_type_arbitrary_prefix() {
    use crate::cache::adapter::view_name_to_entity_type;
    assert_eq!(view_name_to_entity_type("tv_user_event"), Some("UserEvent".to_string()));
    assert_eq!(view_name_to_entity_type("mat_order"), Some("Order".to_string()));
}

#[test]
fn test_view_name_to_entity_type_no_prefix() {
    use crate::cache::adapter::view_name_to_entity_type;
    // No underscore → not a typed view → None
    assert_eq!(view_name_to_entity_type("users"), None);
    assert_eq!(view_name_to_entity_type("orders"), None);
}

#[test]
fn test_view_name_to_entity_type_empty_after_prefix() {
    use crate::cache::adapter::view_name_to_entity_type;
    assert_eq!(view_name_to_entity_type("v_"), None);
    assert_eq!(view_name_to_entity_type("_"), None);
}

// ===== Tests: Opt-in per-query caching (#186, #187) =====

/// Views with no TTL annotation bypass key-generation entirely when
/// opt-in mode is active (i.e. `with_view_ttl_overrides` or
/// `with_ttl_overrides_from_schema` was called).  This eliminates the
/// allocation overhead that caused the 2.4× throughput regression on
/// TV-table and on-the-fly JSONB workloads.
#[tokio::test]
async fn test_non_cacheable_view_always_hits_db() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    // Only "v_expensive" opts into caching; "v_user" does not.
    let overrides = HashMap::from([("v_expensive".to_string(), 300_u64)]);
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string())
        .with_view_ttl_overrides(overrides);

    // First call to a non-cacheable view.
    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second call — should bypass the cache and hit the DB again.
    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        2,
        "non-cacheable view must not be served from cache"
    );
}

/// A view that opts in via `cache_ttl_seconds` is still cached normally
/// even when other views in the schema have no TTL annotation.
#[tokio::test]
async fn test_cacheable_view_is_still_cached() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let overrides = HashMap::from([("v_expensive".to_string(), 300_u64)]);
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string())
        .with_view_ttl_overrides(overrides);

    // First call — cache miss.
    adapter
        .execute_where_query("v_expensive", None, None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second call — cache hit; DB must NOT be called again.
    adapter
        .execute_where_query("v_expensive", None, None, None, None)
        .await
        .unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        1,
        "opt-in view must be served from cache on second call"
    );
}

/// When no TTL overrides are set AND no schema was loaded (`opt_in_mode = false`),
/// all views remain cacheable — preserving backward-compatible behaviour for
/// adapters constructed without a schema (e.g. in unit tests or direct usage).
#[tokio::test]
async fn test_all_views_cacheable_when_no_overrides_set() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    // No schema loaded → opt_in_mode = false → all views are cached (backward compat).
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string());

    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second call — cache hit.
    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        1,
        "with no schema loaded all views must be cached"
    );
}

/// Fixes #187: when a schema with NO `cache_ttl_seconds` annotations is loaded
/// (e.g. fraiseql-v on-the-fly JSONB views), opt-in mode is active but
/// `cacheable_views` is empty.  ALL views should bypass key-generation entirely
/// — restoring v2.1.2 throughput for unannotated schemas.
#[tokio::test]
async fn test_schema_without_ttl_annotations_bypasses_cache() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    // Schema loaded but no queries have cache_ttl_seconds → cacheable_views = {} but
    // opt_in_mode = true.
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string())
        .with_view_ttl_overrides(HashMap::new()); // simulates schema with no TTL annotations

    // Every call should bypass the cache and hit the DB directly.
    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        2,
        "schema with no TTL annotations must bypass cache on every request (#187)"
    );
}

/// `with_ttl_overrides_from_schema` activates opt-in mode unconditionally.
/// When the schema has no `cache_ttl_seconds` annotations, `cacheable_views`
/// is empty and every query bypasses the cache entirely — zero overhead and no
/// stale-data risk from unconfigured caching.
#[tokio::test]
async fn test_ttl_overrides_from_empty_schema_bypasses_cache() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    // Schema with no cache_ttl_seconds annotations on any query.
    let schema = CompiledSchema::default();
    let adapter = CachedDatabaseAdapter::new(mock, cache, "1.0.0".to_string())
        .with_ttl_overrides_from_schema(&schema);

    // First call — cache bypass, hits DB.
    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second call — still bypasses cache (opt-in mode, no annotations).
    adapter.execute_where_query("v_user", None, None, None, None).await.unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        2,
        "with_ttl_overrides_from_schema on unannotated schema must bypass cache entirely"
    );
}

// RLS guard — has_rls initialization and cache key isolation

#[test]
fn with_rls_sets_has_rls_field() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter_rls = CachedDatabaseAdapter::new(mock, cache, "v1".to_string()).with_rls(true);
    assert!(adapter_rls.has_rls, "with_rls(true) must set has_rls=true");

    let mock2 = MockAdapter::new();
    let cache2 = QueryResultCache::new(CacheConfig::enabled());
    let adapter_no_rls =
        CachedDatabaseAdapter::new(mock2, cache2, "v1".to_string()).with_rls(false);
    assert!(!adapter_no_rls.has_rls, "with_rls(false) must set has_rls=false");
}

#[test]
fn default_has_rls_is_false() {
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "v1".to_string());
    assert!(!adapter.has_rls, "default has_rls must be false");
}

#[tokio::test]
async fn cache_key_differs_for_different_where_clauses() {
    // Isolation in RLS deployments relies on tenants having different WHERE clauses
    // (because the RLS inject_params produce tenant-specific filters). Verify that
    // two otherwise identical queries with different WHERE clauses never share a
    // cache entry.
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "v1".to_string())
        .with_view_ttl_overrides(std::collections::HashMap::from([("v_item".to_string(), 60_u64)]));

    let where_tenant_a = WhereClause::Field {
        path:     vec!["tenant_id".to_string()],
        operator: WhereOperator::Eq,
        value:    serde_json::json!("tenant-a"),
    };
    let where_tenant_b = WhereClause::Field {
        path:     vec!["tenant_id".to_string()],
        operator: WhereOperator::Eq,
        value:    serde_json::json!("tenant-b"),
    };

    // Tenant A: 1 DB call, result cached
    adapter
        .execute_where_query("v_item", Some(&where_tenant_a), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Tenant A again: cache hit, no extra DB call
    adapter
        .execute_where_query("v_item", Some(&where_tenant_a), None, None, None)
        .await
        .unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        1,
        "second request for same tenant must be a cache hit"
    );

    // Tenant B: different WHERE clause → different cache key → DB call
    adapter
        .execute_where_query("v_item", Some(&where_tenant_b), None, None, None)
        .await
        .unwrap();
    assert_eq!(
        adapter.inner().call_count(),
        2,
        "different tenant WHERE clause must be a cache miss"
    );
}

#[tokio::test]
async fn with_rls_does_not_disable_cache() {
    // After the fix: has_rls=true must NOT bypass the cache for all requests.
    // Cache isolation is provided structurally by the WHERE clause; the has_rls
    // flag is for observability and future extension only.
    let mock = MockAdapter::new();
    let cache = QueryResultCache::new(CacheConfig::enabled());
    let adapter = CachedDatabaseAdapter::new(mock, cache, "v1".to_string())
        .with_view_ttl_overrides(std::collections::HashMap::from([("v_thing".to_string(), 60_u64)]))
        .with_rls(true);

    let where_clause = WhereClause::Field {
        path:     vec!["tenant_id".to_string()],
        operator: WhereOperator::Eq,
        value:    serde_json::json!("tenant-x"),
    };

    // First call → DB hit
    adapter
        .execute_where_query("v_thing", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1);

    // Second call with same WHERE → cache hit (has_rls=true must NOT disable cache)
    adapter
        .execute_where_query("v_thing", Some(&where_clause), None, None, None)
        .await
        .unwrap();
    assert_eq!(adapter.inner().call_count(), 1, "has_rls=true must not prevent cache hits");
}