elusion 8.2.0

Elusion is a modern DataFrame / Data Engineering / Data Analysis library that combines the familiarity of DataFrame operations (like those in PySpark, Pandas, and Polars) with the power of SQL query building. It provides flexible query construction without enforcing strict operation ordering, enabling developers to write intuitive and maintainable data transformations.
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
1189
1190
1191
1192
use crate::prelude::*;
use redis::{Client, Connection, TypedCommands, RedisResult};
use std::hash::{DefaultHasher, Hash, Hasher};
use serde::{Serialize, Deserialize};
use chrono::{DateTime, Utc};
use tokio::task;

// =================== REDIS CONNECTION (EMBEDDED) ===================

/// Redis connection configuration for caching
#[derive(Debug, Clone)]
pub struct RedisCacheConfig {
    pub host: String,
    pub port: u16,
    pub password: Option<String>,
    pub database: u8,
    pub timeout_seconds: u64,
}

impl Default for RedisCacheConfig {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".to_string(),
            port: 6379,
            password: None,
            database: 0,
            timeout_seconds: 30,
        }
    }
}

impl RedisCacheConfig {
    pub fn new(host: &str, port: u16) -> Self {
        Self {
            host: host.to_string(),
            port,
            ..Default::default()
        }
    }

    pub fn with_auth(mut self, password: &str) -> Self {
        self.password = Some(password.to_string());
        self
    }

    pub fn with_database(mut self, database: u8) -> Self {
        self.database = database;
        self
    }

    fn to_connection_string(&self) -> String {
        match &self.password {
            Some(password) => format!(
                "redis://:{}@{}:{}/{}",
                password, self.host, self.port, self.database
            ),
            None => format!("redis://{}:{}/{}", self.host, self.port, self.database),
        }
    }
}

/// Redis connection wrapper for caching operations
#[derive(Debug, Clone)]
pub struct RedisCacheConnection {
    client: Client,
}

impl RedisCacheConnection {
    /// Create a new Redis cache connection
    pub async fn new(config: RedisCacheConfig) -> crate::ElusionResult<Self> {
        let connection_string = config.to_connection_string();
        
        // Test connection in blocking context
        let conn_str_clone = connection_string.clone();
        let client = task::spawn_blocking(move || {
            let client = Client::open(conn_str_clone)?;
            
            // Test the connection
            let mut conn = client.get_connection()?;
            let _: String = conn.ping()?;
            
            Ok::<Client, redis::RedisError>(client)
        })
        .await
        .map_err(|e| crate::ElusionError::Custom(format!("Failed to create Redis cache task: {}", e)))?
        .map_err(|e| crate::ElusionError::Custom(format!("Redis cache connection failed: {}", e)))?;

        println!("โœ… Redis cache connected at {}:{}", config.host, config.port);

        Ok(Self { client })
    }

    /// Quick local connection
    pub async fn local() -> crate::ElusionResult<Self> {
        Self::new(RedisCacheConfig::default()).await
    }

    /// Execute Redis commands with automatic type handling
    async fn execute_typed<T, F>(&self, operation: F) -> crate::ElusionResult<T>
    where
        F: FnOnce(&mut Connection) -> RedisResult<T> + Send + 'static,
        T: Send + 'static,
    {
        let client = self.client.clone();
        
        task::spawn_blocking(move || {
            let mut conn = client.get_connection()?;
            operation(&mut conn)
        })
        .await
        .map_err(|e| crate::ElusionError::Custom(format!("Redis cache task error: {}", e)))?
        .map_err(|e| crate::ElusionError::Custom(format!("Redis cache operation error: {}", e)))
    }

    /// Set a key-value pair with automatic serialization
    async fn set<V>(&self, key: &str, value: V) -> crate::ElusionResult<()>
    where
        V: serde::Serialize + Send + 'static,
    {
        let key = key.to_string();
        let value_json = serde_json::to_string(&value)
            .map_err(|e| crate::ElusionError::Custom(format!("Failed to serialize cache value: {}", e)))?;

        self.execute_typed(move |conn| {
            conn.set(&key, value_json)
        }).await
    }

    /// Set a key-value pair with TTL
    async fn set_with_ttl<V>(&self, key: &str, value: V, ttl_seconds: u64) -> crate::ElusionResult<()>
    where
        V: serde::Serialize + Send + 'static,
    {
        let key = key.to_string();
        let value_json = serde_json::to_string(&value)
            .map_err(|e| crate::ElusionError::Custom(format!("Failed to serialize cache value: {}", e)))?;

        self.execute_typed(move |conn| {
            conn.set_ex(&key, value_json, ttl_seconds)
        }).await
    }

    /// Get a value with automatic deserialization
    async fn get<T>(&self, key: &str) -> crate::ElusionResult<Option<T>>
    where
        T: for<'de> serde::Deserialize<'de> + Send + 'static,
    {
        let key = key.to_string();
        
        let value_str: Option<String> = self.execute_typed(move |conn| {
            conn.get(&key)
        }).await?;

        match value_str {
            Some(json_str) => {
                let value = serde_json::from_str(&json_str)
                    .map_err(|e| crate::ElusionError::Custom(format!("Failed to deserialize cache value: {}", e)))?;
                Ok(Some(value))
            }
            None => Ok(None),
        }
    }

