pywatt_sdk 0.5.3

Standardized SDK for building PyWatt modules in Rust
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
use async_trait::async_trait;
use base64::{engine::general_purpose::STANDARD, Engine};
use serde::de::Error as DeError;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::Mutex;

use crate::data::database::{
    DatabaseConfig, DatabaseConnection, DatabaseError, DatabaseResult, DatabaseRow,
    DatabaseTransaction, DatabaseType, DatabaseValue,
};
use crate::ipc::send_request;
use crate::ipc_types::{
    ServiceOperation, ServiceOperationResult, ServiceRequest, ServiceResponse, ServiceType,
};

// Row implementation for proxy connections
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ProxyDatabaseRow {
    data: std::collections::HashMap<String, serde_json::Value>,
}

impl DatabaseRow for ProxyDatabaseRow {
    fn get_string(&self, column: &str) -> DatabaseResult<String> {
        match self.data.get(column) {
            Some(value) => {
                if let Some(s) = value.as_str() {
                    Ok(s.to_string())
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not a string",
                        column
                    )))
                }
            }
            None => Err(DatabaseError::Query(format!(
                "Column '{}' not found",
                column
            ))),
        }
    }

    fn get_i64(&self, column: &str) -> DatabaseResult<i64> {
        match self.data.get(column) {
            Some(value) => {
                if let Some(n) = value.as_i64() {
                    Ok(n)
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not an integer",
                        column
                    )))
                }
            }
            None => Err(DatabaseError::Query(format!(
                "Column '{}' not found",
                column
            ))),
        }
    }

    fn get_f64(&self, column: &str) -> DatabaseResult<f64> {
        match self.data.get(column) {
            Some(value) => {
                if let Some(n) = value.as_f64() {
                    Ok(n)
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not a float",
                        column
                    )))
                }
            }
            None => Err(DatabaseError::Query(format!(
                "Column '{}' not found",
                column
            ))),
        }
    }

    fn get_bool(&self, column: &str) -> DatabaseResult<bool> {
        match self.data.get(column) {
            Some(value) => {
                if let Some(b) = value.as_bool() {
                    Ok(b)
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not a boolean",
                        column
                    )))
                }
            }
            None => Err(DatabaseError::Query(format!(
                "Column '{}' not found",
                column
            ))),
        }
    }

    fn get_bytes(&self, column: &str) -> DatabaseResult<Vec<u8>> {
        match self.data.get(column) {
            Some(value) => {
                if let Some(s) = value.as_str() {
                    match STANDARD.decode(s) {
                        Ok(bytes) => Ok(bytes),
                        Err(e) => Err(DatabaseError::Query(format!(
                            "Column '{}' has invalid base64: {}",
                            column, e
                        ))),
                    }
                } else if let Some(array) = value.as_array() {
                    let bytes: Result<Vec<u8>, _> = array
                        .iter()
                        .map(|v| {
                            if let Some(n) = v.as_u64() {
                                if n <= 255 {
                                    Ok(n as u8)
                                } else {
                                    Err(DatabaseError::Query(format!(
                                        "Invalid byte value {} in column '{}'",
                                        n, column
                                    )))
                                }
                            } else {
                                Err(DatabaseError::Query(format!(
                                    "Invalid byte value in column '{}'",
                                    column
                                )))
                            }
                        })
                        .collect();
                    bytes
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not bytes",
                        column
                    )))
                }
            }
            None => Err(DatabaseError::Query(format!(
                "Column '{}' not found",
                column
            ))),
        }
    }

    fn try_get_string(&self, column: &str) -> DatabaseResult<Option<String>> {
        match self.data.get(column) {
            Some(value) => {
                if value.is_null() {
                    Ok(None)
                } else if let Some(s) = value.as_str() {
                    Ok(Some(s.to_string()))
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not a string",
                        column
                    )))
                }
            }
            None => Ok(None),
        }
    }

    fn try_get_i64(&self, column: &str) -> DatabaseResult<Option<i64>> {
        match self.data.get(column) {
            Some(value) => {
                if value.is_null() {
                    Ok(None)
                } else if let Some(n) = value.as_i64() {
                    Ok(Some(n))
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not an integer",
                        column
                    )))
                }
            }
            None => Ok(None),
        }
    }

    fn try_get_f64(&self, column: &str) -> DatabaseResult<Option<f64>> {
        match self.data.get(column) {
            Some(value) => {
                if value.is_null() {
                    Ok(None)
                } else if let Some(n) = value.as_f64() {
                    Ok(Some(n))
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not a float",
                        column
                    )))
                }
            }
            None => Ok(None),
        }
    }

    fn try_get_bool(&self, column: &str) -> DatabaseResult<Option<bool>> {
        match self.data.get(column) {
            Some(value) => {
                if value.is_null() {
                    Ok(None)
                } else if let Some(b) = value.as_bool() {
                    Ok(Some(b))
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not a boolean",
                        column
                    )))
                }
            }
            None => Ok(None),
        }
    }

    fn try_get_bytes(&self, column: &str) -> DatabaseResult<Option<Vec<u8>>> {
        match self.data.get(column) {
            Some(value) => {
                if value.is_null() {
                    Ok(None)
                } else if let Some(s) = value.as_str() {
                    match STANDARD.decode(s) {
                        Ok(bytes) => Ok(Some(bytes)),
                        Err(e) => Err(DatabaseError::Query(format!(
                            "Column '{}' has invalid base64: {}",
                            column, e
                        ))),
                    }
                } else if let Some(array) = value.as_array() {
                    let bytes: Result<Vec<u8>, _> = array
                        .iter()
                        .map(|v| {
                            if let Some(n) = v.as_u64() {
                                if n <= 255 {
                                    Ok(n as u8)
                                } else {
                                    Err(DatabaseError::Query(format!(
                                        "Invalid byte value {} in column '{}'",
                                        n, column
                                    )))
                                }
                            } else {
                                Err(DatabaseError::Query(format!(
                                    "Invalid byte value in column '{}'",
                                    column
                                )))
                            }
                        })
                        .collect();
                    bytes.map(Some)
                } else {
                    Err(DatabaseError::Query(format!(
                        "Column '{}' is not bytes",
                        column
                    )))
                }
            }
            None => Ok(None),
        }
    }
}

