edgedb-sdk 0.1.0

EdgeDB SDK for WebAssembly workers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
//! Client to the EdgeDB
//!
//! This is a major way to contact the database. Database credentials always
//! come preconfigured to connect to the specific database that this WebAssembly
//! file was run from.
use std::collections::HashMap;
use std::sync::Arc;

use bytes::Bytes;

pub use edgedb_errors::{self as errors, Error, ErrorKind};
pub use edgedb_protocol::QueryResult;
pub use edgedb_protocol::common::Cardinality;
pub use edgedb_protocol::features::ProtocolVersion;
pub use edgedb_protocol::query_arg::{QueryArgs, Encoder};
pub use edgedb_protocol::server_message::CommandDataDescription;
use edgedb_errors::{ClientError, ProtocolEncodingError, NoResultExpected};
use edgedb_errors::{NoDataError};
use edgedb_protocol::model::Json;

use bytes::BytesMut;

#[allow(dead_code)]
#[allow(unused_parens)]
// wit_bindgen_rust::import!("../wit/edgedb-client-v1.wit");
mod edgedb_client_v1 {
  #[repr(u8)]
  #[derive(Clone, Copy, PartialEq, Eq)]
  pub enum IoFormat{
    Binary,
    Json,
    JsonElements,
  }
  impl std::fmt::Debug for IoFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      match self {
        IoFormat::Binary => {
          f.debug_tuple("IoFormat::Binary").finish()
        }
        IoFormat::Json => {
          f.debug_tuple("IoFormat::Json").finish()
        }
        IoFormat::JsonElements => {
          f.debug_tuple("IoFormat::JsonElements").finish()
        }
      }
    }
  }
  #[repr(u8)]
  #[derive(Clone, Copy, PartialEq, Eq)]
  pub enum Cardinality{
    NoResult,
    AtMostOne,
    One,
    Many,
    AtLeastOne,
  }
  impl std::fmt::Debug for Cardinality {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      match self {
        Cardinality::NoResult => {
          f.debug_tuple("Cardinality::NoResult").finish()
        }
        Cardinality::AtMostOne => {
          f.debug_tuple("Cardinality::AtMostOne").finish()
        }
        Cardinality::One => {
          f.debug_tuple("Cardinality::One").finish()
        }
        Cardinality::Many => {
          f.debug_tuple("Cardinality::Many").finish()
        }
        Cardinality::AtLeastOne => {
          f.debug_tuple("Cardinality::AtLeastOne").finish()
        }
      }
    }
  }
  #[derive(Clone)]
  pub struct Error {
    pub code: u32,
    pub messages: Vec<String>,
    pub error: Option<String>,
    pub headers: Vec<(u16,Vec<u8>,)>,
  }
  impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      f.debug_struct("Error").field("code", &self.code).field("messages", &self.messages).field("error", &self.error).field("headers", &self.headers).finish()}
  }
  bitflags::bitflags! {
    pub struct Capabilities: u8 {
      const MODIFICATIONS = 1 << 0;
      const SESSION_CONFIG = 1 << 1;
      const TRANSACTION = 1 << 2;
      const DDL = 1 << 3;
      const PERSISTENT_CONFIG = 1 << 4;
    }
  }
  impl Capabilities {
        /// Convert from a raw integer, preserving any unknown bits. See
        /// <https://github.com/bitflags/bitflags/issues/263#issuecomment-957088321>
        pub fn from_bits_preserve(bits: u8) -> Self {
              Self { bits }
        }
  }
  impl crate::bindgen::AsI32 for Capabilities {
        #[inline]    fn as_i32(self) -> i32 {
              self.bits() as i32
        }}
  #[repr(C)]
  #[derive(Copy, Clone)]
  pub struct CompilationFlags {
    pub implicit_limit: Option<u64>,
    pub implicit_typenames: bool,
    pub implicit_typeids: bool,
    pub allow_capabilities: Capabilities,
    pub explicit_objectids: bool,
    pub io_format: IoFormat,
    pub expected_cardinality: Cardinality,
  }
  impl std::fmt::Debug for CompilationFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      f.debug_struct("CompilationFlags").field("implicit-limit", &self.implicit_limit).field("implicit-typenames", &self.implicit_typenames).field("implicit-typeids", &self.implicit_typeids).field("allow-capabilities", &self.allow_capabilities).field("explicit-objectids", &self.explicit_objectids).field("io-format", &self.io_format).field("expected-cardinality", &self.expected_cardinality).finish()}
  }
  #[derive(Clone)]
  pub struct PrepareComplete {
    pub capabilities: Capabilities,
    pub cardinality: Cardinality,
    pub input_typedesc_id: String,
    pub output_typedesc_id: String,
  }
  impl std::fmt::Debug for PrepareComplete {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      f.debug_struct("PrepareComplete").field("capabilities", &self.capabilities).field("cardinality", &self.cardinality).field("input-typedesc-id", &self.input_typedesc_id).field("output-typedesc-id", &self.output_typedesc_id).finish()}
  }
  #[derive(Clone)]
  pub struct DataDescription {
    pub proto: (u16,u16,),
    pub result_cardinality: Cardinality,
    pub input_typedesc_id: String,
    pub input_typedesc: Vec<u8>,
    pub output_typedesc_id: String,
    pub output_typedesc: Vec<u8>,
  }
  impl std::fmt::Debug for DataDescription {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      f.debug_struct("DataDescription").field("proto", &self.proto).field("result-cardinality", &self.result_cardinality).field("input-typedesc-id", &self.input_typedesc_id).field("input-typedesc", &self.input_typedesc).field("output-typedesc-id", &self.output_typedesc_id).field("output-typedesc", &self.output_typedesc).finish()}
  }
  #[derive(Clone)]
  pub struct Data {
    pub chunks: Vec<Vec<u8>>,
  }
  impl std::fmt::Debug for Data {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      f.debug_struct("Data").field("chunks", &self.chunks).finish()}
  }
  #[derive(Debug)]
  #[repr(transparent)]
  pub struct Query(i32);
  impl Query{
    pub unsafe fn from_raw(raw: i32) -> Self {
      Self(raw)
    }
    
    pub fn into_raw(self) -> i32 {
      let ret = self.0;
      core::mem::forget(self);
      return ret;
    }
    
    pub fn as_raw(&self) -> i32 {
      self.0
    }
  }
  impl Drop for Query{
    fn drop(&mut self) {
      #[link(wasm_import_module = "canonical_abi")]
      extern "C" {
        #[link_name = "resource_drop_query"]
        fn close(fd: i32);
      }
      unsafe {
        close(self.0);
      }
    }
  }
  impl Clone for Query{
    fn clone(&self) -> Self {
      #[link(wasm_import_module = "canonical_abi")]
      extern "C" {
        #[link_name = "resource_clone_query"]
        fn clone(val: i32) -> i32;
      }
      unsafe {
        Self(clone(self.0))
      }
    }
  }
  #[derive(Debug)]
  #[repr(transparent)]
  pub struct Client(i32);
  impl Client{
    pub unsafe fn from_raw(raw: i32) -> Self {
      Self(raw)
    }
    
    pub fn into_raw(self) -> i32 {
      let ret = self.0;
      core::mem::forget(self);
      return ret;
    }
    
    pub fn as_raw(&self) -> i32 {
      self.0
    }
  }
  impl Drop for Client{
    fn drop(&mut self) {
      #[link(wasm_import_module = "canonical_abi")]
      extern "C" {
        #[link_name = "resource_drop_client"]
        fn close(fd: i32);
      }
      unsafe {
        close(self.0);
      }
    }
  }
  impl Clone for Client{
    fn clone(&self) -> Self {
      #[link(wasm_import_module = "canonical_abi")]
      extern "C" {
        #[link_name = "resource_clone_client"]
        fn clone(val: i32) -> i32;
      }
      unsafe {
        Self(clone(self.0))
      }
    }
  }
  #[derive(Debug)]
  #[repr(transparent)]
  pub struct Transaction(i32);
  impl Transaction{
    pub unsafe fn from_raw(raw: i32) -> Self {
      Self(raw)
    }
    
    pub fn into_raw(self) -> i32 {
      let ret = self.0;
      core::mem::forget(self);
      return ret;
    }
    
    pub fn as_raw(&self) -> i32 {
      self.0
    }
  }
  impl Drop for Transaction{
    fn drop(&mut self) {
      #[link(wasm_import_module = "canonical_abi")]
      extern "C" {
        #[link_name = "resource_drop_transaction"]
        fn close(fd: i32);
      }
      unsafe {
        close(self.0);
      }
    }
  }
  impl Clone for Transaction{
    fn clone(&self) -> Self {
      #[link(wasm_import_module = "canonical_abi")]
      extern "C" {
        #[link_name = "resource_clone_transaction"]
        fn clone(val: i32) -> i32;
      }
      unsafe {
        Self(clone(self.0))
      }
    }
  }
  impl Query {
    pub fn describe_data(&self,) -> Result<DataDescription,Error>{
      unsafe {
        let ptr0 = RET_AREA.as_mut_ptr() as i32;
        #[link(wasm_import_module = "edgedb-client-v1")]
        extern "C" {
          #[cfg_attr(target_arch = "wasm32", link_name = "query::describe-data")]
          #[cfg_attr(not(target_arch = "wasm32"), link_name = "edgedb-client-v1_query::describe-data")]
          fn wit_import(_: i32, _: i32, );
        }
        wit_import(self.0, ptr0);
        match *((ptr0 + 0) as *const i32) {
          0 => Ok({
            let len1 = *((ptr0 + 40) as *const i32) as usize;
            let len2 = *((ptr0 + 56) as *const i32) as usize;
            let len3 = *((ptr0 + 72) as *const i32) as usize;
            let len4 = *((ptr0 + 88) as *const i32) as usize;
            
            DataDescription{proto:(*((ptr0 + 8) as *const i32) as u16, *((ptr0 + 16) as *const i32) as u16), result_cardinality:match *((ptr0 + 24) as *const i32) {
              0 => Cardinality::NoResult,
              1 => Cardinality::AtMostOne,
              2 => Cardinality::One,
              3 => Cardinality::Many,
              4 => Cardinality::AtLeastOne,
              _ => panic!("invalid enum discriminant"),
            }, input_typedesc_id:String::from_utf8(Vec::from_raw_parts(*((ptr0 + 32) as *const i32) as *mut _, len1, len1)).unwrap(), input_typedesc:Vec::from_raw_parts(*((ptr0 + 48) as *const i32) as *mut _, len2, len2), output_typedesc_id:String::from_utf8(Vec::from_raw_parts(*((ptr0 + 64) as *const i32) as *mut _, len3, len3)).unwrap(), output_typedesc:Vec::from_raw_parts(*((ptr0 + 80) as *const i32) as *mut _, len4, len4), }
          }),
          1 => Err({
            let base6 = *((ptr0 + 16) as *const i32);
            let len6 = *((ptr0 + 24) as *const i32);
            let mut result6 = Vec::with_capacity(len6 as usize);
            for i in 0..len6 {
              let base = base6 + i *8;
              result6.push({
                let len5 = *((base + 4) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((base + 0) as *const i32) as *mut _, len5, len5)).unwrap()
              });
            }
            std::alloc::dealloc(
            base6 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len6 as usize) * 8,
            4,
            ),
            );
            let base9 = *((ptr0 + 56) as *const i32);
            let len9 = *((ptr0 + 64) as *const i32);
            let mut result9 = Vec::with_capacity(len9 as usize);
            for i in 0..len9 {
              let base = base9 + i *12;
              result9.push({
                let len8 = *((base + 8) as *const i32) as usize;
                
                (i32::from(*((base + 0) as *const u16)) as u16, Vec::from_raw_parts(*((base + 4) as *const i32) as *mut _, len8, len8))
              });
            }
            std::alloc::dealloc(
            base9 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len9 as usize) * 12,
            4,
            ),
            );
            
            Error{code:*((ptr0 + 8) as *const i32) as u32, messages:result6, error:match *((ptr0 + 32) as *const i32) {
              0 => None,
              1 => Some({
                let len7 = *((ptr0 + 48) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((ptr0 + 40) as *const i32) as *mut _, len7, len7)).unwrap()
              }),
              _ => panic!("invalid enum discriminant"),
            }, headers:result9, }
          }),
          _ => panic!("invalid enum discriminant"),
        }
      }
    }
  }
  impl Query {
    pub fn execute(&self,arguments: &[u8],) -> Result<Data,Error>{
      unsafe {
        let vec0 = arguments;
        let ptr0 = vec0.as_ptr() as i32;
        let len0 = vec0.len() as i32;
        let ptr1 = RET_AREA.as_mut_ptr() as i32;
        #[link(wasm_import_module = "edgedb-client-v1")]
        extern "C" {
          #[cfg_attr(target_arch = "wasm32", link_name = "query::execute")]
          #[cfg_attr(not(target_arch = "wasm32"), link_name = "edgedb-client-v1_query::execute")]
          fn wit_import(_: i32, _: i32, _: i32, _: i32, );
        }
        wit_import(self.0, ptr0, len0, ptr1);
        match *((ptr1 + 0) as *const i32) {
          0 => Ok({
            let base3 = *((ptr1 + 8) as *const i32);
            let len3 = *((ptr1 + 16) as *const i32);
            let mut result3 = Vec::with_capacity(len3 as usize);
            for i in 0..len3 {
              let base = base3 + i *8;
              result3.push({
                let len2 = *((base + 4) as *const i32) as usize;
                
                Vec::from_raw_parts(*((base + 0) as *const i32) as *mut _, len2, len2)
              });
            }
            std::alloc::dealloc(
            base3 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len3 as usize) * 8,
            4,
            ),
            );
            
            Data{chunks:result3, }
          }),
          1 => Err({
            let base5 = *((ptr1 + 16) as *const i32);
            let len5 = *((ptr1 + 24) as *const i32);
            let mut result5 = Vec::with_capacity(len5 as usize);
            for i in 0..len5 {
              let base = base5 + i *8;
              result5.push({
                let len4 = *((base + 4) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((base + 0) as *const i32) as *mut _, len4, len4)).unwrap()
              });
            }
            std::alloc::dealloc(
            base5 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len5 as usize) * 8,
            4,
            ),
            );
            let base8 = *((ptr1 + 56) as *const i32);
            let len8 = *((ptr1 + 64) as *const i32);
            let mut result8 = Vec::with_capacity(len8 as usize);
            for i in 0..len8 {
              let base = base8 + i *12;
              result8.push({
                let len7 = *((base + 8) as *const i32) as usize;
                
                (i32::from(*((base + 0) as *const u16)) as u16, Vec::from_raw_parts(*((base + 4) as *const i32) as *mut _, len7, len7))
              });
            }
            std::alloc::dealloc(
            base8 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len8 as usize) * 12,
            4,
            ),
            );
            
            Error{code:*((ptr1 + 8) as *const i32) as u32, messages:result5, error:match *((ptr1 + 32) as *const i32) {
              0 => None,
              1 => Some({
                let len6 = *((ptr1 + 48) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((ptr1 + 40) as *const i32) as *mut _, len6, len6)).unwrap()
              }),
              _ => panic!("invalid enum discriminant"),
            }, headers:result8, }
          }),
          _ => panic!("invalid enum discriminant"),
        }
      }
    }
  }
  impl Client {
    pub fn connect() -> Client{
      unsafe {
        #[link(wasm_import_module = "edgedb-client-v1")]
        extern "C" {
          #[cfg_attr(target_arch = "wasm32", link_name = "client::connect")]
          #[cfg_attr(not(target_arch = "wasm32"), link_name = "edgedb-client-v1_client::connect")]
          fn wit_import() -> i32;
        }
        let ret = wit_import();
        Client(ret)
      }
    }
  }
  impl Client {
    pub fn transaction(&self,) -> Result<Transaction,Error>{
      unsafe {
        let ptr0 = RET_AREA.as_mut_ptr() as i32;
        #[link(wasm_import_module = "edgedb-client-v1")]
        extern "C" {
          #[cfg_attr(target_arch = "wasm32", link_name = "client::transaction")]
          #[cfg_attr(not(target_arch = "wasm32"), link_name = "edgedb-client-v1_client::transaction")]
          fn wit_import(_: i32, _: i32, );
        }
        wit_import(self.0, ptr0);
        match *((ptr0 + 0) as *const i32) {
          0 => Ok(Transaction(*((ptr0 + 8) as *const i32))),
          1 => Err({
            let base2 = *((ptr0 + 16) as *const i32);
            let len2 = *((ptr0 + 24) as *const i32);
            let mut result2 = Vec::with_capacity(len2 as usize);
            for i in 0..len2 {
              let base = base2 + i *8;
              result2.push({
                let len1 = *((base + 4) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((base + 0) as *const i32) as *mut _, len1, len1)).unwrap()
              });
            }
            std::alloc::dealloc(
            base2 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len2 as usize) * 8,
            4,
            ),
            );
            let base5 = *((ptr0 + 56) as *const i32);
            let len5 = *((ptr0 + 64) as *const i32);
            let mut result5 = Vec::with_capacity(len5 as usize);
            for i in 0..len5 {
              let base = base5 + i *12;
              result5.push({
                let len4 = *((base + 8) as *const i32) as usize;
                
                (i32::from(*((base + 0) as *const u16)) as u16, Vec::from_raw_parts(*((base + 4) as *const i32) as *mut _, len4, len4))
              });
            }
            std::alloc::dealloc(
            base5 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len5 as usize) * 12,
            4,
            ),
            );
            
            Error{code:*((ptr0 + 8) as *const i32) as u32, messages:result2, error:match *((ptr0 + 32) as *const i32) {
              0 => None,
              1 => Some({
                let len3 = *((ptr0 + 48) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((ptr0 + 40) as *const i32) as *mut _, len3, len3)).unwrap()
              }),
              _ => panic!("invalid enum discriminant"),
            }, headers:result5, }
          }),
          _ => panic!("invalid enum discriminant"),
        }
      }
    }
  }
  impl Client {
    pub fn prepare(&self,compilation_flags: CompilationFlags,query: & str,) -> Result<(Query,PrepareComplete,),Error>{
      unsafe {
        let CompilationFlags{ implicit_limit:implicit_limit0, implicit_typenames:implicit_typenames0, implicit_typeids:implicit_typeids0, allow_capabilities:allow_capabilities0, explicit_objectids:explicit_objectids0, io_format:io_format0, expected_cardinality:expected_cardinality0, } = compilation_flags;
        let (result1_0,result1_1,) = match implicit_limit0{
          None => { (0i32, 0i64)}
          Some(e) => { (1i32, crate::bindgen::as_i64(e))}
        };
        let flags2 = allow_capabilities0;
        let vec3 = query;
        let ptr3 = vec3.as_ptr() as i32;
        let len3 = vec3.len() as i32;
        let ptr4 = RET_AREA.as_mut_ptr() as i32;
        #[link(wasm_import_module = "edgedb-client-v1")]
        extern "C" {
          #[cfg_attr(target_arch = "wasm32", link_name = "client::prepare")]
          #[cfg_attr(not(target_arch = "wasm32"), link_name = "edgedb-client-v1_client::prepare")]
          fn wit_import(_: i32, _: i32, _: i64, _: i32, _: i32, _: i32, _: i32, _: i32, _: i32, _: i32, _: i32, _: i32, );
        }
        wit_import(self.0, result1_0, result1_1, match implicit_typenames0 { true => 1, false => 0 }, match implicit_typeids0 { true => 1, false => 0 }, (flags2.bits() >> 0) as i32, match explicit_objectids0 { true => 1, false => 0 }, io_format0 as i32, expected_cardinality0 as i32, ptr3, len3, ptr4);
        match *((ptr4 + 0) as *const i32) {
          0 => Ok({
            let len5 = *((ptr4 + 40) as *const i32) as usize;
            let len6 = *((ptr4 + 56) as *const i32) as usize;
            
            (Query(*((ptr4 + 8) as *const i32)), PrepareComplete{capabilities:Capabilities::empty() | Capabilities::from_bits_preserve(((*((ptr4 + 16) as *const i32) as u32) << 0) as _), cardinality:match *((ptr4 + 24) as *const i32) {
              0 => Cardinality::NoResult,
              1 => Cardinality::AtMostOne,
              2 => Cardinality::One,
              3 => Cardinality::Many,
              4 => Cardinality::AtLeastOne,
              _ => panic!("invalid enum discriminant"),
            }, input_typedesc_id:String::from_utf8(Vec::from_raw_parts(*((ptr4 + 32) as *const i32) as *mut _, len5, len5)).unwrap(), output_typedesc_id:String::from_utf8(Vec::from_raw_parts(*((ptr4 + 48) as *const i32) as *mut _, len6, len6)).unwrap(), })
          }),
          1 => Err({
            let base8 = *((ptr4 + 16) as *const i32);
            let len8 = *((ptr4 + 24) as *const i32);
            let mut result8 = Vec::with_capacity(len8 as usize);
            for i in 0..len8 {
              let base = base8 + i *8;
              result8.push({
                let len7 = *((base + 4) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((base + 0) as *const i32) as *mut _, len7, len7)).unwrap()
              });
            }
            std::alloc::dealloc(
            base8 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len8 as usize) * 8,
            4,
            ),
            );
            let base11 = *((ptr4 + 56) as *const i32);
            let len11 = *((ptr4 + 64) as *const i32);
            let mut result11 = Vec::with_capacity(len11 as usize);
            for i in 0..len11 {
              let base = base11 + i *12;
              result11.push({
                let len10 = *((base + 8) as *const i32) as usize;
                
                (i32::from(*((base + 0) as *const u16)) as u16, Vec::from_raw_parts(*((base + 4) as *const i32) as *mut _, len10, len10))
              });
            }
            std::alloc::dealloc(
            base11 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len11 as usize) * 12,
            4,
            ),
            );
            
            Error{code:*((ptr4 + 8) as *const i32) as u32, messages:result8, error:match *((ptr4 + 32) as *const i32) {
              0 => None,
              1 => Some({
                let len9 = *((ptr4 + 48) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((ptr4 + 40) as *const i32) as *mut _, len9, len9)).unwrap()
              }),
              _ => panic!("invalid enum discriminant"),
            }, headers:result11, }
          }),
          _ => panic!("invalid enum discriminant"),
        }
      }
    }
  }
  impl Transaction {
    pub fn prepare(&self,compilation_flags: CompilationFlags,query: & str,) -> Result<(Query,PrepareComplete,),Error>{
      unsafe {
        let CompilationFlags{ implicit_limit:implicit_limit0, implicit_typenames:implicit_typenames0, implicit_typeids:implicit_typeids0, allow_capabilities:allow_capabilities0, explicit_objectids:explicit_objectids0, io_format:io_format0, expected_cardinality:expected_cardinality0, } = compilation_flags;
        let (result1_0,result1_1,) = match implicit_limit0{
          None => { (0i32, 0i64)}
          Some(e) => { (1i32, crate::bindgen::as_i64(e))}
        };
        let flags2 = allow_capabilities0;
        let vec3 = query;
        let ptr3 = vec3.as_ptr() as i32;
        let len3 = vec3.len() as i32;
        let ptr4 = RET_AREA.as_mut_ptr() as i32;
        #[link(wasm_import_module = "edgedb-client-v1")]
        extern "C" {
          #[cfg_attr(target_arch = "wasm32", link_name = "transaction::prepare")]
          #[cfg_attr(not(target_arch = "wasm32"), link_name = "edgedb-client-v1_transaction::prepare")]
          fn wit_import(_: i32, _: i32, _: i64, _: i32, _: i32, _: i32, _: i32, _: i32, _: i32, _: i32, _: i32, _: i32, );
        }
        wit_import(self.0, result1_0, result1_1, match implicit_typenames0 { true => 1, false => 0 }, match implicit_typeids0 { true => 1, false => 0 }, (flags2.bits() >> 0) as i32, match explicit_objectids0 { true => 1, false => 0 }, io_format0 as i32, expected_cardinality0 as i32, ptr3, len3, ptr4);
        match *((ptr4 + 0) as *const i32) {
          0 => Ok({
            let len5 = *((ptr4 + 40) as *const i32) as usize;
            let len6 = *((ptr4 + 56) as *const i32) as usize;
            
            (Query(*((ptr4 + 8) as *const i32)), PrepareComplete{capabilities:Capabilities::empty() | Capabilities::from_bits_preserve(((*((ptr4 + 16) as *const i32) as u32) << 0) as _), cardinality:match *((ptr4 + 24) as *const i32) {
              0 => Cardinality::NoResult,
              1 => Cardinality::AtMostOne,
              2 => Cardinality::One,
              3 => Cardinality::Many,
              4 => Cardinality::AtLeastOne,
              _ => panic!("invalid enum discriminant"),
            }, input_typedesc_id:String::from_utf8(Vec::from_raw_parts(*((ptr4 + 32) as *const i32) as *mut _, len5, len5)).unwrap(), output_typedesc_id:String::from_utf8(Vec::from_raw_parts(*((ptr4 + 48) as *const i32) as *mut _, len6, len6)).unwrap(), })
          }),
          1 => Err({
            let base8 = *((ptr4 + 16) as *const i32);
            let len8 = *((ptr4 + 24) as *const i32);
            let mut result8 = Vec::with_capacity(len8 as usize);
            for i in 0..len8 {
              let base = base8 + i *8;
              result8.push({
                let len7 = *((base + 4) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((base + 0) as *const i32) as *mut _, len7, len7)).unwrap()
              });
            }
            std::alloc::dealloc(
            base8 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len8 as usize) * 8,
            4,
            ),
            );
            let base11 = *((ptr4 + 56) as *const i32);
            let len11 = *((ptr4 + 64) as *const i32);
            let mut result11 = Vec::with_capacity(len11 as usize);
            for i in 0..len11 {
              let base = base11 + i *12;
              result11.push({
                let len10 = *((base + 8) as *const i32) as usize;
                
                (i32::from(*((base + 0) as *const u16)) as u16, Vec::from_raw_parts(*((base + 4) as *const i32) as *mut _, len10, len10))
              });
            }
            std::alloc::dealloc(
            base11 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len11 as usize) * 12,
            4,
            ),
            );
            
            Error{code:*((ptr4 + 8) as *const i32) as u32, messages:result8, error:match *((ptr4 + 32) as *const i32) {
              0 => None,
              1 => Some({
                let len9 = *((ptr4 + 48) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((ptr4 + 40) as *const i32) as *mut _, len9, len9)).unwrap()
              }),
              _ => panic!("invalid enum discriminant"),
            }, headers:result11, }
          }),
          _ => panic!("invalid enum discriminant"),
        }
      }
    }
  }
  impl Transaction {
    pub fn commit(&self,) -> Result<(),Error>{
      unsafe {
        let ptr0 = RET_AREA.as_mut_ptr() as i32;
        #[link(wasm_import_module = "edgedb-client-v1")]
        extern "C" {
          #[cfg_attr(target_arch = "wasm32", link_name = "transaction::commit")]
          #[cfg_attr(not(target_arch = "wasm32"), link_name = "edgedb-client-v1_transaction::commit")]
          fn wit_import(_: i32, _: i32, );
        }
        wit_import(self.0, ptr0);
        match *((ptr0 + 0) as *const i32) {
          0 => Ok(()),
          1 => Err({
            let base2 = *((ptr0 + 16) as *const i32);
            let len2 = *((ptr0 + 24) as *const i32);
            let mut result2 = Vec::with_capacity(len2 as usize);
            for i in 0..len2 {
              let base = base2 + i *8;
              result2.push({
                let len1 = *((base + 4) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((base + 0) as *const i32) as *mut _, len1, len1)).unwrap()
              });
            }
            std::alloc::dealloc(
            base2 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len2 as usize) * 8,
            4,
            ),
            );
            let base5 = *((ptr0 + 56) as *const i32);
            let len5 = *((ptr0 + 64) as *const i32);
            let mut result5 = Vec::with_capacity(len5 as usize);
            for i in 0..len5 {
              let base = base5 + i *12;
              result5.push({
                let len4 = *((base + 8) as *const i32) as usize;
                
                (i32::from(*((base + 0) as *const u16)) as u16, Vec::from_raw_parts(*((base + 4) as *const i32) as *mut _, len4, len4))
              });
            }
            std::alloc::dealloc(
            base5 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len5 as usize) * 12,
            4,
            ),
            );
            
            Error{code:*((ptr0 + 8) as *const i32) as u32, messages:result2, error:match *((ptr0 + 32) as *const i32) {
              0 => None,
              1 => Some({
                let len3 = *((ptr0 + 48) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((ptr0 + 40) as *const i32) as *mut _, len3, len3)).unwrap()
              }),
              _ => panic!("invalid enum discriminant"),
            }, headers:result5, }
          }),
          _ => panic!("invalid enum discriminant"),
        }
      }
    }
  }
  impl Transaction {
    pub fn rollback(&self,) -> Result<(),Error>{
      unsafe {
        let ptr0 = RET_AREA.as_mut_ptr() as i32;
        #[link(wasm_import_module = "edgedb-client-v1")]
        extern "C" {
          #[cfg_attr(target_arch = "wasm32", link_name = "transaction::rollback")]
          #[cfg_attr(not(target_arch = "wasm32"), link_name = "edgedb-client-v1_transaction::rollback")]
          fn wit_import(_: i32, _: i32, );
        }
        wit_import(self.0, ptr0);
        match *((ptr0 + 0) as *const i32) {
          0 => Ok(()),
          1 => Err({
            let base2 = *((ptr0 + 16) as *const i32);
            let len2 = *((ptr0 + 24) as *const i32);
            let mut result2 = Vec::with_capacity(len2 as usize);
            for i in 0..len2 {
              let base = base2 + i *8;
              result2.push({
                let len1 = *((base + 4) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((base + 0) as *const i32) as *mut _, len1, len1)).unwrap()
              });
            }
            std::alloc::dealloc(
            base2 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len2 as usize) * 8,
            4,
            ),
            );
            let base5 = *((ptr0 + 56) as *const i32);
            let len5 = *((ptr0 + 64) as *const i32);
            let mut result5 = Vec::with_capacity(len5 as usize);
            for i in 0..len5 {
              let base = base5 + i *12;
              result5.push({
                let len4 = *((base + 8) as *const i32) as usize;
                
                (i32::from(*((base + 0) as *const u16)) as u16, Vec::from_raw_parts(*((base + 4) as *const i32) as *mut _, len4, len4))
              });
            }
            std::alloc::dealloc(
            base5 as *mut _,
            std::alloc::Layout::from_size_align_unchecked(
            (len5 as usize) * 12,
            4,
            ),
            );
            
            Error{code:*((ptr0 + 8) as *const i32) as u32, messages:result2, error:match *((ptr0 + 32) as *const i32) {
              0 => None,
              1 => Some({
                let len3 = *((ptr0 + 48) as *const i32) as usize;
                
                String::from_utf8(Vec::from_raw_parts(*((ptr0 + 40) as *const i32) as *mut _, len3, len3)).unwrap()
              }),
              _ => panic!("invalid enum discriminant"),
            }, headers:result5, }
          }),
          _ => panic!("invalid enum discriminant"),
        }
      }
    }
  }
  static mut RET_AREA: [i64; 12] = [0; 12];
}

