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
// This file is @generated by wasmcloud/weld-codegen 0.4.6.
// It is not intended for manual editing.
// namespace: org.wasmcloud.interface.sqldb

#[allow(unused_imports)]
use async_trait::async_trait;
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[allow(unused_imports)]
use std::{borrow::Borrow, borrow::Cow, io::Write, string::ToString};
#[allow(unused_imports)]
use wasmbus_rpc::{
    cbor::*,
    common::{
        deserialize, message_format, serialize, Context, Message, MessageDispatch, MessageFormat,
        SendOpts, Transport,
    },
    error::{RpcError, RpcResult},
    Timestamp,
};

#[allow(dead_code)]
pub const SMITHY_VERSION: &str = "1.0";

/// Metadata about a Column in the result set
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Column {
    /// column ordinal
    #[serde(default)]
    pub ordinal: u32,
    /// Column name in the result
    #[serde(default)]
    pub name: String,
    /// column data type as reported by the database
    #[serde(rename = "dbType")]
    #[serde(default)]
    pub db_type: String,
}

// Encode Column as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_column<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &Column,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.array(3)?;
    e.u32(val.ordinal)?;
    e.str(&val.name)?;
    e.str(&val.db_type)?;
    Ok(())
}

// Decode Column from cbor input stream
#[doc(hidden)]
pub fn decode_column(d: &mut wasmbus_rpc::cbor::Decoder<'_>) -> Result<Column, RpcError> {
    let __result = {
        let mut ordinal: Option<u32> = None;
        let mut name: Option<String> = None;
        let mut db_type: Option<String> = None;

        let is_array = match d.datatype()? {
            wasmbus_rpc::cbor::Type::Array => true,
            wasmbus_rpc::cbor::Type::Map => false,
            _ => {
                return Err(RpcError::Deser(
                    "decoding struct Column, expected array or map".to_string(),
                ))
            }
        };
        if is_array {
            let len = d.fixed_array()?;
            for __i in 0..(len as usize) {
                match __i {
                    0 => ordinal = Some(d.u32()?),
                    1 => name = Some(d.str()?.to_string()),
                    2 => db_type = Some(d.str()?.to_string()),
                    _ => d.skip()?,
                }
            }
        } else {
            let len = d.fixed_map()?;
            for __i in 0..(len as usize) {
                match d.str()? {
                    "ordinal" => ordinal = Some(d.u32()?),
                    "name" => name = Some(d.str()?.to_string()),
                    "dbType" => db_type = Some(d.str()?.to_string()),
                    _ => d.skip()?,
                }
            }
        }
        Column {
            ordinal: if let Some(__x) = ordinal {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field Column.ordinal (#0)".to_string(),
                ));
            },

            name: if let Some(__x) = name {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field Column.name (#1)".to_string(),
                ));
            },

            db_type: if let Some(__x) = db_type {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field Column.db_type (#2)".to_string(),
                ));
            },
        }
    };
    Ok(__result)
}
/// List of columns in the result set returned by a Query operation
pub type Columns = Vec<Column>;

// Encode Columns as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_columns<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &Columns,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.array(val.len() as u64)?;
    for item in val.iter() {
        encode_column(e, item)?;
    }
    Ok(())
}

// Decode Columns from cbor input stream
#[doc(hidden)]
pub fn decode_columns(d: &mut wasmbus_rpc::cbor::Decoder<'_>) -> Result<Columns, RpcError> {
    let __result = {
        if let Some(n) = d.array()? {
            let mut arr: Vec<Column> = Vec::with_capacity(n as usize);
            for _ in 0..(n as usize) {
                arr.push(decode_column(d).map_err(|e| {
                    format!("decoding 'org.wasmcloud.interface.sqldb#Column': {}", e)
                })?)
            }
            arr
        } else {
            // indefinite array
            let mut arr: Vec<Column> = Vec::new();
            loop {
                match d.datatype() {
                    Err(_) => break,
                    Ok(wasmbus_rpc::cbor::Type::Break) => break,
                    Ok(_) => arr.push(decode_column(d).map_err(|e| {
                        format!("decoding 'org.wasmcloud.interface.sqldb#Column': {}", e)
                    })?),
                }
            }
            arr
        }
    };
    Ok(__result)
}
/// Result of an Execute operation
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct ExecuteResult {
    /// the number of rows affected by the query
    #[serde(rename = "rowsAffected")]
    #[serde(default)]
    pub rows_affected: u64,
    /// optional error information.
    /// If error is included in the QueryResult, other values should be ignored.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<SqlDbError>,
}