// ProxyDatabaseTransaction for handling transactions via IPC
pub struct ProxyDatabaseTransaction {
    connection_id: String,
    transaction_id: String,
}

#[async_trait]
impl DatabaseTransaction for ProxyDatabaseTransaction {
    async fn execute(&mut self, query: &str, params: &[DatabaseValue]) -> DatabaseResult<u64> {
        let serialized_params =
            serialize_params(params).map_err(|e| DatabaseError::Serialization(e.to_string()))?;

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "transaction_execute".to_string(),
            params: serde_json::json!({
                "transaction_id": self.transaction_id,
                "query": query,
                "params": serialized_params
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                let affected = value.as_u64().ok_or_else(|| {
                    DatabaseError::Query("Invalid affected rows count".to_string())
                })?;
                Ok(affected)
            }
            None => Err(DatabaseError::Query("No result from operation".to_string())),
        }
    }

    async fn query(
        &mut self,
        query: &str,
        params: &[DatabaseValue],
    ) -> DatabaseResult<Vec<Box<dyn DatabaseRow>>> {
        let serialized_params =
            serialize_params(params).map_err(|e| DatabaseError::Serialization(e.to_string()))?;

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "transaction_query".to_string(),
            params: serde_json::json!({
                "transaction_id": self.transaction_id,
                "query": query,
                "params": serialized_params
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                let rows: Vec<ProxyDatabaseRow> = serde_json::from_value(value).map_err(|e| {
                    DatabaseError::Serialization(format!("Failed to deserialize rows: {}", e))
                })?;

                Ok(rows
                    .into_iter()
                    .map(|r| Box::new(r) as Box<dyn DatabaseRow>)
                    .collect())
            }
            None => Err(DatabaseError::Query("No result from operation".to_string())),
        }
    }

