hdbconnect-mcp 0.3.4

MCP server for SAP HANA database
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
//! Helper utilities for MCP server

#[cfg(feature = "cache")]
use std::future::Future;

use hdbconnect_async::HdbValue;
use rmcp::ErrorData;
#[cfg(feature = "cache")]
use serde::{Deserialize, Serialize};

use crate::Error;
use crate::pool::{Pool, PooledConnection};

/// Get a connection from the pool, returning `ErrorData` on failure
pub async fn get_connection(pool: &Pool) -> Result<PooledConnection, ErrorData> {
    Box::pin(pool.get())
        .await
        .map_err(|_| Error::PoolExhausted.into())
}

/// Convert `HdbValue` to `serde_json::Value`
pub fn hdb_value_to_json(value: &HdbValue) -> serde_json::Value {
    match value {
        HdbValue::NULL => serde_json::Value::Null,
        HdbValue::TINYINT(v) => serde_json::json!(v),
        HdbValue::SMALLINT(v) => serde_json::json!(v),
        HdbValue::INT(v) => serde_json::json!(v),
        HdbValue::BIGINT(v) => serde_json::json!(v),
        HdbValue::DECIMAL(v) => serde_json::json!(v.to_string()),
        HdbValue::REAL(v) => serde_json::json!(v),
        HdbValue::DOUBLE(v) => serde_json::json!(v),
        HdbValue::STRING(v) => serde_json::json!(v),
        HdbValue::BOOLEAN(v) => serde_json::json!(v),
        _ => serde_json::json!(format!("{value:?}")),
    }
}

/// Try to get a value from cache, falling back to a fetch function.
/// Cache errors are logged but never propagate - always fallback to fetch.
#[cfg(feature = "cache")]
pub async fn cached_or_fetch<T, F, Fut>(
    cache: &dyn crate::cache::CacheProvider,
    key: &crate::cache::CacheKey,
    ttl: std::time::Duration,
    fetch: F,
) -> crate::Result<T>
where
    T: Serialize + for<'de> Deserialize<'de>,
    F: FnOnce() -> Fut,
    Fut: Future<Output = crate::Result<T>>,
{
    // 1. Try cache first
    match cache.get(key).await {
        Ok(Some(data)) => match serde_json::from_slice::<T>(&data) {
            Ok(value) => {
                tracing::debug!(
                    cache.result = "hit",
                    cache.key = %key,
                    "Returning cached value"
                );
                return Ok(value);
            }
            Err(e) => {
                tracing::warn!(
                    cache.key = %key,
                    error = %e,
                    "Cache deserialization failed, fetching from source"
                );
            }
        },
        Ok(None) => {
            tracing::debug!(
                cache.result = "miss",
                cache.key = %key,
                "Cache miss, fetching from source"
            );
        }
        Err(e) => {
            tracing::warn!(
                cache.key = %key,
                error = %e,
                "Cache get failed, fetching from source"
            );
        }
    }

    // 2. Fetch from source
    let value = fetch().await?;

    // 3. Store in cache (fire-and-forget, errors logged but not propagated)
    match serde_json::to_vec(&value) {
        Ok(data) => {
            if let Err(e) = cache.set(key, &data, Some(ttl)).await {
                tracing::warn!(
                    cache.key = %key,
                    error = %e,
                    "Failed to cache value"
                );
            }
        }
        Err(e) => {
            tracing::warn!(
                cache.key = %key,
                error = %e,
                "Failed to serialize value for caching"
            );
        }
    }

    Ok(value)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_hdb_value_to_json_null() {
        let result = hdb_value_to_json(&HdbValue::NULL);
        assert!(result.is_null());
    }

    #[test]
    fn test_hdb_value_to_json_tinyint() {
        let result = hdb_value_to_json(&HdbValue::TINYINT(42));
        assert_eq!(result.as_u64(), Some(42));
    }

    #[test]
    fn test_hdb_value_to_json_smallint() {
        let result = hdb_value_to_json(&HdbValue::SMALLINT(1234));
        assert_eq!(result.as_i64(), Some(1234));
    }

    #[test]
    fn test_hdb_value_to_json_int() {
        let result = hdb_value_to_json(&HdbValue::INT(123456));
        assert_eq!(result.as_i64(), Some(123456));
    }

    #[test]
    fn test_hdb_value_to_json_bigint() {
        let result = hdb_value_to_json(&HdbValue::BIGINT(9_876_543_210));
        assert_eq!(result.as_i64(), Some(9_876_543_210));
    }

    #[test]
    fn test_hdb_value_to_json_real() {
        let result = hdb_value_to_json(&HdbValue::REAL(3.14));
        assert!(result.is_number());
    }

    #[test]
    fn test_hdb_value_to_json_double() {
        let result = hdb_value_to_json(&HdbValue::DOUBLE(2.71828));
        assert_eq!(result.as_f64(), Some(2.71828));
    }

    #[test]
    fn test_hdb_value_to_json_string() {
        let result = hdb_value_to_json(&HdbValue::STRING("hello world".to_string()));
        assert_eq!(result.as_str(), Some("hello world"));
    }

    #[test]
    fn test_hdb_value_to_json_boolean_true() {
        let result = hdb_value_to_json(&HdbValue::BOOLEAN(true));
        assert_eq!(result.as_bool(), Some(true));
    }

    #[test]
    fn test_hdb_value_to_json_boolean_false() {
        let result = hdb_value_to_json(&HdbValue::BOOLEAN(false));
        assert_eq!(result.as_bool(), Some(false));
    }

    #[test]
    fn test_hdb_value_to_json_binary_fallback() {
        let result = hdb_value_to_json(&HdbValue::BINARY(vec![1, 2, 3]));
        assert!(result.is_string());
        assert!(result.as_str().unwrap().contains("BINARY"));
    }
}

