hyprstream_core/storage/
adbc.rs

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
//! ADBC (Arrow Database Connectivity) storage backend implementation.
//!
//! This module provides a storage backend using ADBC, enabling:
//! - Connection to any ADBC-compliant database
//! - High-performance data transport using Arrow's columnar format
//! - Connection pooling and prepared statements
//! - Support for various database systems (PostgreSQL, MySQL, etc.)
//!
//! # Configuration
//!
//! The ADBC backend can be configured using the following options:
//!
//! ```toml
//! [engine]
//! engine = "adbc"
//! # Base connection without credentials
//! connection = "postgresql://localhost:5432/metrics"
//! options = {
//!     driver_path = "/usr/local/lib/libadbc_driver_postgresql.so",  # Required: Path to ADBC driver
//!     pool_max = "10",                                            # Optional: Maximum pool connections
//!     pool_min = "1",                                             # Optional: Minimum pool connections
//!     connect_timeout = "30"                                      # Optional: Connection timeout in seconds
//! }
//! ```
//!
//! For security, credentials should be provided via environment variables:
//! ```bash
//! export HYPRSTREAM_DB_USERNAME=postgres
//! export HYPRSTREAM_DB_PASSWORD=secret
//! ```
//!
//! Or via command line:
//!
//! ```bash
//! hyprstream \
//!   --engine adbc \
//!   --engine-connection "postgresql://localhost:5432/metrics" \
//!   --engine-options driver_path=/usr/local/lib/libadbc_driver_postgresql.so \
//!   --engine-options pool_max=10
//! ```
//!
//! The implementation is optimized for efficient data transfer and
//! query execution using Arrow's native formats.

use adbc_core::{
    driver_manager::{ManagedConnection, ManagedDriver},
    options::{AdbcVersion, OptionDatabase, OptionValue},
    Connection, Database, Driver, Statement, Optionable,
};
use arrow_array::{
    Array, Int8Array, Int16Array, Int32Array, Int64Array,
    Float32Array, Float64Array, BooleanArray, StringArray,
    BinaryArray, TimestampNanosecondArray,
};
use arrow_schema::{Schema, DataType, Field};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::sync::Mutex;
use tonic::Status;
use crate::aggregation::{AggregateFunction, GroupBy, AggregateResult, build_aggregate_query};
use crate::storage::table_manager::{TableManager, AggregationView};
use crate::config::Credentials;
use crate::metrics::MetricRecord;
use crate::storage::StorageBackend;
use crate::storage::cache::{CacheManager, CacheEviction};
use arrow_array::ArrayRef;
use arrow_array::RecordBatch;
use crate::aggregation::TimeWindow;
use crate::storage::BatchAggregation;
use std::time::Duration;
use hex;
use tracing::error;

pub struct AdbcBackend {
    conn: Arc<Mutex<ManagedConnection>>,
    statement_counter: AtomicU64,
    prepared_statements: Arc<Mutex<Vec<(u64, String)>>>,
    cache_manager: CacheManager,
    table_manager: TableManager,
}

#[async_trait]
impl CacheEviction for AdbcBackend {
    async fn execute_eviction(&self, query: &str) -> Result<(), Status> {
        let conn = self.conn.clone();
        let query = query.to_string(); // Clone for background task
        tokio::spawn(async move {
            let mut conn_guard = conn.lock().await;
            if let Err(e) = conn_guard.new_statement()
                .and_then(|mut stmt| {
                    stmt.set_sql_query(&query)?;
                    stmt.execute_update()
                }) {
                tracing::error!("Background eviction error: {}", e);
            }
        });
        Ok(())
    }
}