mod transaction;

use edgedb_client_v1 as v1;
use transaction::{Transaction, transaction};

/// EdgeDB Client
///
/// Internally it contains a connection pool.
///
/// To create client, use [`create_client`] function.
#[derive(Debug, Clone)]
pub struct Client {
    client: Arc<v1::Client>,
}

/// Create a connection to the database that this WebAssembly app is attached to
pub fn create_client() -> Client {
    Client {
        client: Arc::new(v1::Client::connect()),
    }
}

trait StartQuery {
    fn prepare(self, flags: v1::CompilationFlags, query: &str)
        -> Result<(v1::Query, v1::PrepareComplete), v1::Error>;
}

impl v1::Error {
    fn into_err(self) -> Error {
        let mut err = Error::from_code(self.code);
        for msg in self.messages {
            err = err.context(msg);
        }
        // TODO(tailhook) headers
        return err;
    }
}

impl StartQuery for &'_ Client {
    fn prepare(self, flags: v1::CompilationFlags, query: &str)
        -> Result<(v1::Query, v1::PrepareComplete), v1::Error>
    {
        self.client.prepare(flags, query)
    }
}

fn execute_query<T: StartQuery, R, A>(target: T, query: &str, arguments: &A)
    -> Result<Vec<R>, Error>
    where A: QueryArgs,
          R: QueryResult,
{
    let flags = v1::CompilationFlags {
        implicit_limit: None,
        implicit_typenames: false,
        implicit_typeids: false,
        explicit_objectids: true,
        // host app will remove everything else anyway
        allow_capabilities: v1::Capabilities::MODIFICATIONS,
        io_format: v1::IoFormat::Binary,
        expected_cardinality: v1::Cardinality::Many,
    };
    let (query, _prepare_info) = target.prepare(flags, query)
        .map_err(|e| e.into_err())?;
    let desc = query.describe_data().map_err(|e| e.into_err())?;
    let desc = CommandDataDescription::try_from(desc)?;
    let inp_desc = desc.input()
        .map_err(ProtocolEncodingError::with_source)?;

    let mut arg_buf = BytesMut::with_capacity(8);
    arguments.encode(&mut Encoder::new(
        &inp_desc.as_query_arg_context(),
        &mut arg_buf,
    ))?;

    let data = query.execute(&arg_buf).map_err(|e| e.into_err())?;

    let out_desc = desc.output()
        .map_err(ProtocolEncodingError::with_source)?;
    match out_desc.root_pos() {
        Some(root_pos) => {
            let ctx = out_desc.as_queryable_context();
            let mut state = R::prepare(&ctx, root_pos)?;
            let rows = data.chunks.into_iter()
               .map(|chunk| R::decode(&mut state, &chunk.into()))
               .collect::<Result<_, _>>()?;
            Ok(rows)
        }
        None => Err(NoResultExpected::build()),
    }
}