// Encode ExecuteResult as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_execute_result<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &ExecuteResult,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.array(2)?;
    e.u64(val.rows_affected)?;
    if let Some(val) = val.error.as_ref() {
        encode_sql_db_error(e, val)?;
    } else {
        e.null()?;
    }
    Ok(())
}

// Decode ExecuteResult from cbor input stream
#[doc(hidden)]
pub fn decode_execute_result(
    d: &mut wasmbus_rpc::cbor::Decoder<'_>,
) -> Result<ExecuteResult, RpcError> {
    let __result = {
        let mut rows_affected: Option<u64> = None;
        let mut error: Option<Option<SqlDbError>> = Some(None);

        let is_array = match d.datatype()? {
            wasmbus_rpc::cbor::Type::Array => true,
            wasmbus_rpc::cbor::Type::Map => false,
            _ => {
                return Err(RpcError::Deser(
                    "decoding struct ExecuteResult, expected array or map".to_string(),
                ))
            }
        };
        if is_array {
            let len = d.fixed_array()?;
            for __i in 0..(len as usize) {
                match __i {
                    0 => rows_affected = Some(d.u64()?),
                    1 => {
                        error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(decode_sql_db_error(d).map_err(|e| {
                                format!(
                                    "decoding 'org.wasmcloud.interface.sqldb#SqlDbError': {}",
                                    e
                                )
                            })?))
                        }
                    }

                    _ => d.skip()?,
                }
            }
        } else {
            let len = d.fixed_map()?;
            for __i in 0..(len as usize) {
                match d.str()? {
                    "rowsAffected" => rows_affected = Some(d.u64()?),
                    "error" => {
                        error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(decode_sql_db_error(d).map_err(|e| {
                                format!(
                                    "decoding 'org.wasmcloud.interface.sqldb#SqlDbError': {}",
                                    e
                                )
                            })?))
                        }
                    }
                    _ => d.skip()?,
                }
            }
        }
        ExecuteResult {
            rows_affected: if let Some(__x) = rows_affected {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field ExecuteResult.rows_affected (#0)".to_string(),
                ));
            },
            error: error.unwrap(),
        }
    };
    Ok(__result)
}
/// An optional list of arguments to be used in the SQL statement.
/// When a statement uses question marks '?' for placeholders,
/// the capability provider will replace the specified arguments during execution.
/// The command must have exactly as many placeholders as arguments, or the request will fail.
/// The members are CBOR encoded.
pub type Parameters = Vec<Vec<u8>>;

// Encode Parameters as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_parameters<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &Parameters,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.array(val.len() as u64)?;
    for item in val.iter() {
        e.bytes(item)?;
    }
    Ok(())
}

// Decode Parameters from cbor input stream
#[doc(hidden)]
pub fn decode_parameters(d: &mut wasmbus_rpc::cbor::Decoder<'_>) -> Result<Parameters, RpcError> {
    let __result = {
        if let Some(n) = d.array()? {
            let mut arr: Vec<Vec<u8>> = Vec::with_capacity(n as usize);
            for _ in 0..(n as usize) {
                arr.push(d.bytes()?.to_vec())
            }
            arr
        } else {
            // indefinite array
            let mut arr: Vec<Vec<u8>> = Vec::new();
            loop {
                match d.datatype() {
                    Err(_) => break,
                    Ok(wasmbus_rpc::cbor::Type::Break) => break,
                    Ok(_) => arr.push(d.bytes()?.to_vec()),
                }
            }
            arr
        }
    };
    Ok(__result)
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct PingResult {
    /// Optional error information.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<SqlDbError>,
}

// Encode PingResult as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_ping_result<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &PingResult,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.map(1)?;
    if let Some(val) = val.error.as_ref() {
        e.str("error")?;
        encode_sql_db_error(e, val)?;
    } else {
        e.null()?;
    }
    Ok(())
}