impl AdbcBackend {
    pub fn new(driver_path: &str, connection: Option<&str>, credentials: Option<&Credentials>) -> Result<Self, Status> {
        let mut driver = ManagedDriver::load_dynamic_from_filename(
            driver_path,
            None,
            AdbcVersion::V100,
        ).map_err(|e| Status::internal(format!("Failed to load ADBC driver: {}", e)))?;

        let mut database = driver.new_database()
            .map_err(|e| Status::internal(format!("Failed to create database: {}", e)))?;

        // Set connection string if provided
        if let Some(conn_str) = connection {
            database.set_option(OptionDatabase::Uri, OptionValue::String(conn_str.to_string()))
                .map_err(|e| Status::internal(format!("Failed to set connection string: {}", e)))?;
        }

        // Set credentials if provided
        if let Some(creds) = credentials {
            database.set_option(OptionDatabase::Username, OptionValue::String(creds.username.clone()))
                .map_err(|e| Status::internal(format!("Failed to set username: {}", e)))?;

            database.set_option(OptionDatabase::Password, OptionValue::String(creds.password.clone()))
                .map_err(|e| Status::internal(format!("Failed to set password: {}", e)))?;
        }

        let connection = database.new_connection()
            .map_err(|e| Status::internal(format!("Failed to create connection: {}", e)))?;

        Ok(Self {
            conn: Arc::new(Mutex::new(connection)),
            statement_counter: AtomicU64::new(0),
            prepared_statements: Arc::new(Mutex::new(Vec::new())),
            cache_manager: CacheManager::new(None), // Initialize without TTL
            table_manager: TableManager::new(),
        })
    }