    /// Delete keys
    async fn delete(&self, keys: &[&str]) -> crate::ElusionResult<u64> {
        let keys: Vec<String> = keys.iter().map(|k| k.to_string()).collect();
        
        self.execute_typed(move |conn| {
            let result: usize = conn.del(&keys)?;
            Ok(result as u64)
        }).await
    }

    /// Get keys matching pattern
    async fn keys(&self, pattern: &str) -> crate::ElusionResult<Vec<String>> {
        let pattern = pattern.to_string();
        
        self.execute_typed(move |conn| {
            conn.keys(&pattern)
        }).await
    }

    /// Get Redis info
    async fn info(&self) -> crate::ElusionResult<String> {
        self.execute_typed(move |conn| {
            redis::cmd("INFO").query(conn)
        }).await
    }
}

// =================== CACHE IMPLEMENTATION ===================

/// Redis cache statistics
#[derive(Debug, Serialize, Deserialize)]
pub struct RedisCacheStats {
    pub total_keys: u64,
    pub cache_hits: u64,
    pub cache_misses: u64,
    pub hit_rate: f64,
    pub total_memory_used: String,
    pub avg_query_time_ms: f64,
}

/// Cache entry metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
struct RedisCacheEntry {
    query_sql: String,
    created_at: DateTime<Utc>,
    expires_at: Option<DateTime<Utc>>,
    row_count: usize,
    schema_fingerprint: String,
    compressed: bool,
}

/// Generate cache key for a query
fn generate_cache_key(query: &str) -> String {
    let mut hasher = DefaultHasher::new();
    query.hash(&mut hasher);
    let query_hash = hasher.finish();
    format!("elusion:query_cache:{:x}", query_hash)
}

/// Generate schema fingerprint
fn generate_schema_fingerprint(schema: &datafusion::arrow::datatypes::SchemaRef) -> String {
    let mut hasher = DefaultHasher::new();
    for field in schema.fields() {
        field.name().hash(&mut hasher);
        format!("{:?}", field.data_type()).hash(&mut hasher);
    }
    format!("{:x}", hasher.finish())
}

/// Execute query with Redis caching
pub async fn elusion_with_redis_cache_impl(
    df: &crate::CustomDataFrame,
    redis_conn: &RedisCacheConnection,
    alias: &str,
    ttl_seconds: Option<u64>,
) -> crate::ElusionResult<crate::CustomDataFrame> {
    let sql = df.construct_sql();
    let cache_key = generate_cache_key(&sql);
    let meta_key = format!("{}_meta", cache_key);
    let data_key = format!("{}_data", cache_key);
    
    println!("๐Ÿ” Checking Redis cache for query...");
    
    // Try to get cached result
    match get_cached_result_from_redis(redis_conn, &cache_key, &meta_key, &data_key).await {
        Ok(Some(cached_batches)) => {
            println!("โœ… Using Redis cached result for query");
            
            // Create DataFrame from cached result
            let ctx = SessionContext::new();
            let schema = cached_batches[0].schema();
            
            let mem_table = MemTable::try_new(schema.clone(), vec![cached_batches])
                .map_err(|e| crate::ElusionError::Custom(format!("Failed to create memory table from Redis cache: {}", e)))?;
            
            ctx.register_table(alias, Arc::new(mem_table))
                .map_err(|e| crate::ElusionError::Custom(format!("Failed to register table from Redis cache: {}", e)))?;
            
            let df_result = ctx.table(alias).await
                .map_err(|e| crate::ElusionError::Custom(format!("Failed to create DataFrame from Redis cache: {}", e)))?;
            
            // Update cache hit statistics - Fixed: explicitly specify i64 return type
            let _ = redis_conn.execute_typed(move |conn| -> redis::RedisResult<i64> {
                redis::cmd("INCR").arg("elusion:cache_stats:hits").query(conn)
            }).await;
            
            return Ok(crate::CustomDataFrame {
                df: df_result,
                table_alias: alias.to_string(),
                from_table: alias.to_string(),
                selected_columns: Vec::new(),
                alias_map: Vec::new(),
                aggregations: Vec::new(),
                group_by_columns: Vec::new(),
                where_conditions: Vec::new(),
                having_conditions: Vec::new(),
                order_by_columns: Vec::new(),
                limit_count: None,
                joins: Vec::new(),
                window_functions: Vec::new(),
                ctes: Vec::new(),
                subquery_source: None,
                set_operations: Vec::new(),
                query: sql,
                aggregated_df: None,
                union_tables: None,
                original_expressions: df.original_expressions.clone(),
                needs_normalization: false,
                raw_selected_columns: Vec::new(),
                raw_group_by_columns: Vec::new(),
                raw_where_conditions: Vec::new(),
                raw_having_conditions: Vec::new(),
                raw_join_conditions: Vec::new(),
                raw_aggregations: Vec::new(),
                uses_group_by_all: false,
            });
        }
        Ok(None) => {
            println!("๐Ÿ’พ No cached result found, executing query...");
        }
        Err(e) => {
            println!("โš ๏ธ Redis cache read error: {}, executing query...", e);
        }
    }
    
    let start_time = std::time::Instant::now();
    let result = df.elusion(alias).await?;
    let query_time = start_time.elapsed();
    
    let batches = result.df.clone().collect().await
        .map_err(|e| crate::ElusionError::Custom(format!("Failed to collect batches for Redis caching: {}", e)))?;
    
    if !batches.is_empty() {
        match cache_result_in_redis(redis_conn, &cache_key, &meta_key, &data_key, &sql, &batches, ttl_seconds).await {
            Ok(_) => {
                let row_count: usize = batches.iter().map(|b| b.num_rows()).sum();
                println!("โœ… Cached {} rows in Redis (query took: {:?})", row_count, query_time);
            }
            Err(e) => {
                println!("โš ๏ธ Failed to cache result in Redis: {}", e);
            }
        }
    }
    
    let _ = redis_conn.execute_typed(move |conn| -> redis::RedisResult<i64> {
        redis::cmd("INCR").arg("elusion:cache_stats:misses").query(conn)
    }).await;
    
    let query_time_ms = query_time.as_millis() as i64;
    let _ = redis_conn.execute_typed(move |conn| -> redis::RedisResult<i64> {
        redis::cmd("LPUSH").arg("elusion:cache_stats:query_times").arg(query_time_ms).query(conn)
    }).await;
    
    let _ = redis_conn.execute_typed(move |conn| -> redis::RedisResult<()> {
        redis::cmd("LTRIM").arg("elusion:cache_stats:query_times").arg(0).arg(99).query(conn)
    }).await;
    
    Ok(result)
}