// Decode PingResult from cbor input stream
#[doc(hidden)]
pub fn decode_ping_result(d: &mut wasmbus_rpc::cbor::Decoder<'_>) -> Result<PingResult, RpcError> {
    let __result = {
        let mut error: Option<Option<SqlDbError>> = Some(None);

        let is_array = match d.datatype()? {
            wasmbus_rpc::cbor::Type::Array => true,
            wasmbus_rpc::cbor::Type::Map => false,
            _ => {
                return Err(RpcError::Deser(
                    "decoding struct PingResult, expected array or map".to_string(),
                ))
            }
        };
        if is_array {
            let len = d.fixed_array()?;
            for __i in 0..(len as usize) {
                match __i {
                    0 => {
                        error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(decode_sql_db_error(d).map_err(|e| {
                                format!(
                                    "decoding 'org.wasmcloud.interface.sqldb#SqlDbError': {}",
                                    e
                                )
                            })?))
                        }
                    }

                    _ => d.skip()?,
                }
            }
        } else {
            let len = d.fixed_map()?;
            for __i in 0..(len as usize) {
                match d.str()? {
                    "error" => {
                        error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(decode_sql_db_error(d).map_err(|e| {
                                format!(
                                    "decoding 'org.wasmcloud.interface.sqldb#SqlDbError': {}",
                                    e
                                )
                            })?))
                        }
                    }
                    _ => d.skip()?,
                }
            }
        }
        PingResult {
            error: error.unwrap(),
        }
    };
    Ok(__result)
}
/// Result of a query
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct QueryResult {
    /// number of rows returned
    #[serde(rename = "numRows")]
    #[serde(default)]
    pub num_rows: u64,
    /// description of columns returned
    pub columns: Columns,
    /// result rows, encoded in CBOR as
    /// an array (rows) of arrays (fields per row)
    #[serde(with = "serde_bytes")]
    #[serde(default)]
    pub rows: Vec<u8>,
    /// optional error information.
    /// If error is included in the QueryResult, other values should be ignored.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<SqlDbError>,
}

// Encode QueryResult as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_query_result<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &QueryResult,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.array(4)?;
    e.u64(val.num_rows)?;
    encode_columns(e, &val.columns)?;
    e.bytes(&val.rows)?;
    if let Some(val) = val.error.as_ref() {
        encode_sql_db_error(e, val)?;
    } else {
        e.null()?;
    }
    Ok(())
}