    async fn get_connection(&self) -> Result<tokio::sync::MutexGuard<'_, ManagedConnection>, Status> {
        Ok(self.conn.lock().await)
    }

    async fn execute_statement(&self, conn: &mut ManagedConnection, query: &str) -> Result<(), Status> {
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        stmt.set_sql_query(query)
            .map_err(|e| Status::internal(format!("Failed to set query: {}", e)))?;

        stmt.execute_update()
            .map_err(|e| Status::internal(format!("Failed to execute statement: {}", e)))?;

        Ok(())
    }

    async fn execute_query(&self, conn: &mut ManagedConnection, query: &str, params: Option<RecordBatch>) -> Result<Vec<MetricRecord>, Status> {
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        stmt.set_sql_query(query)
            .map_err(|e| Status::internal(format!("Failed to set query: {}", e)))?;

        if let Some(batch) = params {
            // Create a new statement for binding parameters
            let mut bind_stmt = conn.new_statement()
                .map_err(|e| Status::internal(format!("Failed to create bind statement: {}", e)))?;

            // Set the parameters using SQL directly
            let mut param_values = Vec::new();
            for i in 0..batch.num_rows() {
                for j in 0..batch.num_columns() {
                    let col = batch.column(j);
                    match col.data_type() {
                        DataType::Int64 => {
                            let array = col.as_any().downcast_ref::<Int64Array>().unwrap();
                            param_values.push(array.value(i).to_string());
                        }
                        DataType::Float64 => {
                            let array = col.as_any().downcast_ref::<Float64Array>().unwrap();
                            param_values.push(array.value(i).to_string());
                        }
                        DataType::Utf8 => {
                            let array = col.as_any().downcast_ref::<StringArray>().unwrap();
                            param_values.push(format!("'{}'", array.value(i)));
                        }
                        _ => return Err(Status::internal("Unsupported parameter type")),
                    }
                }
            }

            let params_sql = format!("VALUES ({})", param_values.join(", "));
            bind_stmt.set_sql_query(&params_sql)
                .map_err(|e| Status::internal(format!("Failed to set parameters: {}", e)))?;

            let mut bind_result = bind_stmt.execute()
                .map_err(|e| Status::internal(format!("Failed to execute parameter binding: {}", e)))?;

            while let Some(batch_result) = bind_result.next() {
                let _ = batch_result.map_err(|e| Status::internal(format!("Failed to bind parameters: {}", e)))?;
            }
        }

        let mut reader = stmt.execute()
            .map_err(|e| Status::internal(format!("Failed to execute query: {}", e)))?;

        let mut metrics = Vec::new();
        while let Some(batch_result) = reader.next() {
            let batch = batch_result.map_err(|e| Status::internal(format!("Failed to get next batch: {}", e)))?;
            
            let metric_ids = batch.column_by_name("metric_id")
                .and_then(|col| col.as_any().downcast_ref::<StringArray>())
                .ok_or_else(|| Status::internal("Invalid metric_id column"))?;

            let timestamps = batch.column_by_name("timestamp")
                .and_then(|col| col.as_any().downcast_ref::<Int64Array>())
                .ok_or_else(|| Status::internal("Invalid timestamp column"))?;

            let sums = batch.column_by_name("value_running_window_sum")
                .and_then(|col| col.as_any().downcast_ref::<Float64Array>())
                .ok_or_else(|| Status::internal("Invalid value_running_window_sum column"))?;

            let avgs = batch.column_by_name("value_running_window_avg")
                .and_then(|col| col.as_any().downcast_ref::<Float64Array>())
                .ok_or_else(|| Status::internal("Invalid value_running_window_avg column"))?;

            let counts = batch.column_by_name("value_running_window_count")
                .and_then(|col| col.as_any().downcast_ref::<Int64Array>())
                .ok_or_else(|| Status::internal("Invalid value_running_window_count column"))?;

            for i in 0..batch.num_rows() {
                metrics.push(MetricRecord {
                    metric_id: metric_ids.value(i).to_string(),
                    timestamp: timestamps.value(i),
                    value_running_window_sum: sums.value(i),
                    value_running_window_avg: avgs.value(i),
                    value_running_window_count: counts.value(i),
                });
            }
        }

        Ok(metrics)
    }

    fn prepare_timestamp_param(timestamp: i64) -> Result<RecordBatch, Status> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("timestamp", DataType::Int64, false),
        ]));

        let timestamps: ArrayRef = Arc::new(Int64Array::from(vec![timestamp]));
        
        RecordBatch::try_new(schema, vec![timestamps])
            .map_err(|e| Status::internal(format!("Failed to create parameter batch: {}", e)))
    }

    fn prepare_params(metrics: &[MetricRecord]) -> Result<RecordBatch, Status> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("metric_id", DataType::Utf8, false),
            Field::new("timestamp", DataType::Int64, false),
            Field::new("value_running_window_sum", DataType::Float64, false),
            Field::new("value_running_window_avg", DataType::Float64, false),
            Field::new("value_running_window_count", DataType::Int64, false),
        ]));

        let metric_ids = StringArray::from_iter_values(metrics.iter().map(|m| m.metric_id.as_str()));
        let timestamps = Int64Array::from_iter_values(metrics.iter().map(|m| m.timestamp));
        let sums = Float64Array::from_iter_values(metrics.iter().map(|m| m.value_running_window_sum));
        let avgs = Float64Array::from_iter_values(metrics.iter().map(|m| m.value_running_window_avg));
        let counts = Int64Array::from_iter_values(metrics.iter().map(|m| m.value_running_window_count));

        let arrays: Vec<ArrayRef> = vec![
            Arc::new(metric_ids),
            Arc::new(timestamps),
            Arc::new(sums),
            Arc::new(avgs),
            Arc::new(counts),
        ];

        RecordBatch::try_new(schema, arrays)
            .map_err(|e| Status::internal(format!("Failed to create parameter batch: {}", e)))
    }

    /// Inserts a batch of metrics with optimized aggregation updates.
    async fn insert_batch_optimized(&self, metrics: &[MetricRecord], window: TimeWindow) -> Result<(), Status> {
        // Begin transaction
        self.begin_transaction().await?;
        let mut conn = self.conn.lock().await;
        
        // Insert metrics
        let batch = Self::prepare_params(metrics)?;
        let sql = self.build_insert_sql("metrics", &batch);
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        stmt.set_sql_query(&sql)
            .map_err(|e| Status::internal(format!("Failed to set query: {}", e)))?;

        // Bind parameters
        let mut bind_stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create bind statement: {}", e)))?;

        let mut param_values = Vec::new();
        for i in 0..batch.num_rows() {
            for j in 0..batch.num_columns() {
                let col = batch.column(j);
                match col.data_type() {
                    DataType::Int64 => {
                        let array = col.as_any().downcast_ref::<Int64Array>().unwrap();
                        param_values.push(array.value(i).to_string());
                    }
                    DataType::Float64 => {
                        let array = col.as_any().downcast_ref::<Float64Array>().unwrap();
                        param_values.push(array.value(i).to_string());
                    }
                    DataType::Utf8 => {
                        let array = col.as_any().downcast_ref::<StringArray>().unwrap();
                        param_values.push(format!("'{}'", array.value(i)));
                    }
                    _ => return Err(Status::internal("Unsupported parameter type")),
                }
            }
        }

        let params_sql = format!("VALUES ({})", param_values.join(", "));
        bind_stmt.set_sql_query(&params_sql)
            .map_err(|e| Status::internal(format!("Failed to set parameters: {}", e)))?;

        let mut bind_result = bind_stmt.execute()
            .map_err(|e| Status::internal(format!("Failed to execute parameter binding: {}", e)))?;

        while let Some(batch_result) = bind_result.next() {
            let _ = batch_result.map_err(|e| Status::internal(format!("Failed to bind parameters: {}", e)))?;
        }

        stmt.execute_update()
            .map_err(|e| Status::internal(format!("Failed to insert metrics: {}", e)))?;

        // Commit transaction
        self.commit_transaction().await?;

        Ok(())
    }

    /// Prepares parameters for aggregation insertion
    fn prepare_aggregation_params(agg: &BatchAggregation) -> Result<RecordBatch, Status> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("metric_id", DataType::Utf8, false),
            Field::new("window_start", DataType::Int64, false),
            Field::new("window_end", DataType::Int64, false),
            Field::new("running_sum", DataType::Float64, false),
            Field::new("running_count", DataType::Int64, false),
            Field::new("min_value", DataType::Float64, false),
            Field::new("max_value", DataType::Float64, false),
        ]));

        let arrays: Vec<ArrayRef> = vec![
            Arc::new(StringArray::from(vec![agg.metric_id.as_str()])),
            Arc::new(Int64Array::from(vec![agg.window_start])),
            Arc::new(Int64Array::from(vec![agg.window_end])),
            Arc::new(Float64Array::from(vec![agg.running_sum])),
            Arc::new(Int64Array::from(vec![agg.running_count])),
            Arc::new(Float64Array::from(vec![agg.min_value])),
            Arc::new(Float64Array::from(vec![agg.max_value])),
        ];

        RecordBatch::try_new(schema, arrays)
            .map_err(|e| Status::internal(format!("Failed to create aggregation batch: {}", e)))
    }

    async fn begin_transaction(&self) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        stmt.set_sql_query("BEGIN")
            .map_err(|e| Status::internal(format!("Failed to set SQL query: {}", e)))?;

        stmt.execute_update()
            .map_err(|e| Status::internal(format!("Failed to execute query: {}", e)))?;

        Ok(())
    }

    async fn commit_transaction(&self) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        stmt.set_sql_query("COMMIT")
            .map_err(|e| Status::internal(format!("Failed to set SQL query: {}", e)))?;

        stmt.execute_update()
            .map_err(|e| Status::internal(format!("Failed to execute query: {}", e)))?;

        Ok(())
    }

    async fn rollback_transaction(&self, conn: &mut ManagedConnection) -> Result<(), Status> {
        self.execute_statement(conn, "ROLLBACK").await
    }

    async fn create_table(&self, table_name: &str, schema: &Schema) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let sql = self.build_create_table_sql(table_name, schema);
        self.execute_statement(&mut conn, &sql).await
    }

    async fn create_view(&self, view: &AggregationView, sql: &str) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let create_view_sql = format!("CREATE VIEW {} AS {}", view.source_table, sql);
        self.execute_statement(&mut conn, &create_view_sql).await
    }

    async fn drop_table(&self, table_name: &str) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let sql = format!("DROP TABLE IF EXISTS {}", table_name);
        self.execute_statement(&mut conn, &sql).await
    }

    async fn drop_view(&self, view_name: &str) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let sql = format!("DROP VIEW IF EXISTS {}", view_name);
        self.execute_statement(&mut conn, &sql).await
    }

    fn build_create_table_sql(&self, table_name: &str, schema: &Schema) -> String {
        let mut sql = format!("CREATE TABLE IF NOT EXISTS {} (", table_name);
        let mut first = true;

        for field in schema.fields() {
            if !first {
                sql.push_str(", ");
            }
            first = false;

            sql.push_str(&format!("{} {}", field.name(), self.arrow_type_to_sql_type(field.data_type())));
        }

        sql.push_str(")");
        sql
    }

    fn build_insert_sql(&self, table_name: &str, batch: &RecordBatch) -> String {
        let mut sql = format!("INSERT INTO {} (", table_name);
        let mut first = true;

        for field in batch.schema().fields() {
            if !first {
                sql.push_str(", ");
            }
            first = false;
            sql.push_str(field.name());
        }

        sql.push_str(") VALUES (");
        first = true;

        for i in 0..batch.num_columns() {
            if !first {
                sql.push_str(", ");
            }
            first = false;
            sql.push('?');
        }

        sql.push(')');
        sql
    }

    fn arrow_type_to_sql_type(&self, data_type: &DataType) -> &'static str {
        match data_type {
            DataType::Boolean => "BOOLEAN",
            DataType::Int8 => "TINYINT",
            DataType::Int16 => "SMALLINT",
            DataType::Int32 => "INTEGER",
            DataType::Int64 => "BIGINT",
            DataType::UInt8 => "TINYINT UNSIGNED",
            DataType::UInt16 => "SMALLINT UNSIGNED",
            DataType::UInt32 => "INTEGER UNSIGNED",
            DataType::UInt64 => "BIGINT UNSIGNED",
            DataType::Float32 => "FLOAT",
            DataType::Float64 => "DOUBLE",
            DataType::Utf8 => "VARCHAR",
            DataType::Binary => "BLOB",
            DataType::Date32 => "DATE",
            DataType::Date64 => "DATE",
            DataType::Time32(_) => "TIME",
            DataType::Time64(_) => "TIME",
            DataType::Timestamp(_, _) => "TIMESTAMP",
            _ => "VARCHAR",
        }
    }
}