/// Get cached result from Redis
async fn get_cached_result_from_redis(
    redis_conn: &RedisCacheConnection,
    _cache_key: &str,
    meta_key: &str,
    data_key: &str,
) -> crate::ElusionResult<Option<Vec<RecordBatch>>> {
    // Get metadata first
    let metadata: Option<RedisCacheEntry> = redis_conn.get(meta_key).await?;
    let meta = match metadata {
        Some(m) => m,
        None => return Ok(None),
    };
    
    // Check if expired
    if let Some(expires_at) = meta.expires_at {
        if Utc::now() > expires_at {
            // Expired, clean up
            let _ = redis_conn.delete(&[meta_key, data_key]).await;
            return Ok(None);
        }
    }
    
    // Get the actual data
    let data_buffer: Option<Vec<u8>> = redis_conn.get(data_key).await?;
    let buffer = match data_buffer {
        Some(buf) => buf,
        None => return Ok(None),
    };
    
    // Deserialize Arrow IPC data
    let cursor = std::io::Cursor::new(buffer);
    let mut reader = datafusion::arrow::ipc::reader::StreamReader::try_new(cursor, None)
        .map_err(|e| crate::ElusionError::Custom(format!("Failed to read cached Arrow data: {}", e)))?;
    
    let mut batches = Vec::new();
    while let Some(batch_result) = reader.next() {
        let batch = batch_result
            .map_err(|e| crate::ElusionError::Custom(format!("Failed to deserialize cached batch: {}", e)))?;
        batches.push(batch);
    }
    
    Ok(Some(batches))
}

/// Cache result in Redis
async fn cache_result_in_redis(
    redis_conn: &RedisCacheConnection,
    _cache_key: &str,
    meta_key: &str,
    data_key: &str,
    query_sql: &str,
    batches: &[RecordBatch],
    ttl_seconds: Option<u64>,
) -> crate::ElusionResult<()> {
    if batches.is_empty() {
        return Ok(());
    }
    
    let schema = batches[0].schema();
    let schema_fingerprint = generate_schema_fingerprint(&schema);
    let row_count = batches.iter().map(|b| b.num_rows()).sum();
    
    // Serialize to Arrow IPC format
    let mut buffer = Vec::new();
    {
        let mut writer = datafusion::arrow::ipc::writer::StreamWriter::try_new(&mut buffer, &schema)
            .map_err(|e| crate::ElusionError::Custom(format!("Failed to create Arrow writer: {}", e)))?;
        
        for batch in batches {
            writer.write(batch)
                .map_err(|e| crate::ElusionError::Custom(format!("Failed to write batch to cache: {}", e)))?;
        }
        
        writer.finish()
            .map_err(|e| crate::ElusionError::Custom(format!("Failed to finish Arrow writer: {}", e)))?;
    }
    
    // Create metadata
    let metadata = RedisCacheEntry {
        query_sql: query_sql.to_string(),
        created_at: Utc::now(),
        expires_at: ttl_seconds.map(|ttl| Utc::now() + chrono::Duration::seconds(ttl as i64)),
        row_count,
        schema_fingerprint,
        compressed: false, // add compression later
    };

    let meta_key = meta_key.to_string();
    let data_key = data_key.to_string();
    
    // Store both metadata and data
    if let Some(ttl) = ttl_seconds {
        redis_conn.set_with_ttl(&meta_key, metadata.clone(), ttl).await?;
        redis_conn.set_with_ttl(&data_key, buffer.clone(), ttl).await?;
    } else {
        redis_conn.set(&meta_key, metadata).await?;
        redis_conn.set(&data_key, buffer).await?;
    }
    
    Ok(())
}