// Decode QueryResult from cbor input stream
#[doc(hidden)]
pub fn decode_query_result(
    d: &mut wasmbus_rpc::cbor::Decoder<'_>,
) -> Result<QueryResult, RpcError> {
    let __result = {
        let mut num_rows: Option<u64> = None;
        let mut columns: Option<Columns> = None;
        let mut rows: Option<Vec<u8>> = None;
        let mut error: Option<Option<SqlDbError>> = Some(None);

        let is_array = match d.datatype()? {
            wasmbus_rpc::cbor::Type::Array => true,
            wasmbus_rpc::cbor::Type::Map => false,
            _ => {
                return Err(RpcError::Deser(
                    "decoding struct QueryResult, expected array or map".to_string(),
                ))
            }
        };
        if is_array {
            let len = d.fixed_array()?;
            for __i in 0..(len as usize) {
                match __i {
                    0 => num_rows = Some(d.u64()?),
                    1 => {
                        columns = Some(decode_columns(d).map_err(|e| {
                            format!("decoding 'org.wasmcloud.interface.sqldb#Columns': {}", e)
                        })?)
                    }
                    2 => rows = Some(d.bytes()?.to_vec()),
                    3 => {
                        error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(decode_sql_db_error(d).map_err(|e| {
                                format!(
                                    "decoding 'org.wasmcloud.interface.sqldb#SqlDbError': {}",
                                    e
                                )
                            })?))
                        }
                    }

                    _ => d.skip()?,
                }
            }
        } else {
            let len = d.fixed_map()?;
            for __i in 0..(len as usize) {
                match d.str()? {
                    "numRows" => num_rows = Some(d.u64()?),
                    "columns" => {
                        columns = Some(decode_columns(d).map_err(|e| {
                            format!("decoding 'org.wasmcloud.interface.sqldb#Columns': {}", e)
                        })?)
                    }
                    "rows" => rows = Some(d.bytes()?.to_vec()),
                    "error" => {
                        error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(decode_sql_db_error(d).map_err(|e| {
                                format!(
                                    "decoding 'org.wasmcloud.interface.sqldb#SqlDbError': {}",
                                    e
                                )
                            })?))
                        }
                    }
                    _ => d.skip()?,
                }
            }
        }
        QueryResult {
            num_rows: if let Some(__x) = num_rows {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field QueryResult.num_rows (#0)".to_string(),
                ));
            },

            columns: if let Some(__x) = columns {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field QueryResult.columns (#1)".to_string(),
                ));
            },

            rows: if let Some(__x) = rows {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field QueryResult.rows (#2)".to_string(),
                ));
            },
            error: error.unwrap(),
        }
    };
    Ok(__result)
}
/// Detailed error information from the previous operation
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct SqlDbError {
    /// Type of error.
    /// The list of enum variants for this field may be expanded in the future
    /// to provide finer-granularity failure information
    #[serde(default)]
    pub code: String,
    /// error message
    #[serde(default)]
    pub message: String,
}

// Encode SqlDbError as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_sql_db_error<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &SqlDbError,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.array(2)?;
    e.str(&val.code)?;
    e.str(&val.message)?;
    Ok(())
}

// Decode SqlDbError from cbor input stream
#[doc(hidden)]
pub fn decode_sql_db_error(d: &mut wasmbus_rpc::cbor::Decoder<'_>) -> Result<SqlDbError, RpcError> {
    let __result = {
        let mut code: Option<String> = None;
        let mut message: Option<String> = None;

        let is_array = match d.datatype()? {
            wasmbus_rpc::cbor::Type::Array => true,
            wasmbus_rpc::cbor::Type::Map => false,
            _ => {
                return Err(RpcError::Deser(
                    "decoding struct SqlDbError, expected array or map".to_string(),
                ))
            }
        };
        if is_array {
            let len = d.fixed_array()?;
            for __i in 0..(len as usize) {
                match __i {
                    0 => code = Some(d.str()?.to_string()),
                    1 => message = Some(d.str()?.to_string()),
                    _ => d.skip()?,
                }
            }
        } else {
            let len = d.fixed_map()?;
            for __i in 0..(len as usize) {
                match d.str()? {
                    "code" => code = Some(d.str()?.to_string()),
                    "message" => message = Some(d.str()?.to_string()),
                    _ => d.skip()?,
                }
            }
        }
        SqlDbError {
            code: if let Some(__x) = code {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field SqlDbError.code (#0)".to_string(),
                ));
            },

            message: if let Some(__x) = message {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field SqlDbError.message (#1)".to_string(),
                ));
            },
        }
    };
    Ok(__result)
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Statement {
    /// Optional database in which the statement must be executed.
    /// The value in this field is case-sensitive.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub database: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Parameters>,
    /// A sql query or statement that is a non-empty string containing
    /// in the syntax of the back-end database.
    #[serde(default)]
    pub sql: String,
}