#[async_trait]
impl StorageBackend for AdbcBackend {
    async fn init(&self) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        
        // Create metrics table
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        stmt.set_sql_query(r#"
            CREATE TABLE IF NOT EXISTS metrics (
                metric_id VARCHAR NOT NULL,
                timestamp BIGINT NOT NULL,
                value_running_window_sum DOUBLE PRECISION NOT NULL,
                value_running_window_avg DOUBLE PRECISION NOT NULL,
                value_running_window_count BIGINT NOT NULL,
                PRIMARY KEY (metric_id, timestamp)
            );

            CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON metrics(timestamp);

            CREATE TABLE IF NOT EXISTS metric_aggregations (
                metric_id VARCHAR NOT NULL,
                window_start BIGINT NOT NULL,
                window_end BIGINT NOT NULL,
                running_sum DOUBLE PRECISION NOT NULL,
                running_count BIGINT NOT NULL,
                min_value DOUBLE PRECISION NOT NULL,
                max_value DOUBLE PRECISION NOT NULL,
                PRIMARY KEY (metric_id, window_start, window_end)
            );

            CREATE INDEX IF NOT EXISTS idx_aggregations_window 
            ON metric_aggregations(window_start, window_end);
        "#).map_err(|e| Status::internal(format!("Failed to set query: {}", e)))?;

        stmt.execute_update()
            .map_err(|e| Status::internal(format!("Failed to create tables: {}", e)))?;

        Ok(())
    }