    async fn query_one(
        &mut self,
        query: &str,
        params: &[DatabaseValue],
    ) -> DatabaseResult<Option<Box<dyn DatabaseRow>>> {
        let serialized_params =
            serialize_params(params).map_err(|e| DatabaseError::Serialization(e.to_string()))?;

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "transaction_query_one".to_string(),
            params: serde_json::json!({
                "transaction_id": self.transaction_id,
                "query": query,
                "params": serialized_params
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if value.is_null() {
                    return Ok(None);
                }

                let row: ProxyDatabaseRow = serde_json::from_value(value).map_err(|e| {
                    DatabaseError::Serialization(format!("Failed to deserialize row: {}", e))
                })?;

                Ok(Some(Box::new(row) as Box<dyn DatabaseRow>))
            }
            None => Ok(None),
        }
    }

    async fn commit(self: Box<Self>) -> DatabaseResult<()> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "transaction_commit".to_string(),
            params: serde_json::json!({
                "transaction_id": self.transaction_id,
            }),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(DatabaseError::Transaction(
                result
                    .error
                    .unwrap_or_else(|| "Unknown transaction error".to_string()),
            ))
        }
    }

    async fn rollback(self: Box<Self>) -> DatabaseResult<()> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "transaction_rollback".to_string(),
            params: serde_json::json!({
                "transaction_id": self.transaction_id,
            }),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(DatabaseError::Transaction(
                result
                    .error
                    .unwrap_or_else(|| "Unknown transaction error".to_string()),
            ))
        }
    }
}

// ProxyDatabaseConnection for handling database connections via IPC
pub struct ProxyDatabaseConnection {
    connection_id: String,
    db_type: DatabaseType,
    active_transactions: Arc<Mutex<Vec<String>>>,
}

impl ProxyDatabaseConnection {
    pub async fn connect(config: &DatabaseConfig) -> DatabaseResult<Self> {
        // Create a unique ID for this connection request
        let request_id = format!("db_request_{}", uuid::Uuid::new_v4());

        // Create a service request
        let request = ServiceRequest {
            id: request_id.clone(),
            service_type: ServiceType::Database,
            config: Some(serde_json::to_value(config).map_err(|e| {
                DatabaseError::Configuration(format!("Failed to serialize database config: {}", e))
            })?),
        };

        // Send the request to the orchestrator
        let response = send_request(&request)
            .await
            .map_err(|e| DatabaseError::Connection(format!("Failed to send request: {}", e)))?;

        // Deserialize the response
        let service_response: ServiceResponse = serde_json::from_str(&response)
            .map_err(|e| DatabaseError::Connection(format!("Failed to parse response: {}", e)))?;

        // Check if the request was successful
        if !service_response.success {
            return Err(DatabaseError::Connection(
                service_response
                    .error
                    .unwrap_or_else(|| "Unknown connection error".to_string()),
            ));
        }

        // Get the connection ID
        let connection_id = service_response
            .connection_id
            .ok_or_else(|| DatabaseError::Connection("No connection ID returned".to_string()))?;

        Ok(Self {
            connection_id,
            db_type: match config.db_type {
                DatabaseType::Postgres => DatabaseType::Postgres,
                DatabaseType::MySql => DatabaseType::MySql,
                DatabaseType::Sqlite => DatabaseType::Sqlite,
            },
            active_transactions: Arc::new(Mutex::new(Vec::new())),
        })
    }
}