// Encode Statement as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_statement<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &Statement,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.map(3)?;
    if let Some(val) = val.database.as_ref() {
        e.str("database")?;
        e.str(val)?;
    } else {
        e.null()?;
    }
    if let Some(val) = val.parameters.as_ref() {
        e.str("parameters")?;
        encode_parameters(e, val)?;
    } else {
        e.null()?;
    }
    e.str("sql")?;
    e.str(&val.sql)?;
    Ok(())
}

// Decode Statement from cbor input stream
#[doc(hidden)]
pub fn decode_statement(d: &mut wasmbus_rpc::cbor::Decoder<'_>) -> Result<Statement, RpcError> {
    let __result = {
        let mut database: Option<Option<String>> = Some(None);
        let mut parameters: Option<Option<Parameters>> = Some(None);
        let mut sql: Option<String> = None;

        let is_array = match d.datatype()? {
            wasmbus_rpc::cbor::Type::Array => true,
            wasmbus_rpc::cbor::Type::Map => false,
            _ => {
                return Err(RpcError::Deser(
                    "decoding struct Statement, expected array or map".to_string(),
                ))
            }
        };
        if is_array {
            let len = d.fixed_array()?;
            for __i in 0..(len as usize) {
                match __i {
                    0 => {
                        database = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(d.str()?.to_string()))
                        }
                    }
                    1 => {
                        parameters = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(decode_parameters(d).map_err(|e| {
                                format!(
                                    "decoding 'org.wasmcloud.interface.sqldb#Parameters': {}",
                                    e
                                )
                            })?))
                        }
                    }
                    2 => sql = Some(d.str()?.to_string()),
                    _ => d.skip()?,
                }
            }
        } else {
            let len = d.fixed_map()?;
            for __i in 0..(len as usize) {
                match d.str()? {
                    "database" => {
                        database = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(d.str()?.to_string()))
                        }
                    }
                    "parameters" => {
                        parameters = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(decode_parameters(d).map_err(|e| {
                                format!(
                                    "decoding 'org.wasmcloud.interface.sqldb#Parameters': {}",
                                    e
                                )
                            })?))
                        }
                    }
                    "sql" => sql = Some(d.str()?.to_string()),
                    _ => d.skip()?,
                }
            }
        }
        Statement {
            database: database.unwrap(),
            parameters: parameters.unwrap(),

            sql: if let Some(__x) = sql {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field Statement.sql (#2)".to_string(),
                ));
            },
        }
    };
    Ok(__result)
}
/// SqlDb - SQL Database connections
/// To use this capability, the actor must be linked
/// with the capability contract "wasmcloud:sqldb"
/// wasmbus.contractId: wasmcloud:sqldb
/// wasmbus.providerReceive
#[async_trait]
pub trait SqlDb {
    /// returns the capability contract id for this interface
    fn contract_id() -> &'static str {
        "wasmcloud:sqldb"
    }
    /// Execute an sql statement
    async fn execute(&self, ctx: &Context, arg: &Statement) -> RpcResult<ExecuteResult>;
    /// Perform select query on database, returning all result rows
    async fn query(&self, ctx: &Context, arg: &Statement) -> RpcResult<QueryResult>;
}