fn execute_query_single<T: StartQuery, R, A>(target: T,
                                             query: &str, arguments: &A)
    -> Result<Option<R>, Error>
    where A: QueryArgs,
          R: QueryResult,
{
    let flags = v1::CompilationFlags {
        implicit_limit: None,
        implicit_typenames: false,
        implicit_typeids: false,
        explicit_objectids: true,
        // host app will remove everything else anyway
        allow_capabilities: v1::Capabilities::MODIFICATIONS,
        io_format: v1::IoFormat::Binary,
        expected_cardinality: v1::Cardinality::AtMostOne,
    };
    let (query, _prepare_info) = target.prepare(flags, query)
        .map_err(|e| e.into_err())?;
    let desc = query.describe_data().map_err(|e| e.into_err())?;
    let desc = CommandDataDescription::try_from(desc)?;
    let inp_desc = desc.input()
        .map_err(ProtocolEncodingError::with_source)?;

    let mut arg_buf = BytesMut::with_capacity(8);
    arguments.encode(&mut Encoder::new(
        &inp_desc.as_query_arg_context(),
        &mut arg_buf,
    ))?;

    let data = query.execute(&arg_buf).map_err(|e| e.into_err())?;

    let out_desc = desc.output()
        .map_err(ProtocolEncodingError::with_source)?;
    match out_desc.root_pos() {
        Some(root_pos) => {
            let ctx = out_desc.as_queryable_context();
            let mut state = R::prepare(&ctx, root_pos)?;
            let bytes = data.chunks.into_iter().next();
            if let Some(bytes) = bytes {
                Ok(Some(R::decode(&mut state, &Bytes::from(bytes))?))
            } else {
                Ok(None)
            }
        }
        None => Err(NoResultExpected::build()),
    }
}