/// Clear Redis cache
pub async fn clear_redis_cache_impl(
    redis_conn: &RedisCacheConnection,
    pattern: Option<&str>,
) -> crate::ElusionResult<()> {
    let search_pattern = pattern.unwrap_or("elusion:query_cache:*");
    
    println!("๐Ÿ—‘๏ธ Clearing Redis cache with pattern: {}", search_pattern);
    
    let keys = redis_conn.keys(search_pattern).await?;
    
    if keys.is_empty() {
        println!("โ„น๏ธ No cache keys found to clear");
        return Ok(());
    }
    
    // Also get metadata keys
    let meta_pattern = format!("{}_meta", search_pattern);
    let data_pattern = format!("{}_data", search_pattern);
    
    let mut all_keys = keys;
    all_keys.extend(redis_conn.keys(&meta_pattern).await?);
    all_keys.extend(redis_conn.keys(&data_pattern).await?);
    
    if !all_keys.is_empty() {
        let key_refs: Vec<&str> = all_keys.iter().map(|s| s.as_str()).collect();
        let deleted_count = redis_conn.delete(&key_refs).await?;
        println!("โœ… Cleared {} Redis cache keys", deleted_count);
    }
    
    // Clear statistics
    let _ = redis_conn.delete(&[
        "elusion:cache_stats:hits",
        "elusion:cache_stats:misses", 
        "elusion:cache_stats:query_times"
    ]).await;
    
    Ok(())
}

/// Get Redis cache statistics
pub async fn get_redis_cache_stats_impl(
    redis_conn: &RedisCacheConnection,
) -> crate::ElusionResult<RedisCacheStats> {
    // Get cache hit/miss stats
    let hits: u64 = redis_conn.get("elusion:cache_stats:hits").await?.unwrap_or(0);
    let misses: u64 = redis_conn.get("elusion:cache_stats:misses").await?.unwrap_or(0);
    
    let total_requests = hits + misses;
    let hit_rate = if total_requests > 0 {
        (hits as f64 / total_requests as f64) * 100.0
    } else {
        0.0
    };
    
    // Count total cache keys
    let cache_keys = redis_conn.keys("elusion:query_cache:*").await?;
    let total_keys = cache_keys.len() as u64;
    
    // Get memory usage info
    let info = redis_conn.info().await?;
    let memory_line = info.lines()
        .find(|line| line.starts_with("used_memory_human:"))
        .unwrap_or("used_memory_human:unknown");
    let memory_used = memory_line.split(':').nth(1).unwrap_or("unknown").to_string();
    
    // Calculate average query time
    let query_times: Vec<String> = redis_conn.execute_typed(move |conn| -> redis::RedisResult<Vec<String>> {
        conn.lrange("elusion:cache_stats:query_times", 0, -1)
    }).await?;
    
    let parsed_times: Vec<i64> = query_times
        .into_iter()
        .filter_map(|s| s.parse().ok())
        .collect();
    
    let avg_query_time_ms = if !parsed_times.is_empty() {
        parsed_times.iter().sum::<i64>() as f64 / parsed_times.len() as f64
    } else {
        0.0
    };
    
    Ok(RedisCacheStats {
        total_keys,
        cache_hits: hits,
        cache_misses: misses,
        hit_rate,
        total_memory_used: memory_used,
        avg_query_time_ms,
    })
}

/// Invalidate Redis cache by table patterns
pub async fn invalidate_redis_cache_impl(
    redis_conn: &RedisCacheConnection,
    table_names: &[&str],
) -> crate::ElusionResult<()> {
    if table_names.is_empty() {
        return Ok(());
    }
    
    println!("๐Ÿ”„ Invalidating Redis cache for tables: {:?}", table_names);
    
    // clear all cache when any table changes
    clear_redis_cache_impl(redis_conn, Some("elusion:query_cache:*")).await?;
    
    println!("โœ… Redis cache invalidated");
    Ok(())
}

/// Create a Redis cache connection with default settings
pub async fn create_redis_cache_connection() -> crate::ElusionResult<RedisCacheConnection> {
    RedisCacheConnection::local().await
}

/// Create a Redis cache connection with custom settings
pub async fn create_redis_cache_connection_with_config(
    host: &str,
    port: u16,
    password: Option<&str>,
    database: Option<u8>,
) -> crate::ElusionResult<RedisCacheConnection> {
    let mut config = RedisCacheConfig::new(host, port);
    
    if let Some(pass) = password {
        config = config.with_auth(pass);
    }
    
    if let Some(db) = database {
        config = config.with_database(db);
    }
    
    RedisCacheConnection::new(config).await
}


// #[cfg(test)]
// mod tests {
//     use super::*;
//     use std::time::Duration;
//     use tokio::time::timeout;

//     async fn create_test_connection() -> crate::ElusionResult<RedisCacheConnection> {

//         match timeout(Duration::from_secs(5), create_redis_cache_connection()).await {
//             Ok(result) => result,
//             Err(_) => Err(crate::ElusionError::Custom(
//                 "Redis connection timeout - is Redis running on localhost:6379?".to_string()
//             )),
//         }
//     }

//     async fn is_redis_available() -> bool {
//         create_test_connection().await.is_ok()
//     }

//     #[tokio::test]
//     async fn test_redis_connection() {
//         println!("๐Ÿงช Testing Redis connection...");
        
//         match create_test_connection().await {
//             Ok(_) => {
//                 println!("โœ… Redis connection successful!");
//             }
//             Err(e) => {
//                 println!("โŒ Redis connection failed: {}", e);
//                 println!("๐Ÿ’ก Make sure Redis is running:");
//                 println!("   Windows: redis-server");
//                 println!("   Docker: docker run --name redis-cache -p 6379:6379 -d redis:latest");
//                 panic!("Redis not available for testing");
//             }
//         }
//     }