#[cfg(all(test, feature = "cache"))]
mod cache_tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::Duration;

    use async_trait::async_trait;
    use parking_lot::RwLock;

    use super::*;
    use crate::cache::{
        CacheEntryMeta, CacheError, CacheKey, CacheProvider, CacheResult, CacheStats,
    };

    #[derive(Default)]
    struct MockCache {
        get_calls: AtomicU64,
        set_calls: AtomicU64,
        stored: RwLock<std::collections::HashMap<String, Vec<u8>>>,
        fail_get: AtomicU64,
        fail_set: AtomicU64,
    }

    #[async_trait]
    impl CacheProvider for MockCache {
        async fn get(&self, key: &CacheKey) -> CacheResult<Option<Vec<u8>>> {
            self.get_calls.fetch_add(1, Ordering::Relaxed);
            if self.fail_get.load(Ordering::Relaxed) > 0 {
                self.fail_get.fetch_sub(1, Ordering::Relaxed);
                return Err(CacheError::Connection("mock failure".into()));
            }
            Ok(self.stored.read().get(&key.to_key_string()).cloned())
        }

        async fn set(
            &self,
            key: &CacheKey,
            value: &[u8],
            _ttl: Option<Duration>,
        ) -> CacheResult<()> {
            self.set_calls.fetch_add(1, Ordering::Relaxed);
            if self.fail_set.load(Ordering::Relaxed) > 0 {
                self.fail_set.fetch_sub(1, Ordering::Relaxed);
                return Err(CacheError::Connection("mock failure".into()));
            }
            self.stored
                .write()
                .insert(key.to_key_string(), value.to_vec());
            Ok(())
        }

        async fn delete(&self, key: &CacheKey) -> CacheResult<bool> {
            Ok(self.stored.write().remove(&key.to_key_string()).is_some())
        }

        async fn exists(&self, key: &CacheKey) -> CacheResult<bool> {
            Ok(self.stored.read().contains_key(&key.to_key_string()))
        }

        async fn delete_by_prefix(&self, prefix: &str) -> CacheResult<u64> {
            let mut count = 0;
            self.stored.write().retain(|k, _| {
                if k.starts_with(prefix) {
                    count += 1;
                    false
                } else {
                    true
                }
            });
            Ok(count)
        }

        async fn metadata(&self, key: &CacheKey) -> CacheResult<Option<CacheEntryMeta>> {
            Ok(self
                .stored
                .read()
                .get(&key.to_key_string())
                .map(|data| CacheEntryMeta {
                    size_bytes: Some(data.len()),
                    ttl_remaining: None,
                    compressed: false,
                }))
        }

        async fn clear(&self) -> CacheResult<()> {
            self.stored.write().clear();
            Ok(())
        }

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

        async fn stats(&self) -> CacheStats {
            CacheStats {
                hits: 0,
                misses: 0,
                sets: self.set_calls.load(Ordering::Relaxed),
                deletes: 0,
                errors: 0,
                size_bytes: None,
                entry_count: Some(self.stored.read().len() as u64),
            }
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    struct TestData {
        value: String,
    }

    #[tokio::test]
    async fn test_cached_or_fetch_cache_miss() {
        let cache = Arc::new(MockCache::default());
        let key = CacheKey::table_schema(Some("test"), "users");
        let fetch_count = Arc::new(AtomicU64::new(0));
        let fetch_count_clone = Arc::clone(&fetch_count);

        let result: TestData =
            cached_or_fetch(cache.as_ref(), &key, Duration::from_secs(60), || {
                let fetch_count = Arc::clone(&fetch_count_clone);
                async move {
                    fetch_count.fetch_add(1, Ordering::Relaxed);
                    Ok(TestData {
                        value: "from_fetch".to_string(),
                    })
                }
            })
            .await
            .unwrap();

        assert_eq!(result.value, "from_fetch");
        assert_eq!(fetch_count.load(Ordering::Relaxed), 1);
        assert_eq!(cache.get_calls.load(Ordering::Relaxed), 1);
        assert_eq!(cache.set_calls.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn test_cached_or_fetch_cache_hit() {
        let cache = Arc::new(MockCache::default());
        let key = CacheKey::table_schema(Some("test"), "users");
        let fetch_count = Arc::new(AtomicU64::new(0));

        // Pre-populate cache
        let cached_data = TestData {
            value: "cached".to_string(),
        };
        cache
            .set(&key, &serde_json::to_vec(&cached_data).unwrap(), None)
            .await
            .unwrap();
        cache.set_calls.store(0, Ordering::Relaxed);

        let fetch_count_clone = Arc::clone(&fetch_count);
        let result: TestData =
            cached_or_fetch(cache.as_ref(), &key, Duration::from_secs(60), || {
                let fetch_count = Arc::clone(&fetch_count_clone);
                async move {
                    fetch_count.fetch_add(1, Ordering::Relaxed);
                    Ok(TestData {
                        value: "from_fetch".to_string(),
                    })
                }
            })
            .await
            .unwrap();

        assert_eq!(result.value, "cached");
        assert_eq!(fetch_count.load(Ordering::Relaxed), 0);
        assert_eq!(cache.get_calls.load(Ordering::Relaxed), 1);
        assert_eq!(cache.set_calls.load(Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn test_cached_or_fetch_cache_error_fallback() {
        let cache = Arc::new(MockCache::default());
        cache.fail_get.store(1, Ordering::Relaxed);
        let key = CacheKey::table_schema(Some("test"), "users");
        let fetch_count = Arc::new(AtomicU64::new(0));
        let fetch_count_clone = Arc::clone(&fetch_count);

        let result: TestData =
            cached_or_fetch(cache.as_ref(), &key, Duration::from_secs(60), || {
                let fetch_count = Arc::clone(&fetch_count_clone);
                async move {
                    fetch_count.fetch_add(1, Ordering::Relaxed);
                    Ok(TestData {
                        value: "from_fetch".to_string(),
                    })
                }
            })
            .await
            .unwrap();

        assert_eq!(result.value, "from_fetch");
        assert_eq!(fetch_count.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn test_cached_or_fetch_deserialization_error() {
        let cache = Arc::new(MockCache::default());
        let key = CacheKey::table_schema(Some("test"), "users");

        // Pre-populate cache with invalid data
        cache.set(&key, b"invalid json", None).await.unwrap();
        cache.set_calls.store(0, Ordering::Relaxed);

        let fetch_count = Arc::new(AtomicU64::new(0));
        let fetch_count_clone = Arc::clone(&fetch_count);

        let result: TestData =
            cached_or_fetch(cache.as_ref(), &key, Duration::from_secs(60), || {
                let fetch_count = Arc::clone(&fetch_count_clone);
                async move {
                    fetch_count.fetch_add(1, Ordering::Relaxed);
                    Ok(TestData {
                        value: "from_fetch".to_string(),
                    })
                }
            })
            .await
            .unwrap();

        assert_eq!(result.value, "from_fetch");
        assert_eq!(fetch_count.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn test_cached_or_fetch_set_error_still_returns_value() {
        let cache = Arc::new(MockCache::default());
        cache.fail_set.store(1, Ordering::Relaxed);
        let key = CacheKey::table_schema(Some("test"), "users");

        let result: TestData = cached_or_fetch(
            cache.as_ref(),
            &key,
            Duration::from_secs(60),
            || async move {
                Ok(TestData {
                    value: "from_fetch".to_string(),
                })
            },
        )
        .await
        .unwrap();

        assert_eq!(result.value, "from_fetch");
        assert_eq!(cache.set_calls.load(Ordering::Relaxed), 1);
        // Cache should be empty because set failed
        assert!(cache.stored.read().is_empty());
    }
}