fn execute_query_json<T: StartQuery>(target: T,
                                     query: &str, arguments: &impl QueryArgs)
    -> Result<Json, Error>
{
    let flags = v1::CompilationFlags {
        implicit_limit: None,
        implicit_typenames: false,
        implicit_typeids: false,
        explicit_objectids: true,
        // host app will remove everything else anyway
        allow_capabilities: v1::Capabilities::MODIFICATIONS,
        io_format: v1::IoFormat::Json,
        expected_cardinality: v1::Cardinality::Many,
    };
    let (query, _prepare_info) = target.prepare(flags, query)
        .map_err(|e| e.into_err())?;
    let desc = query.describe_data().map_err(|e| e.into_err())?;
    let desc = CommandDataDescription::try_from(desc)?;
    let inp_desc = desc.input()
        .map_err(ProtocolEncodingError::with_source)?;

    let mut arg_buf = BytesMut::with_capacity(8);
    arguments.encode(&mut Encoder::new(
        &inp_desc.as_query_arg_context(),
        &mut arg_buf,
    ))?;

    let data = query.execute(&arg_buf).map_err(|e| e.into_err())?;

    let out_desc = desc.output()
        .map_err(ProtocolEncodingError::with_source)?;
    match out_desc.root_pos() {
        Some(root_pos) => {
            let ctx = out_desc.as_queryable_context();
            // JSON objects are returned as strings :(
            let mut state = String::prepare(&ctx, root_pos)?;
            let bytes = data.chunks.into_iter().next();
            if let Some(bytes) = bytes {
                // we trust database to produce valid json
                let s = String::decode(&mut state, &Bytes::from(bytes))?;
                Ok(unsafe { Json::new_unchecked(s) })
            } else {
                Err(NoDataError::with_message(
                    "query row returned zero results"))
            }
        }
        None => Err(NoResultExpected::build()),
    }
}