//     #[tokio::test]
//     async fn test_redis_config() {
//         println!("๐Ÿงช Testing Redis configuration...");
        
//         let config = RedisCacheConfig::default();
//         assert_eq!(config.host, "127.0.0.1");
//         assert_eq!(config.port, 6379);
//         assert_eq!(config.database, 0);
//         assert!(config.password.is_none());
        
//         let config = RedisCacheConfig::new("localhost", 6380)
//             .with_auth("mypassword")
//             .with_database(1);
        
//         assert_eq!(config.host, "localhost");
//         assert_eq!(config.port, 6380);
//         assert_eq!(config.database, 1);
//         assert_eq!(config.password, Some("mypassword".to_string()));
        
//         let conn_str = config.to_connection_string();
//         assert!(conn_str.contains("mypassword"));
//         assert!(conn_str.contains("localhost"));
//         assert!(conn_str.contains("6380"));
//         assert!(conn_str.contains("/1"));
        
//         println!("โœ… Redis configuration tests passed!");
//     }

//     #[tokio::test]
//     async fn test_redis_ttl_operations() {
//         if !is_redis_available().await {
//             println!("โญ๏ธ Skipping TTL test - Redis not available");
//             return;
//         }

//         println!("๐Ÿงช Testing Redis TTL operations...");
        
//         let redis_conn = create_test_connection().await.unwrap();
        
//         let ttl_key = "elusion:test:ttl";
//         let ttl_value = "This will expire";
        
//         redis_conn.set_with_ttl(ttl_key, ttl_value, 2).await.unwrap();
        
//         let value: Option<String> = redis_conn.get(ttl_key).await.unwrap();
//         assert_eq!(value, Some(ttl_value.to_string()));
        
//         tokio::time::sleep(Duration::from_secs(3)).await;
        
//         let value: Option<String> = redis_conn.get(ttl_key).await.unwrap();
//         assert_eq!(value, None);
        
//         println!("โœ… TTL operations tests passed!");
//     }

//     #[tokio::test]
//     async fn test_redis_delete_operations() {
//         if !is_redis_available().await {
//             println!("โญ๏ธ Skipping delete test - Redis not available");
//             return;
//         }

//         println!("๐Ÿงช Testing Redis delete operations...");
        
//         let redis_conn = create_test_connection().await.unwrap();
        
//         let keys = ["elusion:test:del1", "elusion:test:del2", "elusion:test:del3"];
//         for key in &keys {
//             redis_conn.set(key, "delete me").await.unwrap();
//         }
        
//         for key in &keys {
//             let value: Option<String> = redis_conn.get(key).await.unwrap();
//             assert_eq!(value, Some("delete me".to_string()));
//         }
        
//         let deleted_count = redis_conn.delete(&keys).await.unwrap();
//         assert_eq!(deleted_count, 3);
        
//         for key in &keys {
//             let value: Option<String> = redis_conn.get(key).await.unwrap();
//             assert_eq!(value, None);
//         }
        
//         println!("โœ… Delete operations tests passed!");
//     }

//     #[tokio::test]
//     async fn test_redis_key_patterns() {
//         if !is_redis_available().await {
//             println!("โญ๏ธ Skipping key patterns test - Redis not available");
//             return;
//         }

//         println!("๐Ÿงช Testing Redis key patterns...");
        
//         let redis_conn = create_test_connection().await.unwrap();
        
//         let cache_keys = [
//             "elusion:query_cache:abc123",
//             "elusion:query_cache:def456", 
//             "elusion:query_cache:ghi789"
//         ];
//         let other_keys = [
//             "elusion:stats:hits",
//             "other:namespace:key1",
//             "completely_different"
//         ];
        
//         for key in cache_keys.iter().chain(other_keys.iter()) {
//             redis_conn.set(key, "test_value").await.unwrap();
//         }
        
//         let found_cache_keys = redis_conn.keys("elusion:query_cache:*").await.unwrap();
//         assert_eq!(found_cache_keys.len(), 3);
        
//         let found_elusion_keys = redis_conn.keys("elusion:*").await.unwrap();
//         assert!(found_elusion_keys.len() >= 4); 
        
//         let found_all_keys = redis_conn.keys("*").await.unwrap();
//         assert!(found_all_keys.len() >= 6); 
        
//         let all_test_keys: Vec<&str> = cache_keys.iter().chain(other_keys.iter()).cloned().collect();
//         redis_conn.delete(&all_test_keys).await.unwrap();
        
//         println!("โœ… Key patterns tests passed!");
//     }

//     #[tokio::test]
//     async fn test_cache_key_generation() {
//         println!("๐Ÿงช Testing cache key generation...");
        
//         let query1 = "SELECT * FROM users WHERE id = 1";
//         let query2 = "SELECT * FROM users WHERE id = 1"; 
//         let query3 = "SELECT * FROM users WHERE id = 2"; 
        
//         let key1 = generate_cache_key(query1);
//         let key2 = generate_cache_key(query2);
//         let key3 = generate_cache_key(query3);
        