    async fn insert_metrics(&self, metrics: Vec<MetricRecord>) -> Result<(), Status> {
        if metrics.is_empty() {
            return Ok(());
        }

        // Check if eviction is needed
        if let Some(cutoff) = self.cache_manager.should_evict().await? {
            let query = self.cache_manager.eviction_query(cutoff);
            self.execute_eviction(&query).await?;
        }

        // Use sliding window for batch-level aggregations
        let window = TimeWindow::Sliding {
            window: Duration::from_secs(3600), // 1 hour window
            slide: Duration::from_secs(60),    // 1 minute slide
        };

        // Use optimized batch insertion
        self.insert_batch_optimized(&metrics, window).await
    }

    async fn query_metrics(&self, from_timestamp: i64) -> Result<Vec<MetricRecord>, Status> {
        // Check if eviction is needed
        if let Some(cutoff) = self.cache_manager.should_evict().await? {
            let query = self.cache_manager.eviction_query(cutoff);
            self.execute_eviction(&query).await?;
        }

        let mut conn = self.conn.lock().await;
        
        let query = r#"
            SELECT
                metric_id,
                timestamp,
                value_running_window_sum,
                value_running_window_avg,
                value_running_window_count
            FROM metrics
            WHERE timestamp >= ?
            ORDER BY timestamp ASC
        "#;

        let params = Self::prepare_timestamp_param(from_timestamp)?;
        self.execute_query(&mut conn, query, Some(params)).await
    }