fn execute_query_single_json<T: StartQuery>(target: T,
    query: &str, arguments: &impl QueryArgs)
    -> Result<Option<Json>, Error>
{
    let flags = v1::CompilationFlags {
        implicit_limit: None,
        implicit_typenames: false,
        implicit_typeids: false,
        explicit_objectids: true,
        // host app will remove everything else anyway
        allow_capabilities: v1::Capabilities::MODIFICATIONS,
        io_format: v1::IoFormat::Json,
        expected_cardinality: v1::Cardinality::AtMostOne,
    };
    let (query, _prepare_info) = target.prepare(flags, query)
        .map_err(|e| e.into_err())?;
    let desc = query.describe_data().map_err(|e| e.into_err())?;
    let desc = CommandDataDescription::try_from(desc)?;
    let inp_desc = desc.input()
        .map_err(ProtocolEncodingError::with_source)?;

    let mut arg_buf = BytesMut::with_capacity(8);
    arguments.encode(&mut Encoder::new(
        &inp_desc.as_query_arg_context(),
        &mut arg_buf,
    ))?;

    let data = query.execute(&arg_buf).map_err(|e| e.into_err())?;

    let out_desc = desc.output()
        .map_err(ProtocolEncodingError::with_source)?;
    match out_desc.root_pos() {
        Some(root_pos) => {
            let ctx = out_desc.as_queryable_context();
            // JSON objects are returned as strings :(
            let mut state = String::prepare(&ctx, root_pos)?;
            let bytes = data.chunks.into_iter().next();
            if let Some(bytes) = bytes {
                // we trust database to produce valid json
                let s = String::decode(&mut state, &Bytes::from(bytes))?;
                Ok(Some(unsafe { Json::new_unchecked(s) }))
            } else {
                Ok(None)
            }
        }
        None => Err(NoResultExpected::build()),
    }
}