//         assert_eq!(key1, key2, "Same queries should generate same cache keys");
//         assert_ne!(key1, key3, "Different queries should generate different cache keys");
        
//         assert!(key1.starts_with("elusion:query_cache:"));
//         assert!(key3.starts_with("elusion:query_cache:"));
        
//         println!("โœ… Cache key generation tests passed!");
//     }

//     #[tokio::test]
//     async fn test_cache_statistics() {
//         if !is_redis_available().await {
//             println!("โญ๏ธ Skipping cache statistics test - Redis not available");
//             return;
//         }

//         println!("๐Ÿงช Testing cache statistics...");
        
//         let redis_conn = create_test_connection().await.unwrap();
        
//         clear_redis_cache_impl(&redis_conn, None).await.unwrap();
        
//         let initial_stats = get_redis_cache_stats_impl(&redis_conn).await.unwrap();
//         assert_eq!(initial_stats.cache_hits, 0);
//         assert_eq!(initial_stats.cache_misses, 0);
//         assert_eq!(initial_stats.total_keys, 0);

//         redis_conn.set("elusion:query_cache:test1", "data1").await.unwrap();
//         redis_conn.set("elusion:query_cache:test2", "data2").await.unwrap();
        
//         let stats_with_keys = get_redis_cache_stats_impl(&redis_conn).await.unwrap();
//         assert_eq!(stats_with_keys.total_keys, 2);
        

//         assert_eq!(stats_with_keys.hit_rate, 0.0); 
        
//         clear_redis_cache_impl(&redis_conn, None).await.unwrap();
        
//         println!("โœ… Cache statistics tests passed!");
//     }

//     #[tokio::test]
//     async fn test_cache_clear_operations() {
//         if !is_redis_available().await {
//             println!("โญ๏ธ Skipping cache clear test - Redis not available");
//             return;
//         }

//         println!("๐Ÿงช Testing cache clear operations...");
        
//         let redis_conn = create_test_connection().await.unwrap();
//              // Set up test data
//         let cache_keys = [
//             "elusion:query_cache:clear1",
//             "elusion:query_cache:clear2",
//             "elusion:query_cache:clear1_meta",
//             "elusion:query_cache:clear2_data"
//         ];
//         let other_keys = ["elusion:other:key", "completely:different:key"];
        
//         for key in cache_keys.iter().chain(other_keys.iter()) {
//             redis_conn.set(key, "test_data").await.unwrap();
//         }
        
//         clear_redis_cache_impl(&redis_conn, Some("elusion:query_cache:*")).await.unwrap();
        
//         for key in &cache_keys {
//             let value: Option<String> = redis_conn.get(key).await.unwrap();
//             assert_eq!(value, None, "Cache key {} should be deleted", key);
//         }
        

//         for key in &other_keys {
//             let value: Option<String> = redis_conn.get(key).await.unwrap();
//             assert_eq!(value, Some("test_data".to_string()), "Non-cache key {} should still exist", key);
//         }
        
//         redis_conn.delete(&other_keys).await.unwrap();
        
//         println!("โœ… Cache clear operations tests passed!");
//     }

//     #[tokio::test]
//     async fn test_redis_info() {
//         if !is_redis_available().await {
//             println!("โญ๏ธ Skipping Redis info test - Redis not available");
//             return;
//         }

//         println!("๐Ÿงช Testing Redis info retrieval...");
        
//         let redis_conn = create_test_connection().await.unwrap();
        
//         let info = redis_conn.info().await.unwrap();
        
//         assert!(!info.is_empty(), "Redis info should not be empty");
//         assert!(info.contains("redis_version"), "Info should contain Redis version");
//         assert!(info.contains("used_memory"), "Info should contain memory usage");
        
//         println!("๐Ÿ“‹ Redis info retrieved ({} chars)", info.len());
//         println!("โœ… Redis info tests passed!");
//     }

//     #[tokio::test]
//     async fn test_performance_benchmark() {
//         if !is_redis_available().await {
//             println!("โญ๏ธ Skipping performance test - Redis not available");
//             return;
//         }

//         println!("๐Ÿงช Running performance benchmark...");
        
//         let redis_conn = create_test_connection().await.unwrap();
        
//         let iterations = 50;
//         let test_data = "Performance test data - this is a reasonably sized string for testing";
        
//         let start_time = std::time::Instant::now();
        
//         for i in 0..iterations {
//             let key = format!("elusion:perf:test:{}", i);
//             redis_conn.set(&key, test_data).await.unwrap();
//         }
        
//         let set_duration = start_time.elapsed();
        
//         let start_time = std::time::Instant::now();
        
//         for i in 0..iterations {
//             let key = format!("elusion:perf:test:{}", i);
//             let _: Option<String> = redis_conn.get(&key).await.unwrap();
//         }
        
//         let get_duration = start_time.elapsed();
        
//         let keys: Vec<String> = (0..iterations)
//             .map(|i| format!("elusion:perf:test:{}", i))
//             .collect();
//         let key_refs: Vec<&str> = keys.iter().map(|k| k.as_str()).collect();
//         redis_conn.delete(&key_refs).await.unwrap();
        
//         let avg_set_time = set_duration.as_micros() as f64 / iterations as f64;
//         let avg_get_time = get_duration.as_micros() as f64 / iterations as f64;
        