#[async_trait]
impl DatabaseConnection for ProxyDatabaseConnection {
    async fn execute(&self, query: &str, params: &[DatabaseValue]) -> DatabaseResult<u64> {
        let serialized_params =
            serialize_params(params).map_err(|e| DatabaseError::Serialization(e.to_string()))?;

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "execute".to_string(),
            params: serde_json::json!({
                "query": query,
                "params": serialized_params
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                let affected = value.as_u64().ok_or_else(|| {
                    DatabaseError::Query("Invalid affected rows count".to_string())
                })?;
                Ok(affected)
            }
            None => Err(DatabaseError::Query("No result from operation".to_string())),
        }
    }

    async fn query(
        &self,
        query: &str,
        params: &[DatabaseValue],
    ) -> DatabaseResult<Vec<Box<dyn DatabaseRow>>> {
        let serialized_params =
            serialize_params(params).map_err(|e| DatabaseError::Serialization(e.to_string()))?;

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "query".to_string(),
            params: serde_json::json!({
                "query": query,
                "params": serialized_params
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                let rows: Vec<ProxyDatabaseRow> = serde_json::from_value(value).map_err(|e| {
                    DatabaseError::Serialization(format!("Failed to deserialize rows: {}", e))
                })?;

                Ok(rows
                    .into_iter()
                    .map(|r| Box::new(r) as Box<dyn DatabaseRow>)
                    .collect())
            }
            None => Err(DatabaseError::Query("No result from operation".to_string())),
        }
    }

    async fn query_one(
        &self,
        query: &str,
        params: &[DatabaseValue],
    ) -> DatabaseResult<Option<Box<dyn DatabaseRow>>> {
        let serialized_params =
            serialize_params(params).map_err(|e| DatabaseError::Serialization(e.to_string()))?;

        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "query_one".to_string(),
            params: serde_json::json!({
                "query": query,
                "params": serialized_params
            }),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                if value.is_null() {
                    return Ok(None);
                }

                let row: ProxyDatabaseRow = serde_json::from_value(value).map_err(|e| {
                    DatabaseError::Serialization(format!("Failed to deserialize row: {}", e))
                })?;

                Ok(Some(Box::new(row) as Box<dyn DatabaseRow>))
            }
            None => Ok(None),
        }
    }

    async fn begin_transaction(&self) -> DatabaseResult<Box<dyn DatabaseTransaction>> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "begin_transaction".to_string(),
            params: serde_json::json!({}),
        };

        let result = send_operation(operation).await?;
        match result.result {
            Some(value) => {
                let transaction_id = value
                    .as_str()
                    .ok_or_else(|| {
                        DatabaseError::Transaction("Invalid transaction ID".to_string())
                    })?
                    .to_string();

                // Store the transaction ID
                let mut transactions = self.active_transactions.lock().await;
                transactions.push(transaction_id.clone());

                Ok(Box::new(ProxyDatabaseTransaction {
                    connection_id: self.connection_id.clone(),
                    transaction_id,
                }) as Box<dyn DatabaseTransaction>)
            }
            None => Err(DatabaseError::Transaction(
                "Failed to begin transaction".to_string(),
            )),
        }
    }

    fn get_database_type(&self) -> DatabaseType {
        self.db_type
    }

    async fn ping(&self) -> DatabaseResult<()> {
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "ping".to_string(),
            params: serde_json::json!({}),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(DatabaseError::Connection(
                result.error.unwrap_or_else(|| "Ping failed".to_string()),
            ))
        }
    }

    async fn close(&self) -> DatabaseResult<()> {
        // Roll back any active transactions first
        let mut transactions = self.active_transactions.lock().await;
        let transaction_ids = std::mem::take(&mut *transactions);
        drop(transactions);

        for transaction_id in transaction_ids {
            let operation = ServiceOperation {
                connection_id: self.connection_id.clone(),
                service_type: ServiceType::Database,
                operation: "transaction_rollback".to_string(),
                params: serde_json::json!({
                    "transaction_id": transaction_id,
                }),
            };

            // Just try to roll back, but ignore any errors
            let _ = send_operation(operation).await;
        }

        // Now close the connection
        let operation = ServiceOperation {
            connection_id: self.connection_id.clone(),
            service_type: ServiceType::Database,
            operation: "close".to_string(),
            params: serde_json::json!({}),
        };

        let result = send_operation(operation).await?;
        if result.success {
            Ok(())
        } else {
            Err(DatabaseError::Connection(
                result.error.unwrap_or_else(|| "Close failed".to_string()),
            ))
        }
    }
}