    async fn prepare_sql(&self, query: &str) -> Result<Vec<u8>, Status> {
        let handle = self.statement_counter.fetch_add(1, Ordering::SeqCst);
        let mut statements = self.prepared_statements.lock().await;
        statements.push((handle, query.to_string()));
        Ok(handle.to_le_bytes().to_vec())
    }

    async fn query_sql(&self, statement_handle: &[u8]) -> Result<Vec<MetricRecord>, Status> {
        let handle = u64::from_le_bytes(
            statement_handle.try_into()
                .map_err(|_| Status::invalid_argument("Invalid statement handle"))?
        );

        let statements = self.prepared_statements.lock().await;
        let sql = statements
            .iter()
            .find(|(h, _)| *h == handle)
            .map(|(_, sql)| sql.as_str())
            .ok_or_else(|| Status::invalid_argument("Statement handle not found"))?;

        let mut conn = self.conn.lock().await;
        self.execute_query(&mut conn, sql, None).await
    }

    async fn aggregate_metrics(
        &self,
        function: AggregateFunction,
        group_by: &GroupBy,
        from_timestamp: i64,
        to_timestamp: Option<i64>,
    ) -> Result<Vec<AggregateResult>, Status> {
        // Check if eviction is needed
        if let Some(cutoff) = self.cache_manager.should_evict().await? {
            let query = self.cache_manager.eviction_query(cutoff);
            self.execute_eviction(&query).await?;
        }

        const DEFAULT_COLUMNS: [&str; 5] = [
            "metric_id",
            "timestamp",
            "value_running_window_sum",
            "value_running_window_avg",
            "value_running_window_count"
        ];

        let query = build_aggregate_query(
            "metrics",
            function,
            group_by,
            &DEFAULT_COLUMNS,
            Some(from_timestamp),
            to_timestamp,
        );
        let mut conn = self.conn.lock().await;
        let metrics = self.execute_query(&mut conn, &query, None).await?;

        let mut results = Vec::new();
        for metric in metrics {
            let result = AggregateResult {
                value: metric.value_running_window_sum,
                timestamp: metric.timestamp,
                // Add any other fields required by AggregateResult
            };
            results.push(result);
        }

        Ok(results)
    }

    fn new_with_options(
        connection_string: &str,
        options: &HashMap<String, String>,
        credentials: Option<&Credentials>,
    ) -> Result<Self, Status> {
        let driver_path = options.get("driver_path")
            .ok_or_else(|| Status::invalid_argument("driver_path is required"))?;

        let mut driver = ManagedDriver::load_dynamic_from_filename(
            driver_path,
            None,
            AdbcVersion::V100,
        ).map_err(|e| Status::internal(format!("Failed to load ADBC driver: {}", e)))?;

        let mut database = driver.new_database()
            .map_err(|e| Status::internal(format!("Failed to create database: {}", e)))?;

        // Set connection string
        database.set_option(OptionDatabase::Uri, OptionValue::String(connection_string.to_string()))
            .map_err(|e| Status::internal(format!("Failed to set connection string: {}", e)))?;

        // Set credentials if provided
        if let Some(creds) = credentials {
            database.set_option(OptionDatabase::Username, OptionValue::String(creds.username.clone()))
                .map_err(|e| Status::internal(format!("Failed to set username: {}", e)))?;

            database.set_option(OptionDatabase::Password, OptionValue::String(creds.password.clone()))
                .map_err(|e| Status::internal(format!("Failed to set password: {}", e)))?;
        }

        let connection = database.new_connection()
            .map_err(|e| Status::internal(format!("Failed to create connection: {}", e)))?;

        Ok(Self {
            conn: Arc::new(Mutex::new(connection)),
            statement_counter: AtomicU64::new(0),
            prepared_statements: Arc::new(Mutex::new(Vec::new())),
            cache_manager: CacheManager::new(None), // Initialize without TTL
            table_manager: TableManager::new(),
        })
    }