impl Client {
    /// Execute a query and return a collection of results.
    ///
    /// You will usually have to specify the return type for the query:
    ///
    /// ```rust,ignore
    /// let greeting = pool.query::<String, _>("SELECT 'hello'", &());
    /// // or
    /// let greeting: Vec<String> = pool.query("SELECT 'hello'", &());
    /// ```
    ///
    /// This method can be used with both static arguments, like a tuple of
    /// scalars, and with dynamic arguments [`edgedb_protocol::value::Value`].
    /// Similarly, dynamically typed results are also supported.
    pub fn query<R, A>(&self, query: &str, arguments: &A)
        -> Result<Vec<R>, Error>
        where A: QueryArgs,
              R: QueryResult,
    {
        execute_query(self, query, arguments)
    }

    /// Execute a query and return a single result
    ///
    /// You will usually have to specify the return type for the query:
    ///
    /// ```rust,ignore
    /// let greeting = pool.query_single::<String, _>("SELECT 'hello'", &());
    /// // or
    /// let greeting: Option<String> = pool.query_single(
    ///     "SELECT 'hello'",
    ///     &()
    /// );
    /// ```
    ///
    /// This method can be used with both static arguments, like a tuple of
    /// scalars, and with dynamic arguments [`edgedb_protocol::value::Value`].
    /// Similarly, dynamically typed results are also supported.
    pub fn query_single<R, A>(&self, query: &str, arguments: &A)
        -> Result<Option<R>, Error>
        where A: QueryArgs,
              R: QueryResult,
    {
        execute_query_single(self, query, arguments)
    }