// Utility function to serialize database parameters
pub fn serialize_params(params: &[DatabaseValue]) -> Result<serde_json::Value, serde_json::Error> {
    let serialized_results: Vec<Result<serde_json::Value, serde_json::Error>> = params
        .iter()
        .map(|value| -> Result<serde_json::Value, serde_json::Error> {
            match value {
                DatabaseValue::Null => Ok(serde_json::Value::Null),
                DatabaseValue::Boolean(b) => Ok(serde_json::Value::Bool(*b)),
                DatabaseValue::Integer(i) => Ok(serde_json::Value::Number((*i).into())),
                DatabaseValue::Float(f) => serde_json::Number::from_f64(*f)
                    .map(serde_json::Value::Number)
                    .ok_or_else(|| {
                        serde_json::Error::custom(format!("Invalid float value: {}", f))
                    }),
                DatabaseValue::Text(s) => Ok(serde_json::Value::String(s.clone())),
                DatabaseValue::Blob(b) => Ok(serde_json::Value::String(STANDARD.encode(b))),
                DatabaseValue::Array(arr) => {
                    let values_vec_result: Result<Vec<serde_json::Value>, serde_json::Error> = arr
                        .iter()
                        .map(|v_item| match v_item {
                            DatabaseValue::Null => Ok(serde_json::Value::Null),
                            DatabaseValue::Boolean(b_inner) => {
                                Ok(serde_json::Value::Bool(*b_inner))
                            }
                            DatabaseValue::Integer(i_inner) => {
                                Ok(serde_json::Value::Number((*i_inner).into()))
                            }
                            DatabaseValue::Float(f_inner) => serde_json::Number::from_f64(*f_inner)
                                .map(serde_json::Value::Number)
                                .ok_or_else(|| {
                                    serde_json::Error::custom(format!(
                                        "Invalid float value in array: {}",
                                        f_inner
                                    ))
                                }),
                            DatabaseValue::Text(s_inner) => {
                                Ok(serde_json::Value::String(s_inner.clone()))
                            }
                            DatabaseValue::Blob(b_inner) => {
                                Ok(serde_json::Value::String(STANDARD.encode(b_inner)))
                            }
                            DatabaseValue::Array(_) => Err(serde_json::Error::custom(
                                "Nested arrays not supported for direct IPC serialization",
                            )),
                        })
                        .collect();

                    Ok(serde_json::Value::Array(values_vec_result?))
                }
            }
        })
        .collect();

    let final_serialized_values: Result<Vec<serde_json::Value>, serde_json::Error> =
        serialized_results.into_iter().collect();

    Ok(serde_json::Value::Array(final_serialized_values?))
}

// Helper function to send an operation and receive the result
async fn send_operation(operation: ServiceOperation) -> DatabaseResult<ServiceOperationResult> {
    let response = send_request(&operation)
        .await
        .map_err(|e| DatabaseError::Query(format!("Failed to send operation: {}", e)))?;

    let result: ServiceOperationResult = serde_json::from_str(&response)
        .map_err(|e| DatabaseError::Query(format!("Failed to parse response: {}", e)))?;

    if !result.success {
        let error_msg = result.error.unwrap_or_else(|| "Unknown error".to_string());
        return Err(DatabaseError::Query(error_msg));
    }

    Ok(result)
}

// Add IPC error to the DatabaseError enum
impl From<String> for DatabaseError {
    fn from(error: String) -> Self {
        DatabaseError::Connection(format!("IPC error: {}", error))
    }
}