//         println!("๐Ÿ“Š Performance results ({} operations):", iterations);
//         println!("   Average SET time: {:.2} ฮผs", avg_set_time);
//         println!("   Average GET time: {:.2} ฮผs", avg_get_time);
//         println!("   Total SET time: {:?}", set_duration);
//         println!("   Total GET time: {:?}", get_duration);
        
//         assert!(avg_set_time < 10000.0, "SET operations should be under 10ms on average");
//         assert!(avg_get_time < 10000.0, "GET operations should be under 10ms on average");
        
//         println!("โœ… Performance benchmark passed!");
//     }


//     #[tokio::test]
//     async fn test_error_handling() {
//         println!("๐Ÿงช Testing error handling...");
        

//         let invalid_config = RedisCacheConfig::new("invalid_host", 9999);
        
//         match timeout(Duration::from_secs(2), RedisCacheConnection::new(invalid_config)).await {
//             Ok(Err(_)) => {
//                 println!("โœ… Properly handled invalid Redis connection");
//             }
//             Ok(Ok(_)) => {
//                 panic!("Should not have connected to invalid Redis instance");
//             }
//             Err(_) => {
//                 println!("โœ… Connection attempt timed out as expected");
//             }
//         }
        
//         println!("โœ… Error handling tests passed!");
//     }

//     #[allow(dead_code)]
//     pub async fn run_all_redis_tests() -> Result<(), Box<dyn std::error::Error>> {
//         println!("๐Ÿš€ Running comprehensive Redis cache tests...\n");
        
//         if !is_redis_available().await {
//             println!("โŒ Redis is not available. Please start Redis and try again.");
//             println!("๐Ÿ’ก Start Redis with one of these methods:");
//             println!("   - Windows: redis-server");
//             println!("   - Docker: docker run --name redis-cache -p 6379:6379 -d redis:latest");
//             return Err("Redis not available".into());
//         }
        
//         println!("โœ… Redis is available, running tests...\n");
        

//         Ok(())
//     }
    
// }


// #[cfg(test)]
// mod integration_tests {

//     use std::time::Instant;

//     async fn create_test_dataframe() -> crate::ElusionResult<crate::CustomDataFrame> {
//         use datafusion::prelude::*;
//         use datafusion::arrow::array::*;
//         use datafusion::arrow::datatypes::*;
//         use datafusion::arrow::record_batch::RecordBatch;
//         use datafusion::datasource::MemTable;
//         use std::sync::Arc;

//         let schema = Arc::new(Schema::new(vec![
//             Field::new("id", DataType::Int32, false),
//             Field::new("name", DataType::Utf8, false),
//             Field::new("score", DataType::Float64, false),
//         ]));

//         let id_array = Int32Array::from(vec![1, 2, 3, 4, 5]);
//         let name_array = StringArray::from(vec!["Alice", "Bob", "Charlie", "Diana", "Eve"]);
//         let score_array = Float64Array::from(vec![95.5, 87.2, 92.1, 88.8, 94.3]);

//         let batch = RecordBatch::try_new(
//             schema.clone(),
//             vec![
//                 Arc::new(id_array),
//                 Arc::new(name_array),
//                 Arc::new(score_array),
//             ],
//         ).map_err(|e| crate::ElusionError::Custom(format!("Arrow error: {}", e)))?;

//         let ctx = SessionContext::new();
//         let table = MemTable::try_new(schema, vec![vec![batch]])
//             .map_err(|e| crate::ElusionError::Custom(format!("DataFusion error: {}", e)))?;
//         ctx.register_table("test_users", Arc::new(table))
//             .map_err(|e| crate::ElusionError::Custom(format!("DataFusion error: {}", e)))?;

//         let df = ctx.table("test_users").await
//             .map_err(|e| crate::ElusionError::Custom(format!("DataFusion error: {}", e)))?;
        
//         Ok(crate::CustomDataFrame {
//             df,
//             table_alias: "test_users".to_string(),
//             from_table: "test_users".to_string(),
//             selected_columns: vec!["id".to_string(), "name".to_string(), "score".to_string()],
//             alias_map: Vec::new(),
//             aggregations: Vec::new(),
//             group_by_columns: Vec::new(),
//             where_conditions: Vec::new(),
//             having_conditions: Vec::new(),
//             order_by_columns: Vec::new(),
//             limit_count: None,
//             joins: Vec::new(),
//             window_functions: Vec::new(),
//             ctes: Vec::new(),
//             subquery_source: None,
//             set_operations: Vec::new(),
//             query: "SELECT id, name, score FROM test_users".to_string(),
//             aggregated_df: None,
//             union_tables: None,
//             original_expressions: Vec::new(),
//             needs_normalization: false,
//             raw_selected_columns: Vec::new(),
//             raw_group_by_columns: Vec::new(),
//             raw_where_conditions: Vec::new(),
//             raw_having_conditions: Vec::new(),
//             raw_join_conditions: Vec::new(),
//             raw_aggregations: Vec::new(),
//             uses_group_by_all: false,
//         })
//     }

//     #[tokio::test]
//     async fn test_dataframe_redis_cache_integration() {

//         let redis_conn = match crate::features::redis::create_redis_cache_connection().await {
//             Ok(conn) => conn,
//             Err(e) => {
//                 println!("โญ๏ธ Skipping integration test - Redis not available: {}", e);
//                 return;
//             }
//         };