    async fn create_table(&self, table_name: &str, schema: &Schema) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let sql = self.build_create_table_sql(table_name, schema);
        self.execute_statement(&mut conn, &sql).await
    }

    async fn insert_into_table(&self, table_name: &str, batch: RecordBatch) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let sql = self.build_insert_sql(table_name, &batch);
        self.execute_statement(&mut conn, &sql).await
    }

    async fn query_table(&self, table_name: &str, projection: Option<Vec<String>>) -> Result<RecordBatch, Status> {
        let mut conn = self.conn.lock().await;
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        let columns = projection.map(|cols| cols.join(", ")).unwrap_or_else(|| "*".to_string());
        let sql = format!("SELECT {} FROM {}", columns, table_name);

        stmt.set_sql_query(&sql)
            .map_err(|e| Status::internal(format!("Failed to set query: {}", e)))?;

        let mut reader = stmt.execute()
            .map_err(|e| Status::internal(format!("Failed to execute query: {}", e)))?;

        let batch = reader.next()
            .ok_or_else(|| Status::internal("No data returned"))?
            .map_err(|e| Status::internal(format!("Failed to read record batch: {}", e)))?;

        // Convert ADBC RecordBatch to Arrow RecordBatch
        let schema = batch.schema();
        let mut arrays = Vec::with_capacity(batch.num_columns());

        for i in 0..batch.num_columns() {
            let col = batch.column(i);
            let array: ArrayRef = match col.data_type() {
                &duckdb::arrow::datatypes::DataType::Int64 => {
                    Arc::new(col.as_any().downcast_ref::<Int64Array>().unwrap().clone())
                },
                &duckdb::arrow::datatypes::DataType::Float64 => {
                    Arc::new(col.as_any().downcast_ref::<Float64Array>().unwrap().clone())
                },
                &duckdb::arrow::datatypes::DataType::Utf8 => {
                    Arc::new(col.as_any().downcast_ref::<StringArray>().unwrap().clone())
                },
                _ => return Err(Status::internal("Unsupported column type")),
            };
            arrays.push(array);
        }

        // Convert DuckDB schema to Arrow schema
        let fields: Vec<Field> = schema.fields().iter().map(|f| {
            Field::new(
                f.name(),
                match f.data_type() {
                    &duckdb::arrow::datatypes::DataType::Int64 => DataType::Int64,
                    &duckdb::arrow::datatypes::DataType::Float64 => DataType::Float64,
                    &duckdb::arrow::datatypes::DataType::Utf8 => DataType::Utf8,
                    _ => DataType::Utf8, // Default to string for unsupported types
                },
                f.is_nullable()
            )
        }).collect();

        let arrow_schema = Schema::new(fields);
        RecordBatch::try_new(Arc::new(arrow_schema), arrays)
            .map_err(|e| Status::internal(format!("Failed to create record batch: {}", e)))
    }

    async fn create_aggregation_view(&self, view: &AggregationView) -> Result<(), Status> {
        let columns: Vec<&str> = view.aggregate_columns.iter()
            .map(|s| s.as_str())
            .collect();
            
        let sql = build_aggregate_query(
            &view.source_table,
            view.function,
            &view.group_by,
            &columns,
            None,
            None
        );
        
        let mut conn = self.conn.lock().await;
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        stmt.set_sql_query(&format!("CREATE VIEW {} AS {}", view.source_table, sql))
            .map_err(|e| Status::internal(format!("Failed to set SQL query: {}", e)))?;

        stmt.execute_update()
            .map_err(|e| Status::internal(format!("Failed to execute query: {}", e)))?;

        Ok(())
    }

    async fn query_aggregation_view(&self, view_name: &str) -> Result<RecordBatch, Status> {
        let sql = format!("SELECT * FROM {}", view_name);

        let mut conn = self.conn.lock().await;
        let mut stmt = conn.new_statement()
            .map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;

        stmt.set_sql_query(&sql)
            .map_err(|e| Status::internal(format!("Failed to set SQL query: {}", e)))?;

        let mut reader = stmt.execute()
            .map_err(|e| Status::internal(format!("Failed to execute query: {}", e)))?;

        let batch = reader.next()
            .ok_or_else(|| Status::internal("No data returned"))?
            .map_err(|e| Status::internal(format!("Failed to read record batch: {}", e)))?;

        // Convert DuckDB RecordBatch to Arrow RecordBatch
        let schema = batch.schema();
        let mut arrays = Vec::with_capacity(batch.num_columns());

        for i in 0..batch.num_columns() {
            let col = batch.column(i);
            let array: ArrayRef = match col.data_type() {
                &duckdb::arrow::datatypes::DataType::Int64 => {
                    Arc::new(col.as_any().downcast_ref::<Int64Array>().unwrap().clone())
                },
                &duckdb::arrow::datatypes::DataType::Float64 => {
                    Arc::new(col.as_any().downcast_ref::<Float64Array>().unwrap().clone())
                },
                &duckdb::arrow::datatypes::DataType::Utf8 => {
                    Arc::new(col.as_any().downcast_ref::<StringArray>().unwrap().clone())
                },
                _ => return Err(Status::internal("Unsupported column type")),
            };
            arrays.push(array);
        }

        // Convert DuckDB schema to Arrow schema
        let fields: Vec<Field> = schema.fields().iter().map(|f| {
            Field::new(
                f.name(),
                match f.data_type() {
                    &duckdb::arrow::datatypes::DataType::Int64 => DataType::Int64,
                    &duckdb::arrow::datatypes::DataType::Float64 => DataType::Float64,
                    &duckdb::arrow::datatypes::DataType::Utf8 => DataType::Utf8,
                    _ => DataType::Utf8, // Default to string for unsupported types
                },
                f.is_nullable()
            )
        }).collect();

        let arrow_schema = Schema::new(fields);
        RecordBatch::try_new(Arc::new(arrow_schema), arrays)
            .map_err(|e| Status::internal(format!("Failed to create record batch: {}", e)))
    }

    async fn drop_table(&self, table_name: &str) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let mut stmt = conn.new_statement().map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;
        stmt.set_sql_query(&format!("DROP TABLE IF EXISTS {}", table_name))
            .map_err(|e| Status::internal(format!("Failed to set SQL query: {}", e)))?;
        stmt.execute_update().map_err(|e| Status::internal(format!("Failed to drop table: {}", e)))?;
        Ok(())
    }

    async fn drop_aggregation_view(&self, view_name: &str) -> Result<(), Status> {
        let mut conn = self.conn.lock().await;
        let mut stmt = conn.new_statement().map_err(|e| Status::internal(format!("Failed to create statement: {}", e)))?;
        stmt.set_sql_query(&format!("DROP VIEW IF EXISTS {}", view_name))
            .map_err(|e| Status::internal(format!("Failed to set SQL query: {}", e)))?;
        stmt.execute_update().map_err(|e| Status::internal(format!("Failed to drop view: {}", e)))?;
        Ok(())
    }

    fn table_manager(&self) -> &TableManager {
        &self.table_manager
    }
}