/// SqlDbReceiver receives messages defined in the SqlDb service trait
/// SqlDb - SQL Database connections
/// To use this capability, the actor must be linked
/// with the capability contract "wasmcloud:sqldb"
#[doc(hidden)]
#[async_trait]
pub trait SqlDbReceiver: MessageDispatch + SqlDb {
    async fn dispatch<'disp__, 'ctx__, 'msg__>(
        &'disp__ self,
        ctx: &'ctx__ Context,
        message: &Message<'msg__>,
    ) -> Result<Message<'msg__>, RpcError> {
        match message.method {
            "Execute" => {
                let value: Statement = wasmbus_rpc::common::deserialize(&message.arg)
                    .map_err(|e| RpcError::Deser(format!("'Statement': {}", e)))?;

                let resp = SqlDb::execute(self, ctx, &value).await?;
                let buf = wasmbus_rpc::common::serialize(&resp)?;

                Ok(Message {
                    method: "SqlDb.Execute",
                    arg: Cow::Owned(buf),
                })
            }
            "Query" => {
                let value: Statement = wasmbus_rpc::common::deserialize(&message.arg)
                    .map_err(|e| RpcError::Deser(format!("'Statement': {}", e)))?;

                let resp = SqlDb::query(self, ctx, &value).await?;
                let buf = wasmbus_rpc::common::serialize(&resp)?;

                Ok(Message {
                    method: "SqlDb.Query",
                    arg: Cow::Owned(buf),
                })
            }
            _ => Err(RpcError::MethodNotHandled(format!(
                "SqlDb::{}",
                message.method
            ))),
        }
    }
}

/// SqlDbSender sends messages to a SqlDb service
/// SqlDb - SQL Database connections
/// To use this capability, the actor must be linked
/// with the capability contract "wasmcloud:sqldb"
/// client for sending SqlDb messages
#[derive(Debug)]
pub struct SqlDbSender<T: Transport> {
    transport: T,
}

impl<T: Transport> SqlDbSender<T> {
    /// Constructs a SqlDbSender with the specified transport
    pub fn via(transport: T) -> Self {
        Self { transport }
    }

    pub fn set_timeout(&self, interval: std::time::Duration) {
        self.transport.set_timeout(interval);
    }
}

#[cfg(target_arch = "wasm32")]
impl SqlDbSender<wasmbus_rpc::actor::prelude::WasmHost> {
    /// Constructs a client for sending to a SqlDb provider
    /// implementing the 'wasmcloud:sqldb' capability contract, with the "default" link
    pub fn new() -> Self {
        let transport =
            wasmbus_rpc::actor::prelude::WasmHost::to_provider("wasmcloud:sqldb", "default")
                .unwrap();
        Self { transport }
    }

    /// Constructs a client for sending to a SqlDb provider
    /// implementing the 'wasmcloud:sqldb' capability contract, with the specified link name
    pub fn new_with_link(link_name: &str) -> wasmbus_rpc::error::RpcResult<Self> {
        let transport =
            wasmbus_rpc::actor::prelude::WasmHost::to_provider("wasmcloud:sqldb", link_name)?;
        Ok(Self { transport })
    }
}
#[async_trait]
impl<T: Transport + std::marker::Sync + std::marker::Send> SqlDb for SqlDbSender<T> {
    #[allow(unused)]
    /// Execute an sql statement
    async fn execute(&self, ctx: &Context, arg: &Statement) -> RpcResult<ExecuteResult> {
        let buf = wasmbus_rpc::common::serialize(arg)?;

        let resp = self
            .transport
            .send(
                ctx,
                Message {
                    method: "SqlDb.Execute",
                    arg: Cow::Borrowed(&buf),
                },
                None,
            )
            .await?;

        let value: ExecuteResult = wasmbus_rpc::common::deserialize(&resp)
            .map_err(|e| RpcError::Deser(format!("'{}': ExecuteResult", e)))?;
        Ok(value)
    }
    #[allow(unused)]
    /// Perform select query on database, returning all result rows
    async fn query(&self, ctx: &Context, arg: &Statement) -> RpcResult<QueryResult> {
        let buf = wasmbus_rpc::common::serialize(arg)?;

        let resp = self
            .transport
            .send(
                ctx,
                Message {
                    method: "SqlDb.Query",
                    arg: Cow::Borrowed(&buf),
                },
                None,
            )
            .await?;

        let value: QueryResult = wasmbus_rpc::common::deserialize(&resp)
            .map_err(|e| RpcError::Deser(format!("'{}': QueryResult", e)))?;
        Ok(value)
    }
}