    /// Execute a query and return a single result
    ///
    /// The query must return exactly one element. If the query returns more
    /// than one element, a
    /// [`ResultCardinalityMismatchError`][crate::client::errors::ResultCardinalityMismatchError]
    /// is raised. If the query returns an empty set, a
    /// [`NoDataError`][crate::client::errors::NoDataError] is raised.
    ///
    /// You will usually have to specify the return type for the query:
    ///
    /// ```rust,ignore
    /// let greeting = pool.query_required_single::<String, _>(
    ///     "SELECT 'hello'",
    ///     &(),
    /// );
    /// // or
    /// let greeting: String = pool.query_required_single(
    ///     "SELECT 'hello'",
    ///     &(),
    /// );
    /// ```
    ///
    /// This method can be used with both static arguments, like a tuple of
    /// scalars, and with dynamic arguments [`edgedb_protocol::value::Value`].
    /// Similarly, dynamically typed results are also supported.
    pub fn query_required_single<R, A>(&self, query: &str, arguments: &A)
        -> Result<R, Error>
        where A: QueryArgs,
              R: QueryResult,
    {
        self.query_single(query, arguments)?
            .ok_or_else(|| NoDataError::with_message(
                        "query row returned zero results"))
    }

    /// Execute a query and return the result as JSON.
    pub fn query_json(&self, query: &str, arguments: &impl QueryArgs)
        -> Result<Json, Error>
    {
        execute_query_json(self, query, arguments)
    }