//         crate::features::redis::clear_redis_cache_impl(&redis_conn, None).await.unwrap();

//         let df = create_test_dataframe().await.unwrap();

//         let start_time = Instant::now();
        
//         let result1 = crate::features::redis::elusion_with_redis_cache_impl(
//             &df,
//             &redis_conn,
//             "cached_test_users",
//             Some(300),
//         ).await.unwrap();
        
//         let first_duration = start_time.elapsed();

//         let batches1 = result1.df.clone().collect().await.unwrap();
//         let row_count1 = batches1.iter().map(|b| b.num_rows()).sum::<usize>();

//         let start_time = Instant::now();
        
//         let result2 = crate::features::redis::elusion_with_redis_cache_impl(
//             &df,
//             &redis_conn,
//             "cached_test_users_2", 
//             Some(300),
//         ).await.unwrap();
        
//         let second_duration = start_time.elapsed();
//         println!("Second execution completed in: {:?}", second_duration);

//         let batches2 = result2.df.clone().collect().await.unwrap();
//         let row_count2 = batches2.iter().map(|b| b.num_rows()).sum::<usize>();
//         println!("๐Ÿ“‹ Second execution returned {} rows", row_count2);

//         assert_eq!(row_count1, row_count2, "Both executions should return same number of rows");
//         assert_eq!(row_count1, 5, "Should have 5 test rows");


//         if second_duration < first_duration {
//             let speedup = first_duration.as_micros() as f64 / second_duration.as_micros() as f64;
//             println!("Cache speedup: {:.2}x faster!", speedup);
//         } else {
//             println!("Second execution wasn't faster (this can happen with small datasets)");
//         }

//         let stats = crate::features::redis::get_redis_cache_stats_impl(&redis_conn).await.unwrap();
//         println!("๐Ÿ“Š Cache statistics:");
//         println!("   Total keys: {}", stats.total_keys);
//         println!("   Cache hits: {}", stats.cache_hits);
//         println!("   Cache misses: {}", stats.cache_misses);
//         println!("   Hit rate: {:.2}%", stats.hit_rate);


//         assert!(stats.total_keys > 0, "Should have cached data");
//         assert!(stats.cache_hits > 0 || stats.cache_misses > 0, "Should have cache activity");

//         crate::features::redis::invalidate_redis_cache_impl(&redis_conn, &["test_users"]).await.unwrap();
        
//         let stats_after_invalidation = crate::features::redis::get_redis_cache_stats_impl(&redis_conn).await.unwrap();
//         println!("Stats after invalidation - Total keys: {}", stats_after_invalidation.total_keys);

//     }

//     #[tokio::test]
//     async fn test_cache_ttl_with_dataframe() {

//         let redis_conn = match crate::features::redis::create_redis_cache_connection().await {
//             Ok(conn) => conn,
//             Err(_) => {
//                 println!("โญ๏ธ Skipping TTL test - Redis not available");
//                 return;
//             }
//         };

//         let df = create_test_dataframe().await.unwrap();

//         let _result = crate::features::redis::elusion_with_redis_cache_impl(
//             &df,
//             &redis_conn,
//             "ttl_test_users",
//             Some(2),
//         ).await.unwrap();

//         let stats = crate::features::redis::get_redis_cache_stats_impl(&redis_conn).await.unwrap();
//         let keys_before_expiry = stats.total_keys;
//         println!("Keys before expiry: {}", keys_before_expiry);

//         tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;

//         let stats_after = crate::features::redis::get_redis_cache_stats_impl(&redis_conn).await.unwrap();
//         println!("Keys after expiry: {}", stats_after.total_keys);

//     }

//     #[tokio::test]
//     async fn test_concurrent_cache_access() {
//         println!("๐Ÿงช Testing concurrent cache access...");

//         let redis_conn = match crate::features::redis::create_redis_cache_connection().await {
//             Ok(conn) => conn,
//             Err(_) => {
//                 println!("Skipping concurrent test - Redis not available");
//                 return;
//             }
//         };

//         crate::features::redis::clear_redis_cache_impl(&redis_conn, None).await.unwrap();

//         let df = create_test_dataframe().await.unwrap();

//         let mut tasks = vec![];

//         for i in 0..5 {
//             let df_clone = df.clone(); 
//             let conn_clone = redis_conn.clone();
//             let alias = format!("concurrent_test_{}", i);

//             let task = tokio::spawn(async move {
//                 let start_time = Instant::now();
//                 let _result = crate::features::redis::elusion_with_redis_cache_impl(
//                     &df_clone,
//                     &conn_clone,
//                     &alias,
//                     Some(300),
//                 ).await.unwrap();
                
//                 (i, start_time.elapsed())
//             });

//             tasks.push(task);
//         }

//         let mut results = vec![];
//         for task in tasks {
//             let result = task.await.unwrap();
//             results.push(result);
//         }

//         for (task_id, duration) in results {
//             println!("   Task {}: {:?}", task_id, duration);
//         }

//         let stats = crate::features::redis::get_redis_cache_stats_impl(&redis_conn).await.unwrap();
//         println!("๐Ÿ“Š Final stats - Total keys: {}, Hits: {}, Misses: {}", 
//                 stats.total_keys, stats.cache_hits, stats.cache_misses);

//     }
// }