fn format_value(array: &dyn Array, index: usize) -> String {
    match array.data_type() {
        DataType::Int8 => format!("{}", array.as_any().downcast_ref::<Int8Array>().unwrap().value(index)),
        DataType::Int16 => format!("{}", array.as_any().downcast_ref::<Int16Array>().unwrap().value(index)),
        DataType::Int32 => format!("{}", array.as_any().downcast_ref::<Int32Array>().unwrap().value(index)),
        DataType::Int64 => format!("{}", array.as_any().downcast_ref::<Int64Array>().unwrap().value(index)),
        DataType::Float32 => format!("{}", array.as_any().downcast_ref::<Float32Array>().unwrap().value(index)),
        DataType::Float64 => format!("{}", array.as_any().downcast_ref::<Float64Array>().unwrap().value(index)),
        DataType::Boolean => format!("{}", array.as_any().downcast_ref::<BooleanArray>().unwrap().value(index)),
        DataType::Utf8 => format!("'{}'", array.as_any().downcast_ref::<StringArray>().unwrap().value(index)),
        DataType::Binary => format!("X'{}'", hex::encode(array.as_any().downcast_ref::<BinaryArray>().unwrap().value(index))),
        DataType::Timestamp(_, _) => {
            let ts = array.as_any().downcast_ref::<TimestampNanosecondArray>().unwrap().value(index);
            format!("'{}'", chrono::NaiveDateTime::from_timestamp(ts / 1_000_000_000, (ts % 1_000_000_000) as u32))
        },
        _ => "NULL".to_string(),
    }
}