    /// Execute a query and return a single result as JSON.
    ///
    /// The query must return exactly one element. If the query returns more
    /// than one element, a
    /// [`ResultCardinalityMismatchError`][crate::client::errors::ResultCardinalityMismatchError]
    /// is raised.
    pub fn query_single_json(&self,
                                   query: &str, arguments: &impl QueryArgs)
        -> Result<Option<Json>, Error>
    {
        execute_query_single_json(self, query, arguments)
    }

    /// Execute a query and return a single result as JSON.
    ///
    /// The query must return exactly one element. If the query returns more
    /// than one element, a
    /// [`ResultCardinalityMismatchError`][crate::client::errors::ResultCardinalityMismatchError]
    /// is raised. If the query returns an empty set, a
    /// [`NoDataError`][crate::client::errors::NoDataError] is raised.
    pub fn query_required_single_json(&self,
                                   query: &str, arguments: &impl QueryArgs)
        -> Result<Json, Error>
    {
        self.query_single_json(query, arguments)?
            .ok_or_else(|| NoDataError::with_message(
                        "query row returned zero results"))
    }

    /// Execute a transaction
    ///
    /// Transaction body must be encompassed in the closure. The closure **may
    /// be executed multiple times**. This includes not only database queries
    /// but also executing the whole function, so the transaction code must be
    /// prepared to be idempotent.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # fn transaction() -> Result<(), edgedb_sdk::client::Error> {
    /// let conn = edgedb_sdk::client::create_client();
    /// let val = conn.transaction(|mut tx| {
    ///     // TODO(tailhook) query_required_single
    ///     tx.query_required_single::<i64, _>("
    ///         WITH C := UPDATE Counter SET { value := .value + 1}
    ///         SELECT C.value LIMIT 1
    ///     ", &()
    ///     )
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn transaction<T, F>(&self, body: F) -> Result<T, Error>
        where F: FnMut(&mut Transaction) -> Result<T, Error>,
    {
        transaction(&self, body)
    }
}

impl TryFrom<v1::DataDescription> for CommandDataDescription {
    type Error = Error;
    fn try_from(src: v1::DataDescription)
        -> Result<CommandDataDescription, Error>
    {
        Ok(CommandDataDescription {
            proto: ProtocolVersion::new(src.proto.0, src.proto.1),
            headers: HashMap::new(),
            result_cardinality: src.result_cardinality.into(),
            input_typedesc_id: src.input_typedesc_id.parse()
                .map_err(ClientError::with_source)?,
            input_typedesc: src.input_typedesc.into(),
            output_typedesc_id: src.output_typedesc_id.parse()
                .map_err(ClientError::with_source)?,
            output_typedesc: src.output_typedesc.into(),
        })
    }
}

impl From<v1::Cardinality> for Cardinality {
    fn from(src: v1::Cardinality) -> Cardinality {
        match src {
            v1::Cardinality::NoResult => Cardinality::NoResult,
            v1::Cardinality::AtMostOne => Cardinality::AtMostOne,
            v1::Cardinality::One => Cardinality::One,
            v1::Cardinality::Many => Cardinality::Many,
            v1::Cardinality::AtLeastOne => Cardinality::AtLeastOne,
        }
    }
}