pmeunier / pleingres

Init

By blabla on July 5, 2018
This patch is not signed.
6j4MGnDqtum3hPhiumitdZq2jLKYo9jRhaXTRHhP3sCSSk6Arq475vP5TjXusw2T22YDhCf5gULkMVqtBDVs8QzD
This patch is in the following branches:
master













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
version = "0.4.0"
        "Cargo.toml",
        "src/buffer.rs",
        "src/error.rs",
        "src/lib.rs",
        "src/msg.rs",
        "src/rows.rs",
        "src/spawned.rs",
        "src/statement.rs",
        "src/wait_until.rs"
tokio-core = "0.1"
uuid = "0.6"
error-chain = "0.12"
[package]
name = "pleingres"
version = "0.4.3"
description = "A pure Rust interface to PostgreSQL. Will never block (hence the name, a pun on that fact in french)."
repository = "https://nest.pijul.com/pmeunier/pleingres"
homepage = "https://nest.pijul.com/pmeunier/pleingres"
documentation = "https://docs.rs/pleingres"
license = "Apache-2.0/MIT"
authors = ["Pierre-Étienne Meunier"]
include = [
        "/Cargo.toml",
        "/src/buffer.rs",
        "/src/error.rs",
        "/src/lib.rs",
        "/src/msg.rs",
        "/src/rows.rs",
        "/src/spawned.rs",
        "/src/statement.rs",
        "/src/wait_until.rs"
        ]

[dependencies]
byteorder = "1.2"
chrono = "0.4"
futures = "0.1"
log = "0.4"
md5 = "0.3"
tokio = "0.1"
tokio-io = "0.1"
uuid = "0.7"
digest = "0.7"
serde = "1.0"
serde_derive = "1.0"

bytes = "0.4"
tokio-openssl = "0.2"
tokio-timer = "0.2"

openssl = "0.10"

[dev-dependencies]
env_logger = "0.5"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# An asynchronous, Tokio-based, 100% Rust postgres driver

This crate doesn't do much: it just sends commands to a PostgreSQL server.
But, contrarily to others, it is entirely non-blocking, which means your server can move on to other tasks while the server's response has not arrived, and process the response only when it arrives.

## State of the project

This is experimental, by the way, but still used to serve [nest.pijul.com](https://nest.pijul.com) with some success.

Also, Pleingres supports SSL connections to a PostgreSQL server, which makes it usable to connect to a Google Cloud database server.

## Contributing

The license of this crate is Apache-2.0, or MIT at your convenience.
We expect contributors to follow [Rust's code of conduct](https://www.rust-lang.org/conduct.html).
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
with import <nixpkgs> {};
let release = true;
    verbose = true;
    aho_corasick_0_6_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "aho-corasick";
      version = "0.6.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/aho-corasick/0.6.3/download";
        sha256 = "1cpqzf6acj8lm06z3f1cg41wn6c2n9l3v49nh0dvimv4055qib6k";
        name = "aho-corasick-0.6.3.tar.gz";
      };
      libName = "aho_corasick";
      crateBin = [ {  name = "aho-corasick-dot"; } ];
      inherit dependencies features release verbose;
    };
    backtrace_0_3_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "backtrace";
      version = "0.3.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/backtrace/0.3.3/download";
        sha256 = "0invfdxkj85v8zyrjs3amfxjdk2a36x8irq7wq7kny6q49hh8y0z";
        name = "backtrace-0.3.3.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    backtrace_sys_0_1_16_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "backtrace-sys";
      version = "0.1.16";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/backtrace-sys/0.1.16/download";
        sha256 = "1cn2c8q3dn06crmnk0p62czkngam4l8nf57wy33nz1y5g25pszwy";
        name = "backtrace-sys-0.1.16.tar.gz";
      };
      build = "build.rs";
      buildDependencies = [ cc_0_0_0 ];
      inherit dependencies features release verbose;
    };
    bitflags_0_7_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "bitflags";
      version = "0.7.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/bitflags/0.7.0/download";
        sha256 = "1hr72xg5slm0z4pxs2hiy4wcyx3jva70h58b7mid8l0a4c8f7gn5";
        name = "bitflags-0.7.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    bitflags_0_9_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "bitflags";
      version = "0.9.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/bitflags/0.9.1/download";
        sha256 = "18h073l5jd88rx4qdr95fjddr9rk79pb1aqnshzdnw16cfmb9rws";
        name = "bitflags-0.9.1.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    byte_tools_0_1_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "byte-tools";
      version = "0.1.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/byte-tools/0.1.3/download";
        sha256 = "1igbr5x8krjm2vx05jql2skpsfbjmiyb50b7gsvl5fllp0df29af";
        name = "byte-tools-0.1.3.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    byteorder_1_1_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "byteorder";
      version = "1.1.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/byteorder/1.1.0/download";
        sha256 = "1i2n0161jm00zvzh4bncgv9zrwa6ydbxdn5j4bx0wwn7rvi9zycp";
        name = "byteorder-1.1.0.tar.gz";
      };
      libName = "byteorder";
      inherit dependencies features release verbose;
    };
    bytes_0_4_5_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "bytes";
      version = "0.4.5";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/bytes/0.4.5/download";
        sha256 = "09grypiv7wnqbhsmini1i77d5bwcna6nzp3yhh9i02hn37ma58vn";
        name = "bytes-0.4.5.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    cc_1_0_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "cc";
      version = "1.0.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/cc/1.0.3/download";
        sha256 = "193pwqgh79w6k0k29svyds5nnlrwx44myqyrw605d5jj4yk2zmpr";
        name = "cc-1.0.3.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    cfg_if_0_1_2_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "cfg-if";
      version = "0.1.2";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/cfg-if/0.1.2/download";
        sha256 = "0x06hvrrqy96m97593823vvxcgvjaxckghwyy2jcyc8qc7c6cyhi";
        name = "cfg-if-0.1.2.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    chrono_0_4_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "chrono";
      version = "0.4.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/chrono/0.4.0/download";
        sha256 = "0hm53hi6v7b6b1va6vn96lx26wvj8gzi2g51s1j02nlz0jcprw6a";
        name = "chrono-0.4.0.tar.gz";
      };
      libName = "chrono";
      inherit dependencies features release verbose;
    };
    dbghelp_sys_0_2_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "dbghelp-sys";
      version = "0.2.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/dbghelp-sys/0.2.0/download";
        sha256 = "0ylpi3bbiy233m57hnisn1df1v0lbl7nsxn34b0anzsgg440hqpq";
        name = "dbghelp-sys-0.2.0.tar.gz";
      };
      libName = "dbghelp";
      build = "build.rs";
      buildDependencies = [ winapi_build_0_0_0 ];
      inherit dependencies features release verbose;
    };
    digest_0_5_2_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "digest";
      version = "0.5.2";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/digest/0.5.2/download";
        sha256 = "1vm57l8z8y4h0bsvh6kmp3r90ki9y75qjq39x1iv5y918yy5y3lm";
        name = "digest-0.5.2.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    digest_buffer_0_3_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "digest-buffer";
      version = "0.3.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/digest-buffer/0.3.1/download";
        sha256 = "0y8k8wb30w57fnspgmgmv3sbs8ldkkc1yfm866rrnwqsmhx3vhm4";
        name = "digest-buffer-0.3.1.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    env_logger_0_4_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "env_logger";
      version = "0.4.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/env_logger/0.4.3/download";
        sha256 = "0nrx04p4xa86d5kc7aq4fwvipbqji9cmgy449h47nc9f1chafhgg";
        name = "env_logger-0.4.3.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    error_chain_0_11_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "error-chain";
      version = "0.11.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/error-chain/0.11.0/download";
        sha256 = "19nz17q6dzp0mx2jhh9qbj45gkvvgcl7zq9z2ai5a8ihbisfj6d7";
        name = "error-chain-0.11.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    foreign_types_0_2_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "foreign-types";
      version = "0.2.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/foreign-types/0.2.0/download";
        sha256 = "1sznwg2py4xi7hyrx0gg1sirlwgh87wsanvjx3zb475g6c4139jh";
        name = "foreign-types-0.2.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    fuchsia_zircon_0_2_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "fuchsia-zircon";
      version = "0.2.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/fuchsia-zircon/0.2.1/download";
        sha256 = "0yd4rd7ql1vdr349p6vgq2dnwmpylky1kjp8g1zgvp250jxrhddb";
        name = "fuchsia-zircon-0.2.1.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    fuchsia_zircon_sys_0_2_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "fuchsia-zircon-sys";
      version = "0.2.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/fuchsia-zircon-sys/0.2.0/download";
        sha256 = "1yrqsrjwlhl3di6prxf5xmyd82gyjaysldbka5wwk83z11mpqh4w";
        name = "fuchsia-zircon-sys-0.2.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    futures_0_1_16_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "futures";
      version = "0.1.16";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/futures/0.1.16/download";
        sha256 = "0ndk8cl6l600a95q8il2c3y38jz50nhfsczps0nziadqdd45gy2b";
        name = "futures-0.1.16.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    generic_array_0_7_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "generic-array";
      version = "0.7.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/generic-array/0.7.3/download";
        sha256 = "0jw50an9g7vscf7wfqgzfq9wxrawh0hyypyi74xf2k6zj8zkjgr9";
        name = "generic-array-0.7.3.tar.gz";
      };
      libName = "generic_array";
      inherit dependencies features release verbose;
    };
    iovec_0_1_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "iovec";
      version = "0.1.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/iovec/0.1.1/download";
        sha256 = "14fns3g3arbql6lkczf2gbbzaqh22mfv7y1wq5rr2y8jhh5m8jmm";
        name = "iovec-0.1.1.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    kernel32_sys_0_2_2_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "kernel32-sys";
      version = "0.2.2";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/kernel32-sys/0.2.2/download";
        sha256 = "1lrw1hbinyvr6cp28g60z97w32w8vsk6pahk64pmrv2fmby8srfj";
        name = "kernel32-sys-0.2.2.tar.gz";
      };
      libName = "kernel32";
      build = "build.rs";
      buildDependencies = [ winapi_build_0_0_0 ];
      inherit dependencies features release verbose;
    };
    lazy_static_0_2_9_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "lazy_static";
      version = "0.2.9";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/lazy_static/0.2.9/download";
        sha256 = "08ldzr5292y3hvi6l6v8l4i6v95lm1aysmnfln65h10sqrfh6iw7";
        name = "lazy_static-0.2.9.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    lazycell_0_5_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "lazycell";
      version = "0.5.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/lazycell/0.5.1/download";
        sha256 = "1ds71sc24vnhfy0ys1v46qn7fkcavi4brsk4jg3dp8d0yli3sd31";
        name = "lazycell-0.5.1.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    libc_0_2_32_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "libc";
      version = "0.2.32";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/libc/0.2.32/download";
        sha256 = "1i8njlar6v9qvmkyfvwzhxrvkqw6ijp8fqdnya5csqixxz18a532";
        name = "libc-0.2.32.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    log_0_3_8_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "log";
      version = "0.3.8";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/log/0.3.8/download";
        sha256 = "1c43z4z85sxrsgir4s1hi84558ab5ic7jrn5qgmsiqcv90vvn006";
        name = "log-0.3.8.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    md_5_0_4_4_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "md-5";
      version = "0.4.4";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/md-5/0.4.4/download";
        sha256 = "1fds6qkgf3g6s25ppc29sqh941blhwni6ifnr3034vnhcvp14zwd";
        name = "md-5-0.4.4.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    memchr_1_0_2_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "memchr";
      version = "1.0.2";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/memchr/1.0.2/download";
        sha256 = "0dfb8ifl9nrc9kzgd5z91q6qg87sh285q1ih7xgrsglmqfav9lg7";
        name = "memchr-1.0.2.tar.gz";
      };
      libName = "memchr";
      inherit dependencies features release verbose;
    };
    mio_0_6_11_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "mio";
      version = "0.6.11";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/mio/0.6.11/download";
        sha256 = "0maafa27rard6r62rc7iv5mcn2g0vvv6kw5as1kbf7mr4q1ph6sm";
        name = "mio-0.6.11.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    miow_0_2_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "miow";
      version = "0.2.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/miow/0.2.1/download";
        sha256 = "14f8zkc6ix7mkyis1vsqnim8m29b6l55abkba3p2yz7j1ibcvrl0";
        name = "miow-0.2.1.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    net2_0_2_31_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "net2";
      version = "0.2.31";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/net2/0.2.31/download";
        sha256 = "13mphllfcbybsdqyi1jb3kyqx65m8ch07drr59a4wb3yl89awm7y";
        name = "net2-0.2.31.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    nodrop_0_1_12_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "nodrop";
      version = "0.1.12";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/nodrop/0.1.12/download";
        sha256 = "1b9rxvdg8061gxjc239l9slndf0ds3m6fy2sf3gs8f9kknqgl49d";
        name = "nodrop-0.1.12.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    num_0_1_40_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "num";
      version = "0.1.40";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/num/0.1.40/download";
        sha256 = "0b29c25n9mpf6a921khj7a6y3hz5va4vgwppcd2if975qq1shakg";
        name = "num-0.1.40.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    num_integer_0_1_35_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "num-integer";
      version = "0.1.35";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/num-integer/0.1.35/download";
        sha256 = "0xybj8isi9b6wc646d5rc043i8l8j6wy0vrl4pn995qms9fxbbcc";
        name = "num-integer-0.1.35.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    num_iter_0_1_34_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "num-iter";
      version = "0.1.34";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/num-iter/0.1.34/download";
        sha256 = "02cld7x9dzbqbs6sxxzq1i22z3awlcd6ljkgvhkfr9rsnaxphzl9";
        name = "num-iter-0.1.34.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    num_traits_0_1_40_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "num-traits";
      version = "0.1.40";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/num-traits/0.1.40/download";
        sha256 = "1fr8ghp4i97q3agki54i0hpmqxv3s65i2mqd1pinc7w7arc3fplw";
        name = "num-traits-0.1.40.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    openssl_0_9_20_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "openssl";
      version = "0.9.20";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/openssl/0.9.20/download";
        sha256 = "0dbj6k6z828c3sqbxidw5zfval29k8dlsr8qn8fizhc1alli18gx";
        name = "openssl-0.9.20.tar.gz";
      };
      build = "build.rs";
      inherit dependencies features release verbose;
    };
    openssl_sys_0_9_20_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "openssl-sys";
      version = "0.9.20";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/openssl-sys/0.9.20/download";
        sha256 = "05q6qagvy7lim9vkq2v00vpm34j1dq4xy9pchs7fb6yy803vx24m";
        name = "openssl-sys-0.9.20.tar.gz";
      };
      build = "build.rs";
      buildDependencies = [ cc_0_0_0 pkg_config_0_0_0 ];
      inherit dependencies features release verbose;
    };
    pkg_config_0_3_9_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "pkg-config";
      version = "0.3.9";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/pkg-config/0.3.9/download";
        sha256 = "06k8fxgrsrxj8mjpjcq1n7mn2p1shpxif4zg9y5h09c7vy20s146";
        name = "pkg-config-0.3.9.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    pleingres_0_4_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "pleingres";
      version = "0.4.0";
      src = ./.;
      inherit dependencies features release verbose;
    };
    quote_0_3_15_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "quote";
      version = "0.3.15";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/quote/0.3.15/download";
        sha256 = "09il61jv4kd1360spaj46qwyl21fv1qz18fsv2jra8wdnlgl5jsg";
        name = "quote-0.3.15.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    redox_syscall_0_1_31_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "redox_syscall";
      version = "0.1.31";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/redox_syscall/0.1.31/download";
        sha256 = "0kipd9qslzin4fgj4jrxv6yz5l3l71gnbd7fq1jhk2j7f2sq33j4";
        name = "redox_syscall-0.1.31.tar.gz";
      };
      libName = "syscall";
      inherit dependencies features release verbose;
    };
    regex_0_2_2_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "regex";
      version = "0.2.2";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/regex/0.2.2/download";
        sha256 = "1f1zrrynfylg0vcfyfp60bybq4rp5g1yk2k7lc7fyz7mmc7k2qr7";
        name = "regex-0.2.2.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    regex_syntax_0_4_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "regex-syntax";
      version = "0.4.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/regex-syntax/0.4.1/download";
        sha256 = "01yrsm68lj86ad1whgg1z95c2pfsvv58fz8qjcgw7mlszc0c08ls";
        name = "regex-syntax-0.4.1.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    rustc_demangle_0_1_5_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "rustc-demangle";
      version = "0.1.5";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/rustc-demangle/0.1.5/download";
        sha256 = "096kkcx9j747700fhxj1s4rlwkj21pqjmvj64psdj6bakb2q13nc";
        name = "rustc-demangle-0.1.5.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    scoped_tls_0_1_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "scoped-tls";
      version = "0.1.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/scoped-tls/0.1.0/download";
        sha256 = "1j8azxa15srljafrg7wc221npvxb3700sbfk6jjav0rw2zclsnf5";
        name = "scoped-tls-0.1.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    serde_1_0_16_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "serde";
      version = "1.0.16";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/serde/1.0.16/download";
        sha256 = "1ncjkvibahr7xk0829nnwr9z05pk45s64wfdv5ydljzz5fr4qvjv";
        name = "serde-1.0.16.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    serde_derive_1_0_16_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "serde_derive";
      version = "1.0.16";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/serde_derive/1.0.16/download";
        sha256 = "0zl4aj170ilnyl08d40ibxavvgk6rgb4np4ydr4lfghxlshfrhwl";
        name = "serde_derive-1.0.16.tar.gz";
      };
      libName = "serde_derive";
      procMacro = true;
      inherit dependencies features release verbose;
    };
    serde_derive_internals_0_16_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "serde_derive_internals";
      version = "0.16.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/serde_derive_internals/0.16.0/download";
        sha256 = "1k96ypwlhnvmaksimkx1pd5rwvjaanfcdzpgndhy994hx03xplhs";
        name = "serde_derive_internals-0.16.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    slab_0_3_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "slab";
      version = "0.3.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/slab/0.3.0/download";
        sha256 = "0y6lhjggksh57hyfd3l6p9wgv5nhvw9c6djrysq7jnalz8fih21k";
        name = "slab-0.3.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    slab_0_4_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "slab";
      version = "0.4.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/slab/0.4.0/download";
        sha256 = "1qy2vkgwqgj5z4ygdkh040n9yh1vz80v5flxb1xrvw3i4wxs7yx0";
        name = "slab-0.4.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    syn_0_11_11_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "syn";
      version = "0.11.11";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/syn/0.11.11/download";
        sha256 = "0yw8ng7x1dn5a6ykg0ib49y7r9nhzgpiq2989rqdp7rdz3n85502";
        name = "syn-0.11.11.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    synom_0_11_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "synom";
      version = "0.11.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/synom/0.11.3/download";
        sha256 = "1l6d1s9qjfp6ng2s2z8219igvlv7gyk8gby97sdykqc1r93d8rhc";
        name = "synom-0.11.3.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    thread_local_0_3_4_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "thread_local";
      version = "0.3.4";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/thread_local/0.3.4/download";
        sha256 = "1y6cwyhhx2nkz4b3dziwhqdvgq830z8wjp32b40pjd8r0hxqv2jr";
        name = "thread_local-0.3.4.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    time_0_1_38_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "time";
      version = "0.1.38";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/time/0.1.38/download";
        sha256 = "1ws283vvz7c6jfiwn53rmc6kybapr4pjaahfxxrz232b0qzw7gcp";
        name = "time-0.1.38.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    tokio_core_0_1_10_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "tokio-core";
      version = "0.1.10";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/tokio-core/0.1.10/download";
        sha256 = "005mpg94zgygpk2iib9sg9xi4wxsk8r9gpwbsdvfz4fzs3p6l596";
        name = "tokio-core-0.1.10.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    tokio_io_0_1_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "tokio-io";
      version = "0.1.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/tokio-io/0.1.3/download";
        sha256 = "0j4irap8l9lqa9nw6yiizs16z6fnzh3jbzmzf0f4r3wb3s8mnf6z";
        name = "tokio-io-0.1.3.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    tokio_openssl_0_1_3_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "tokio-openssl";
      version = "0.1.3";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/tokio-openssl/0.1.3/download";
        sha256 = "1344z5s2vs4xsqcnfbksg1kihxny1q1km0qv88mk2fzmxs2pwwr5";
        name = "tokio-openssl-0.1.3.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    typenum_1_9_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "typenum";
      version = "1.9.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/typenum/1.9.0/download";
        sha256 = "1rrvil9sa8dxgjcfmk1rsfmd73x8vs82z6110i8bz34k13l302mv";
        name = "typenum-1.9.0.tar.gz";
      };
      libName = "typenum";
      build = "build/main.rs";
      inherit dependencies features release verbose;
    };
    unicode_xid_0_0_4_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "unicode-xid";
      version = "0.0.4";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/unicode-xid/0.0.4/download";
        sha256 = "1dc8wkkcd3s6534s5aw4lbjn8m67flkkbnajp5bl8408wdg8rh9v";
        name = "unicode-xid-0.0.4.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    unreachable_1_0_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "unreachable";
      version = "1.0.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/unreachable/1.0.0/download";
        sha256 = "1am8czbk5wwr25gbp2zr007744fxjshhdqjz9liz7wl4pnv3whcf";
        name = "unreachable-1.0.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    utf8_ranges_1_0_0_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "utf8-ranges";
      version = "1.0.0";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/utf8-ranges/1.0.0/download";
        sha256 = "0rzmqprwjv9yp1n0qqgahgm24872x6c0xddfym5pfndy7a36vkn0";
        name = "utf8-ranges-1.0.0.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    uuid_0_5_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "uuid";
      version = "0.5.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/uuid/0.5.1/download";
        sha256 = "17d4csjmy7fa3ckrm40d3c3v411rw5d4400w756mcrzyw2pm1i2r";
        name = "uuid-0.5.1.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    vcpkg_0_2_2_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "vcpkg";
      version = "0.2.2";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/vcpkg/0.2.2/download";
        sha256 = "1fl5j0ksnwrnsrf1b1a9lqbjgnajdipq0030vsbhx81mb7d9478a";
        name = "vcpkg-0.2.2.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    void_1_0_2_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "void";
      version = "1.0.2";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/void/1.0.2/download";
        sha256 = "0h1dm0dx8dhf56a83k68mijyxigqhizpskwxfdrs1drwv2cdclv3";
        name = "void-1.0.2.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    winapi_0_2_8_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "winapi";
      version = "0.2.8";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/winapi/0.2.8/download";
        sha256 = "0a45b58ywf12vb7gvj6h3j264nydynmzyqz8d8rqxsj6icqv82as";
        name = "winapi-0.2.8.tar.gz";
      };
      inherit dependencies features release verbose;
    };
    winapi_build_0_1_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "winapi-build";
      version = "0.1.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/winapi-build/0.1.1/download";
        sha256 = "1lxlpi87rkhxcwp2ykf1ldw3p108hwm24nywf3jfrvmff4rjhqga";
        name = "winapi-build-0.1.1.tar.gz";
      };
      libName = "build";
      inherit dependencies features release verbose;
    };
    ws2_32_sys_0_2_1_ = { dependencies?[], features?[] }: mkRustCrate {
      crateName = "ws2_32-sys";
      version = "0.2.1";
      src = fetchzip {
        url = "https://crates.io/api/v1/crates/ws2_32-sys/0.2.1/download";
        sha256 = "1zpy9d9wk11sj17fczfngcj28w4xxjs3b4n036yzpy38dxp4f7kc";
        name = "ws2_32-sys-0.2.1.tar.gz";
      };
      libName = "ws2_32";
      build = "build.rs";
      buildDependencies = [ winapi_build_0_0_0 ];
      inherit dependencies features release verbose;
    };

in
rec {
  aho_corasick_0_6_3 = aho_corasick_0_6_3_ {
    dependencies = [ memchr_1_0_2 ];
  };
  backtrace_0_3_3 = backtrace_0_3_3_ {
    dependencies = [ backtrace_sys_0_1_16 cfg_if_0_1_2 dbghelp_sys_0_2_0 kernel32_sys_0_2_2 libc_0_2_32 rustc_demangle_0_1_5 winapi_0_2_8 ];
    features = [ "backtrace-sys" "coresymbolication" "dbghelp" "dbghelp-sys" "dladdr" "kernel32-sys" "libbacktrace" "libunwind" "winapi" ];
  };
  backtrace_sys_0_1_16 = backtrace_sys_0_1_16_ {
    dependencies = [ cc_1_0_3 libc_0_2_32 ];
  };
  bitflags_0_7_0 = bitflags_0_7_0_ {};
  bitflags_0_9_1 = bitflags_0_9_1_ {
    features = [ "example_generated" ];
  };
  byte_tools_0_1_3 = byte_tools_0_1_3_ {};
  byteorder_1_1_0 = byteorder_1_1_0_ {
    features = [ "std" ];
  };
  bytes_0_4_5 = bytes_0_4_5_ {
    dependencies = [ byteorder_1_1_0 iovec_0_1_1 ];
  };
  cc_1_0_3 = cc_1_0_3_ {};
  cfg_if_0_1_2 = cfg_if_0_1_2_ {};
  chrono_0_4_0 = chrono_0_4_0_ {
    dependencies = [ num_0_1_40 time_0_1_38 ];
  };
  dbghelp_sys_0_2_0 = dbghelp_sys_0_2_0_ {
    dependencies = [ winapi_0_2_8 winapi_build_0_1_1 ];
  };
  digest_0_5_2 = digest_0_5_2_ {
    dependencies = [ generic_array_0_7_3 ];
  };
  digest_buffer_0_3_1 = digest_buffer_0_3_1_ {
    dependencies = [ byte_tools_0_1_3 generic_array_0_7_3 ];
  };
  env_logger_0_4_3 = env_logger_0_4_3_ {
    dependencies = [ log_0_3_8 regex_0_2_2 ];
    features = [ "regex" ];
  };
  error_chain_0_11_0 = error_chain_0_11_0_ {
    dependencies = [ backtrace_0_3_3 ];
    features = [ "backtrace" "example_generated" ];
  };
  foreign_types_0_2_0 = foreign_types_0_2_0_ {};
  fuchsia_zircon_0_2_1 = fuchsia_zircon_0_2_1_ {
    dependencies = [ fuchsia_zircon_sys_0_2_0 ];
  };
  fuchsia_zircon_sys_0_2_0 = fuchsia_zircon_sys_0_2_0_ {
    dependencies = [ bitflags_0_7_0 ];
  };
  futures_0_1_16 = futures_0_1_16_ {
    features = [ "use_std" "with-deprecated" ];
  };
  generic_array_0_7_3 = generic_array_0_7_3_ {
    dependencies = [ nodrop_0_1_12 typenum_1_9_0 ];
  };
  iovec_0_1_1 = iovec_0_1_1_ {
    dependencies = [ libc_0_2_32 winapi_0_2_8 ];
  };
  kernel32_sys_0_2_2 = kernel32_sys_0_2_2_ {
    dependencies = [ winapi_0_2_8 winapi_build_0_1_1 ];
  };
  lazy_static_0_2_9 = lazy_static_0_2_9_ {};
  lazycell_0_5_1 = lazycell_0_5_1_ {};
  libc_0_2_32 = libc_0_2_32_ {
    features = [ "use_std" ];
  };
  log_0_3_8 = log_0_3_8_ {
    features = [ "use_std" ];
  };
  md_5_0_4_4 = md_5_0_4_4_ {
    dependencies = [ byte_tools_0_1_3 digest_0_5_2 digest_buffer_0_3_1 generic_array_0_7_3 ];
  };
  memchr_1_0_2 = memchr_1_0_2_ {
    dependencies = [ libc_0_2_32 ];
    features = [ "libc" "use_std" ];
  };
  mio_0_6_11 = mio_0_6_11_ {
    dependencies = [ fuchsia_zircon_0_2_1 fuchsia_zircon_sys_0_2_0 iovec_0_1_1 kernel32_sys_0_2_2 lazycell_0_5_1 libc_0_2_32 log_0_3_8 miow_0_2_1 net2_0_2_31 slab_0_3_0 winapi_0_2_8 ];
    features = [ "with-deprecated" ];
  };
  miow_0_2_1 = miow_0_2_1_ {
    dependencies = [ kernel32_sys_0_2_2 net2_0_2_31 winapi_0_2_8 ws2_32_sys_0_2_1 ];
  };
  net2_0_2_31 = net2_0_2_31_ {
    dependencies = [ cfg_if_0_1_2 kernel32_sys_0_2_2 libc_0_2_32 winapi_0_2_8 ws2_32_sys_0_2_1 ];
    features = [ "duration" ];
  };
  nodrop_0_1_12 = nodrop_0_1_12_ {
    features = [ "std" ];
  };
  num_0_1_40 = num_0_1_40_ {
    dependencies = [ num_integer_0_1_35 num_iter_0_1_34 num_traits_0_1_40 ];
    features = [ "bigint" "complex" "rational" "rustc-serialize" ];
  };
  num_integer_0_1_35 = num_integer_0_1_35_ {
    dependencies = [ num_traits_0_1_40 ];
  };
  num_iter_0_1_34 = num_iter_0_1_34_ {
    dependencies = [ num_integer_0_1_35 num_traits_0_1_40 ];
  };
  num_traits_0_1_40 = num_traits_0_1_40_ {};
  openssl_0_9_20 = openssl_0_9_20_ {
    dependencies = [ bitflags_0_9_1 foreign_types_0_2_0 lazy_static_0_2_9 libc_0_2_32 openssl_sys_0_9_20 ];
  };
  openssl_sys_0_9_20 = openssl_sys_0_9_20_ {
    dependencies = [ cc_1_0_3 libc_0_2_32 pkg_config_0_3_9 vcpkg_0_2_2 ];
  };
  pkg_config_0_3_9 = pkg_config_0_3_9_ {};
  pleingres_0_4_0 = pleingres_0_4_0_ {
    dependencies = [ byteorder_1_1_0 bytes_0_4_5 chrono_0_4_0 digest_0_5_2 env_logger_0_4_3 error_chain_0_11_0 futures_0_1_16 generic_array_0_7_3 log_0_3_8 md_5_0_4_4 openssl_0_9_20 serde_1_0_16 serde_derive_1_0_16 tokio_core_0_1_10 tokio_io_0_1_3 tokio_openssl_0_1_3 uuid_0_5_1 ];
  };
  quote_0_3_15 = quote_0_3_15_ {};
  redox_syscall_0_1_31 = redox_syscall_0_1_31_ {};
  regex_0_2_2 = regex_0_2_2_ {
    dependencies = [ aho_corasick_0_6_3 memchr_1_0_2 regex_syntax_0_4_1 thread_local_0_3_4 utf8_ranges_1_0_0 ];
  };
  regex_syntax_0_4_1 = regex_syntax_0_4_1_ {};
  rustc_demangle_0_1_5 = rustc_demangle_0_1_5_ {};
  scoped_tls_0_1_0 = scoped_tls_0_1_0_ {};
  serde_1_0_16 = serde_1_0_16_ {
    features = [ "std" ];
  };
  serde_derive_1_0_16 = serde_derive_1_0_16_ {
    dependencies = [ quote_0_3_15 serde_derive_internals_0_16_0 syn_0_11_11 ];
  };
  serde_derive_internals_0_16_0 = serde_derive_internals_0_16_0_ {
    dependencies = [ syn_0_11_11 synom_0_11_3 ];
  };
  slab_0_3_0 = slab_0_3_0_ {};
  slab_0_4_0 = slab_0_4_0_ {};
  syn_0_11_11 = syn_0_11_11_ {
    dependencies = [ quote_0_3_15 synom_0_11_3 unicode_xid_0_0_4 ];
    features = [ "parsing" "printing" "quote" "synom" "unicode-xid" "visit" ];
  };
  synom_0_11_3 = synom_0_11_3_ {
    dependencies = [ unicode_xid_0_0_4 ];
  };
  thread_local_0_3_4 = thread_local_0_3_4_ {
    dependencies = [ lazy_static_0_2_9 unreachable_1_0_0 ];
  };
  time_0_1_38 = time_0_1_38_ {
    dependencies = [ kernel32_sys_0_2_2 libc_0_2_32 redox_syscall_0_1_31 winapi_0_2_8 ];
  };
  tokio_core_0_1_10 = tokio_core_0_1_10_ {
    dependencies = [ bytes_0_4_5 futures_0_1_16 iovec_0_1_1 log_0_3_8 mio_0_6_11 scoped_tls_0_1_0 slab_0_4_0 tokio_io_0_1_3 ];
  };
  tokio_io_0_1_3 = tokio_io_0_1_3_ {
    dependencies = [ bytes_0_4_5 futures_0_1_16 log_0_3_8 ];
  };
  tokio_openssl_0_1_3 = tokio_openssl_0_1_3_ {
    dependencies = [ futures_0_1_16 openssl_0_9_20 tokio_core_0_1_10 tokio_io_0_1_3 ];
  };
  typenum_1_9_0 = typenum_1_9_0_ {};
  unicode_xid_0_0_4 = unicode_xid_0_0_4_ {};
  unreachable_1_0_0 = unreachable_1_0_0_ {
    dependencies = [ void_1_0_2 ];
  };
  utf8_ranges_1_0_0 = utf8_ranges_1_0_0_ {};
  uuid_0_5_1 = uuid_0_5_1_ {};
  vcpkg_0_2_2 = vcpkg_0_2_2_ {};
  void_1_0_2 = void_1_0_2_ {
    features = [ "std" ];
  };
  winapi_0_2_8 = winapi_0_2_8_ {};
  winapi_build_0_1_1 = winapi_build_0_1_1_ {};
  ws2_32_sys_0_2_1 = ws2_32_sys_0_2_1_ {
    dependencies = [ winapi_0_2_8 winapi_build_0_1_1 ];
  };
}








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
fn parse_into(buf: &mut Vec<u8>, statement_name: &[u8], statement: &str, parameter_types: &[SqlType]) {
    buf.write_i16::<BigEndian>(parameter_types.len() as i16).unwrap();
    for p in parameter_types {
        buf.write_i32::<BigEndian>(*p as i32).unwrap()
    pub fn parse<Name:AsRef<[u8]>>(&mut self, statement_name: Name, statement: &str, parameter_types: &[SqlType]) {
            parse_into(buf, statement_name.as_ref(), statement, parameter_types)
            parse_into(&mut self.buf, statement_name.as_ref(), statement, parameter_types)
        self.parse("", statement, &[]);
use byteorder::WriteBytesExt;
use statement::*;
use msg::*;
use std::io::Write;
use byteorder::{BigEndian, ByteOrder};
use {Connection, WriteState, Parameters};
use std::borrow::Cow;
use std::collections::HashMap;
// use tokio::io::{AsyncRead, AsyncWrite};
use tokio_io::{AsyncRead, AsyncWrite};

impl<W: AsyncRead + AsyncWrite, P: AsRef<Parameters>> Connection<W, P> {
    /// Return a pointer to this connection's internal buffer, when
    /// the connection is reading. The connection's `write` method
    /// must be called after the buffer is finished.
    pub fn buffer(&mut self) -> Buffer {
        if let Some(WriteState::Idle { ref mut buf, .. }) = self.write {
            buf.clear();
            Buffer {
                buf,
                parse_buffer: None,
                parsed: &mut self.parsed_queries
            }
        } else {
            unreachable!()
        }
    }
}


/// A single connection uses just two buffers, allocated at the
/// beginning of the connection. This type is a view into one of these
/// buffer, which can be used to send orders via the provided methods.
pub struct Buffer<'a> {
    // Since names are assigned to new queries when they are parsed,
    // and re-issued queries (on reconnection after an error) reuse
    // the same names, we need to reparse queries with the same names
    // at the beginning of each reconnection.  This means that
    // re-issued queries MUST NOT contain parse commands, which is why
    // there are two buffers here. `parse_buffer` will be None when
    // this buffer is for a reconnection, and will be Some when
    // parsing new queries.
    buf: &'a mut Vec<u8>,
    parse_buffer: Option<&'a mut Vec<u8>>,
    parsed: &'a mut HashMap<Cow<'static, str>, usize>
}

/// A portal (the result of a bind). Portals can be executed, or… executed.
pub struct Portal<'b, 'a: 'b, 'c> {
    name: &'c str,
    buf: &'b mut Buffer<'a>
}

impl<'a, 'b: 'a, 'c> Portal<'a, 'b, 'c> {
    /// Execute a given portal, returning at most the supplied number
    /// of rows, or an unlimited number if `max_rows == 0`.
    pub fn execute(self, max_rows: i32) {
        self.buf.execute(self.name, max_rows);
    }
}

impl<'a, 'b:'a, 'c> Drop for Portal<'a, 'b, 'c> {
    fn drop(&mut self) {
        self.buf.close_portal(self.name)
    }
}
use std::str::from_utf8;

#[doc(hidden)]
pub fn name(len: usize) -> [u8; 20] {
    let mut name: [u8; 20] = [b'_'; 20];
    write!(&mut name[..], "__{}", len).unwrap();
    name
}

fn parse_into(buf: &mut Vec<u8>, statement_name: &[u8], statement: &str, parameters: &[&ToSql]) {
    { debug!("parse {:?} {:?}", from_utf8(statement_name), statement); }
    // Prepare statement
    let l0 = buf.len();
    buf.push(MSG_PARSE);
    buf.extend(&[0, 0, 0, 0]);
    buf.extend(statement_name);
    buf.push(0);
    buf.extend(statement.as_bytes());
    buf.push(0);
    buf.write_i16::<BigEndian>(parameters.len() as i16).unwrap();
    for p in parameters {
        buf.write_i32::<BigEndian>(p.sql_type() as i32).unwrap()
    }
    let len = buf.len() - l0 - 1;
    BigEndian::write_u32(&mut buf[l0 + 1..], len as u32);
}


impl<'a> Buffer<'a> {

    #[doc(hidden)]
    pub fn buf(buf: &'a mut Vec<u8>, parse_buffer: &'a mut Vec<u8>, parsed: &'a mut HashMap<Cow<'static, str>, usize>) -> Self {
        Buffer {
            buf: buf,
            parse_buffer: Some(parse_buffer),
            parsed: parsed
        }
    }

    #[doc(hidden)]
    pub fn clone_from_buf(&mut self, v: &[u8]) {
        self.buf.clear();
        self.buf.extend(v)
    }

    #[doc(hidden)]
    pub fn extend(&mut self, v: &[u8]) {
        self.buf.extend(v)
    }

    #[doc(hidden)]
    pub fn clear(&mut self) {
        self.buf.clear();
    }

    /// Parse a statement.
    pub fn parse<Name:AsRef<[u8]>>(&mut self, statement_name: Name, statement: &str, parameters: &[&ToSql]) {
        if let Some(ref mut buf) = self.parse_buffer {
            parse_into(buf, statement_name.as_ref(), statement, parameters)
        } else {
            parse_into(&mut self.buf, statement_name.as_ref(), statement, parameters)
        }
    }

    /// Bind a statement to parameters and a "portal", which is a
    /// result identifier. If only one statement is executed at a
    /// time, the unnamed portal (i.e. `""`) works.
    pub fn named_bind<'b, 'c>(&'b mut self, portal_name: &'c str, statement: &'static str, parameters: &[&ToSql]) -> Portal<'b, 'a, 'c> {
        debug!("named_bind {:?} {:?}", portal_name, statement);
        let len = self.parsed.len();
        let sta = Cow::Borrowed(statement);

        let mut name_ = len;
        if let Some(&n) = self.parsed.get(&sta) {
            name_ = n
        } else {
            let name = name(len);
            self.parse(&name[..], statement, &[]);
            self.parsed.insert(sta, len);
        };
        self.bind_(portal_name, Some(name_), parameters);
        Portal { name: portal_name, buf: self }
    }

    /// Bind a statement to parameters and a "portal", which is a
    /// result identifier. If only one statement is executed at a
    /// time, the unnamed portal (i.e. `""`) works.
    pub fn bind<'b>(&'b mut self, statement: &'static str, parameters: &[&ToSql]) -> Portal<'b, 'a, 'static> {
        self.named_bind("", statement, parameters)
    }

    /// Bind a statement to parameters and a "portal", which is a
    /// result identifier. If only one statement is executed at a
    /// time, the unnamed portal (i.e. `""`) works.
    pub fn bind_unnamed<'b>(&'b mut self, statement: &str, parameters: &[&ToSql]) -> Portal<'b, 'a, 'static> {
        self.parse("", statement, parameters);
        self.bind_("", None, parameters);
        Portal { name: "", buf: self }
    }


    fn bind_(&mut self, portal_name: &str, statement: Option<usize>, parameters: &[&ToSql]) {

        // Bind
        let l0 = self.buf.len();
        self.buf.push(MSG_BIND);
        self.buf.extend(&[0, 0, 0, 0]);
        self.buf.extend(portal_name.as_bytes());
        self.buf.push(0);
        if let Some(statement) = statement {
            let name = name(statement);
            self.buf.extend(&name);
        }
        self.buf.push(0);

        // Parameter format codes
        {
            let mut diff = false;
            let mut first = None;
            let l1 = self.buf.len();
            self.buf.write_i16::<BigEndian>(parameters.len() as i16).unwrap();
            for p in parameters {
                let code = p.format_code() as i16;
                if let Some(first) = first {
                    if first != code {
                        diff = true
                    }
                } else {
                    first = Some(code)
                }
                self.buf.write_i16::<BigEndian>(code).unwrap()
            }
            match first {
                Some(p) if !diff => {
                    self.buf.resize(l1, 0);
                    self.buf.write_i16::<BigEndian>(1).unwrap();
                    self.buf.write_i16::<BigEndian>(p).unwrap();
                }
                _ => {}
            }
        }

        // Parameters
        {
            self.buf.write_i16::<BigEndian>(parameters.len() as i16).unwrap();
            for p in parameters {
                let l0 = self.buf.len();
                self.buf.extend(&[0, 0, 0, 0]);
                let is_not_null = p.write_sql(self.buf);
                let len = self.buf.len() - 4 - l0;

                if is_not_null || len > 0 {
                    BigEndian::write_i32(&mut self.buf[l0..], len as i32);
                } else {
                    BigEndian::write_i32(&mut self.buf[l0..], -1);
                }
            }
        }

        // Return values.
        self.buf.write_i16::<BigEndian>(0).unwrap(); // All return values are text

        let len = self.buf.len() - l0 - 1;
        BigEndian::write_u32(&mut self.buf[l0 + 1..], len as u32);
    }

    /// Ask the server to flush.
    pub fn flush(&mut self) {
        debug!("flush");
        let l0 = self.buf.len();
        self.buf.push(MSG_FLUSH);
        self.buf.extend(&[0, 0, 0, 0]);
        let len = self.buf.len() - l0 - 1;
        BigEndian::write_u32(&mut self.buf[l0 + 1..], len as u32);
    }


    fn execute(&mut self, destination_portal: &str, max_rows: i32) {
        let l0 = self.buf.len();
        self.buf.push(MSG_EXECUTE);
        self.buf.extend(&[0, 0, 0, 0]);
        self.buf.extend(destination_portal.as_bytes());
        self.buf.push(0);
        self.buf.write_i32::<BigEndian>(max_rows).unwrap();
        let len = self.buf.len() - l0 - 1;
        BigEndian::write_u32(&mut self.buf[l0 + 1..], len as u32);
    }

    fn close(&mut self, close: Close, s: &str) {
        let l0 = self.buf.len();
        self.buf.push(MSG_CLOSE);
        self.buf.extend(&[0, 0, 0, 0]);
        self.buf.push(close as u8);
        self.buf.extend(s.as_bytes());
        self.buf.push(0);
        let len = self.buf.len() - l0 - 1;
        BigEndian::write_u32(&mut self.buf[l0 + 1..], len as u32);
    }

    /// Close a named portal. The unnamed portal is automatically
    /// closed when a new `bind` on the unnamed portal is issued.
    fn close_portal(&mut self, s: &str) {
        self.close(Close::Portal, s)
    }
}


#[doc(hidden)]
pub fn sync(buf: &mut Vec<u8>) {
    let l0 = buf.len();
    buf.push(MSG_SYNC);
    buf.extend(&[0, 0, 0, 0]);
    let len = buf.len() - l0 - 1;
    BigEndian::write_u32(&mut buf[l0 + 1..], len as u32);
}


#[derive(Debug, Clone, Copy)]
#[repr(u8)]
enum Close {
    // Statement = b'S',
    Portal = b'P',
}
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
use std;
use futures;

error_chain!{
    foreign_links {
        Io(::std::io::Error);
        Utf8(::std::str::Utf8Error);
        Canceled(::futures::Canceled);
        Parse(::std::num::ParseIntError);
    }
    errors {
        Send {
        };
        Protocol {

        };
        NoAddr {

        };
        Postgres(message: String) {

        };
        Timeout {};
    }
}
/*
/// Errors.
#[derive(Debug)]
pub enum Error {
    /// IO error
    IO(std::io::Error),
    /// UTF8 parse error
    Utf8(std::str::Utf8Error),
    /// Error sending a request to the connection.
    Send,
    /// Communication with the connection was canceled.
    Canceled(futures::Canceled),
    /// A protocol error.
    Protocol,
    /// There was an integer parse error.
    Parse(std::num::ParseIntError),
    /// The supplied network address is invalid.
    NoAddr,
    /// An SQL error happened.
    Postgres {
        /// Error message returned by the server.
        message: String,
    },
    /// The connection timed out.
    Timeout
}

/// A specialized version of `futures::finished` with a known error type.
pub fn finished<T>(t: T) -> futures::Finished<T, Error> {
    futures::finished(t)
}

impl std::convert::From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::IO(e)
    }
}

impl std::convert::From<std::str::Utf8Error> for Error {
    fn from(e: std::str::Utf8Error) -> Self {
        Error::Utf8(e)
    }
}

impl std::convert::From<std::num::ParseIntError> for Error {
    fn from(e: std::num::ParseIntError) -> Self {
        Error::Parse(e)
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::IO(ref e) => e.description(),
            Error::Send => "Send error",
            Error::Canceled(ref e) => e.description(),
            Error::Utf8(ref e) => e.description(),
            Error::Parse(ref e) => e.description(),
            Error::Protocol => "Protocol error",
            Error::NoAddr => "No network address",
            Error::Postgres { ref message } => message,
            Error::Timeout => "Timeout"
        }
    }
    fn cause(&self) -> Option<&std::error::Error> {
        match *self {
            Error::IO(ref e) => Some(e),
            Error::Send => None,
            Error::Canceled(ref e) => Some(e),
            Error::Utf8(ref e) => Some(e),
            Error::Parse(ref e) => Some(e),
            Error::Protocol => None,
            Error::NoAddr => None,
            Error::Postgres { .. } => None,
            Error::Timeout => None
        }
    }
}
impl std::fmt::Display for Error {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        let x: &std::fmt::Debug = self;
        x.fmt(fmt)
    }
}


impl<R> std::convert::From<futures::sync::mpsc::SendError<R>> for Error {
    fn from(_: futures::sync::mpsc::SendError<R>) -> Self {
        Error::Send
    }
}

impl std::convert::From<futures::Canceled> for Error {
    fn from(e: futures::Canceled) -> Self {
        Error::Canceled(e)
    }
}
*/























































































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
//! extern crate tokio_core;
//!     let mut l = tokio_core::reactor::Core::new().unwrap();
extern crate tokio_core;
#[macro_use]
extern crate error_chain;
pub mod error {
    error_chain!{
        foreign_links {
            Io(::std::io::Error);
            Utf8(::std::str::Utf8Error);
            Parse(::std::num::ParseIntError);
            Openssl(::openssl::ssl::Error);
            OpensslStack(::openssl::error::ErrorStack);
            Canceled(::futures::Canceled);
        errors {
            /// A protocol error.
            Protocol {
                description("Postgres protocol error")
            }
            /// The supplied network address is invalid.
            NoAddr {
                description("The supplied network address is invalid")
            }
            /// An SQL error happened.
            Postgres(message: String) {
                description("The server returned an error")
                    display("The server returned an error: {}", message)
            /// The connection timed out.
            Timeout {
                description("The connection timed out")
            }
            /// No particular error
            Unit {}
            /// SSL connection denied
            SSLDenied {}
pub use error::{Error, ErrorKind};
        ErrorKind::Unit.into()
        ErrorKind::Unit.into()
/// options. The connection is unencrypted.
    handle: tokio_core::reactor::Handle,
    fn new(handle: tokio_core::reactor::Handle, stream: W, parameters: P, parsed_queries: HashMap<Cow<'static, str>, usize>) -> Connecting<W, P> {
            handle,
    fn rows<F: HandleRow>(self, f: F, timeout: Option<tokio_core::reactor::Timeout>) -> Result<Rows<W, F, P>, Error> {
    fn timeout(&self) -> Result<tokio_core::reactor::Timeout, Error> {
        Ok(tokio_core::reactor::Timeout::new(
            self.parameters.as_ref().idle_timeout.unwrap_or(std::time::Duration::from_secs(10)),
            &self.handle,
        )?)
        let timeout = self.timeout()?;
                            return Err(ErrorKind::Postgres(into).into())
    Err(ErrorKind::Protocol.into())
            return Err(ErrorKind::Protocol.into());
                            // self.state = Some(read_length(stream, buf));
                            return Err(ErrorKind::Postgres(into).into())
    sender: futures::sync::mpsc::UnboundedSender<(R, futures::sync::oneshot::Sender<Result<R, Error>>)>,
                    match self.sender.start_send((r, send))? {
                        AsyncSink::NotReady((r, send)) => {
    use tokio_core;
            addr: "::1:5432".to_socket_addrs().unwrap().next().unwrap(),
        let mut l = tokio_core::reactor::Core::new().unwrap();

        let db:Handle<Request> =
            spawn_connection(p.clone(), l.handle()).unwrap();
        println!("spawned");
        l.run(db
              .send_request(
                  Request { login: "me".to_string(), id: None }
              )
              .and_then(|dbreq| {
                  if let Some(ref id) = dbreq.id {
                      println!("id: {:?}", id)
                  }
                  futures::finished(())
              })).unwrap()
        let mut l = tokio_core::reactor::Core::new().unwrap();
        let db:Handle<Request> = spawn_connection(p.clone(), l.handle()).unwrap();
        println!("spawned");
        l.run(db
              .send_request(
                  Request { login: "me".to_string(), id: None }
              )
              .and_then(|dbreq| {
                  if let Some(ref id) = dbreq.id {
                      println!("id: {:?}", id)
                  }
                  futures::finished(())
              })).unwrap()
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
#![deny(trivial_casts,
        unstable_features,
        unused_import_braces)]
#![recursion_limit = "128"]
//! A fully-asynchronous Postgres client. Postgres has a notion of
//! "statements", which are named or unnamed SQL commands, and of
//! "portals", where a portal is an instance of a result. All queries
//! to the database follow the same sequence: parse, bind, execute,
//! close (portal and/or statement).
//!
//! Both statements and portals can be named or unnamed, although
//! prototype code might be easier to write using only the `query`
//! method of the `Connection` type, which does the correct sequence
//! using the unnamed statement and unnamed portal.
//!
//! Contrarily to synchronous clients, this client needs to store
//! requests in the event loop while doing asynchronous I/O. The
//! precise type for this storage needs to be provided by the user of
//! this crate, and needs to implement both the `Request` and
//! `HandleRow` traits.
//!
//! This crate provides two API levels:
//!
//! - A higher-level one based using `spawn_connection`, which uses an
//! existing event loop. This API requires an existing instance of
//! `Request+HandleRow`.
//!
//! - A lower-level one based on the `Connection` type, which might be
//! used to build more complex, or more direct pipelines, such as
//! tunneling through another protocol, or waiting for a query to be
//! executed by the server.
//!
//!
//! ```
//! extern crate tokio;
//! extern crate pleingres;
//! extern crate futures;
//! extern crate env_logger;
//! extern crate uuid;
//!
//! use uuid::Uuid;
//! use std::rc::Rc;
//! use std::net::ToSocketAddrs;
//! use futures::Future;
//!
//! // A `Request` is the type used for communication with the
//! // client event loop. It is used both for sending input and
//! // receiving output.
//!
//! struct Request {
//!     login: String,
//!     id: Option<Uuid>
//! }
//!
//! // Requests must implement the `pleingres::Request` trait,
//! // meaning they can be converted to commands to be sent to
//! // the server.
//! impl pleingres::Request for Request {
//!     fn request(&mut self, mut buf: pleingres::Buffer) {
//!         buf.bind("SELECT id FROM users WHERE login=$1", &[&self.login]).execute(0);
//!     }
//! }
//!
//! impl pleingres::HandleRow for Request {
//!     fn row(&mut self, mut row: pleingres::Row) -> bool {
//!         if let Some(id) = row.next() {
//!            self.id = Some(pleingres::FromSql::from_sql(id).unwrap())
//!         }
//!         true
//!     }
//! }
//!
//! fn main() {
//!     env_logger::try_init().unwrap_or(());
//!     let p = Rc::new(pleingres::Parameters {
//!         addr: "::1:5432".to_socket_addrs().unwrap().next().unwrap(),
//!         user: "pe".to_string(),
//!         password: "password".to_string(),
//!         database: Some("pijul".to_string()),
//!         idle_timeout: Some(std::time::Duration::from_millis(20_000)),
//!         tcp_keepalive: Some(std::time::Duration::from_millis(10000)),
//!         ssl: None,
//!     });
//!     let mut l = tokio::reactor::Core::new().unwrap();
//!
//!     let db:pleingres::Handle<Request> =
//!         pleingres::spawn_connection(p.clone(), l.handle()).unwrap();
//!     l.run(db
//!           .send_request(
//!             Request { login: "me".to_string(), id: None }
//!           )
//!           .and_then(|dbreq| {
//!               if let Some(ref id) = dbreq.id {
//!                   println!("id: {:?}", id)
//!               }
//!               futures::finished(())
//!           })).unwrap()
//! }
//! ```
//!
//! Alternatively, the `pleingres::Request` can be implemented using
//! the sql plugin. On the above example, we would replace
//!
//! ``` ignore
//! struct Request {
//!     login: String,
//!     id: Option<Uuid>
//! }
//!
//! impl pleingres::Request for Request {
//!     fn request(&mut self, mut buf: pleingres::Buffer) {
//!         buf.bind("SELECT id FROM users WHERE login=$1", &[&self.login]).execute(0);
//!     }
//! }
//! ```
//!
//! With just
//!
//! ``` ignore
//! #[sql("SELECT id FROM users WHERE login = $login")]
//! struct Request {
//!     login: String,
//!     id: Option<Uuid>
//! }
//! ```

extern crate futures;
extern crate tokio;
#[macro_use]
extern crate log;
extern crate byteorder;
extern crate md5;
extern crate uuid;
extern crate chrono;
extern crate digest;
#[macro_use]
extern crate serde_derive;
#[cfg(test)]
extern crate env_logger;
extern crate tokio_openssl;
extern crate bytes;
extern crate openssl;
extern crate tokio_io;
extern crate tokio_timer;

use byteorder::{WriteBytesExt, BigEndian, ByteOrder};

use std::io::Write;
use tokio_io::io::{ReadHalf, WriteHalf, read_exact, ReadExact};
use tokio_io::{AsyncRead, AsyncWrite};
use std::net::SocketAddr;
use std::time::Duration;
use std::collections::HashMap;

use futures::{Future, Async, Sink};

const MAJOR_VERSION: u16 = 3;
const MINOR_VERSION: u16 = 0;

mod statement;
pub use statement::*;

mod rows;
pub use rows::*;

#[allow(missing_docs)]
mod msg;
use msg::*;

mod buffer;
pub use buffer::*;

mod spawned;
pub use spawned::*;


#[derive(Debug)]
pub enum Error {
    Io(::std::io::Error),
    Utf8(::std::str::Utf8Error),
    Parse(::std::num::ParseIntError),
    Openssl(::openssl::ssl::Error),
    OpensslStack(::openssl::error::ErrorStack),
    Canceled(::futures::Canceled),
    /// A protocol error.
    Protocol,
    /// The supplied network address is invalid.
    NoAddr,
    /// An SQL error happened.
    Postgres { message: String },
    /// The connection timed out.
    Timeout,
    /// No particular error
    Unit,
    /// SSL connection denied
    SSLDenied,
}


impl std::error::Error for Error {

    fn description(&self) -> &str {
        use Error::*;
        match *self {
            Io(ref e) => e.description(),
            Utf8(ref e) => e.description(),
            Parse(ref e) => e.description(),
            Openssl(ref e) => e.description(),
            OpensslStack(ref e) => e.description(),
            Canceled(ref e) => e.description(),
            Protocol => "Postgres protocol error",
            NoAddr => "The supplied network address is invalid",
            Postgres { .. } =>"The server returned an error",
            Timeout => "The connection timed out",
            Unit => "Other error",
            SSLDenied => "SSL connection denied",
        }
    }

    fn cause(&self) -> Option<&std::error::Error> {
        use Error::*;
        match *self {
            Io(ref e) => Some(e),
            Utf8(ref e) => Some(e),
            Parse(ref e) => Some(e),
            Openssl(ref e) => Some(e),
            OpensslStack(ref e) => Some(e),
            Canceled(ref e) => Some(e),
            _ => None
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        use Error::*;
        match *self {
            Io(ref e) => e.fmt(fmt),
            Utf8(ref e) => e.fmt(fmt),
            Parse(ref e) => e.fmt(fmt),
            Openssl(ref e) => e.fmt(fmt),
            OpensslStack(ref e) => e.fmt(fmt),
            Canceled(ref e) => e.fmt(fmt),
            Protocol => write!(fmt, "Postgres protocol error"),
            NoAddr => write!(fmt, "The supplied network address is invalid"),
            Postgres { ref message } => {
                write!(fmt, "The server returned an error: {}", message)
            }
            Timeout => write!(fmt, "The connection timed out"),
            Unit => write!(fmt, "Other error"),
            SSLDenied => write!(fmt, "SSL connection denied"),
        }
    }
}



impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

impl From<openssl::error::ErrorStack> for Error {
    fn from(e: openssl::error::ErrorStack) -> Self {
        Error::OpensslStack(e)
    }
}

impl From<openssl::ssl::Error> for Error {
    fn from(e: openssl::ssl::Error) -> Self {
        Error::Openssl(e)
    }
}

impl From<std::num::ParseIntError> for Error {
    fn from(e: std::num::ParseIntError) -> Self {
        Error::Parse(e)
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(e: std::str::Utf8Error) -> Self {
        Error::Utf8(e)
    }
}

impl From<futures::Canceled> for Error {
    fn from(e: futures::Canceled) -> Self {
        Error::Canceled(e)
    }
}

unsafe impl Send for Error {}


impl std::convert::From<()> for Error {
    fn from(_: ()) -> Self {
        Error::Unit
    }
}

impl<E> std::convert::From<futures::sync::mpsc::SendError<E>> for Error {
    fn from(_: futures::sync::mpsc::SendError<E>) -> Self {
        Error::Unit.into()
    }
}


trait WritePostgresExt {
    fn write_string(&mut self, s: &[u8]) -> std::io::Result<()>;
}

impl<W: Write> WritePostgresExt for W {
    fn write_string(&mut self, s: &[u8]) -> std::io::Result<()> {
        assert!(s.iter().all(|&c| c != 0));
        try!(self.write(s));
        try!(self.write(&[0]));
        Ok(())
    }
}


#[derive(Default, Serialize, Deserialize)]
/// A serializable version of `Parameters`, for inclusion in
/// configuration files.
pub struct ConfigFile {
    /// PostgreSQL user.
    pub user: String,
    /// Password.
    pub password: String,
    /// Database name.
    pub db: String,
    /// Network address of the server.
    pub addr: String,
    /// TCP keepalive interval, defaults to no keep alive (in milliseconds).
    pub tcp_keepalive: Option<u32>,
    /// Time to wait before reconnecting an idle connection (in milliseconds).
    pub idle_timeout: Option<u64>,
    /// SSL parameters
    pub ssl: Option<SSLConfigFile>
}

#[derive(Default, Serialize, Deserialize)]
pub struct SSLConfigFile {
    pub ca_root: Option<String>,
    pub private_key: Option<String>,
    pub hostname: Option<String>,
}

impl ConfigFile {
    /// Convert a configuration file to parameters.
    pub fn to_parameters(&self) -> Result<Parameters, Error> {
        use std::net::ToSocketAddrs;
        let addr = self
            .addr
            .to_socket_addrs()
            .expect("invalid pleingres socket address")
            .next()
            .expect("no pleingres socket address");
        Ok(Parameters {
            addr,
            user: self.user.to_string(),
            password: self.password.to_string(),
            database: Some(self.db.to_string()),
            tcp_keepalive: self.tcp_keepalive.map(|x| std::time::Duration::from_millis(x as u64)),
            idle_timeout: self.idle_timeout.map(Duration::from_millis),
            ssl: if let Some(ref ssl) = self.ssl {
                use openssl::ssl::{SslMethod, SslConnector};
                let mut connector = SslConnector::builder(SslMethod::tls()).unwrap();
                if let Some(ref ca_root) = ssl.ca_root {
                    connector.set_ca_file(ca_root)?
                }
                if let Some(ref client_pk) = ssl.private_key {
                    connector.set_private_key_file(
                        client_pk,
                        openssl::ssl::SslFiletype::PEM,
                    )?
                }
                let connector = connector.build();
                Some(SSLParameters {
                    config: connector,
                    hostname: ssl.hostname.clone(),
                })
            } else {
                None
            }
        })
    }
}



/// Connection configuration: network address, user, database and
/// options.
///
/// The implementation of `Default` connects to the PostgreSQL server
/// on localhost. The minimum parameter that should be added for it to
/// work is a database name.
///
/// ```
/// Parameters { database: Some("database".to_string()), .. Parameters::default() }
/// ```
pub struct Parameters {
    /// Network address of the server
    pub addr: SocketAddr,
    /// User name on the server
    pub user: String,
    /// Password for that user
    pub password: String,
    /// Database to connect to
    pub database: Option<String>,
    /// TCP keep alive, in milliseconds.
    pub tcp_keepalive: Option<std::time::Duration>,
    /// Duration before reconnecting an idle connection.
    pub idle_timeout: Option<Duration>,
    /// SSL client certificate
    pub ssl: Option<SSLParameters>,
}

impl Default for Parameters {
    fn default() -> Self {
        use std::net::ToSocketAddrs;
        Parameters {
            addr: "localhost:5432".to_socket_addrs().unwrap().next().unwrap(),
            user: String::new(),
            password: String::new(),
            database: None,
            idle_timeout: None,
            tcp_keepalive: None,
            ssl: None,
        }
    }
}

pub struct SSLParameters {
    pub config: openssl::ssl::SslConnector,
    pub hostname: Option<String>,
}

enum ReadState<W: AsyncRead> {
    ReadLength(ReadExact<ReadHalf<W>, Vec<u8>>),
    Read {
        msg: u8,
        body: ReadExact<ReadHalf<W>, Vec<u8>>,
    },
}
enum WriteState<W: AsyncWrite> {
    Idle { w: WriteHalf<W>, buf: Vec<u8> },
    Write { w: tokio_io::io::WriteAll<WriteHalf<W>, Vec<u8>> },
    Flush { flush: tokio_io::io::Flush<WriteHalf<W>>, buf: Vec<u8> },
}

use std::borrow::Cow;

/// An active connection to a database.
pub struct Connection<W: AsyncWrite + AsyncRead, P: AsRef<Parameters>> {
    parameters: P,
    // columns: Vec<Column>,
    write: Option<WriteState<W>>,
    read: Option<ReadState<W>>,
    ready_for_query: bool,
    // state: Option<State<W>>,
    process_id: Option<i32>,
    secret_key: Option<i32>,
    parsed_queries: HashMap<Cow<'static, str>, usize>,
}

/// A future ultimately resolving into an established connection.
struct Connecting<W: AsyncWrite + AsyncRead, P: AsRef<Parameters>>(Option<Connection<W, P>>);

impl<W: AsyncWrite + AsyncRead, P:AsRef<Parameters>+Send> Future for Connecting<W, P> {
    type Item = Connection<W, P>;
    type Error = Error;

    fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
        loop {
            debug!("connecting poll");
            if let Some(ref mut c) = self.0 {
                if let Async::NotReady = c.poll_connecting()? {
                    return Ok(Async::NotReady)
                }
            }
            return Ok(Async::Ready(self.0.take().unwrap()))
        }
    }
}


const AUTH_MD5_PASSWORD: u32 = 5;
const AUTH_OK: u32 = 0;

/// A readiness signal sent by the server.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(u8)]
pub enum Wait {
    /// The last statement was executed.
    CommandComplete = b'C',

    /// The last parse command is done.
    Parse = b'1',

    /// The last bind command is done.
    Bind = b'2',

    /// The server is ready for the next query.
    Ready = b'Z',

    /// The last close command was completed.
    CloseComplete = b'3',
}


fn read_length<A: AsyncRead>(stream: ReadHalf<A>, mut buf: Vec<u8>) -> ReadState<A> {
    buf.resize(5, 0);
    ReadState::ReadLength(read_exact(stream, buf))
}

fn read<A: AsyncRead>(stream: ReadHalf<A>, mut buf: Vec<u8>) -> ReadState<A> {
    let msg = buf[0];
    let n = BigEndian::read_u32(&buf[1..]) as usize;
    debug!("n = {:?}", n);
    buf.resize(n - 4, 0);
    ReadState::Read {
        msg: msg,
        body: read_exact(stream, buf),
    }
}


/// Future resolving to the connection once a command has been sent to the server.
pub struct WriteFuture<W: AsyncWrite + AsyncRead, P: AsRef<Parameters>>(Option<Connection<W, P>>);

impl<W: AsyncWrite + AsyncRead, P: AsRef<Parameters>+Send> Connection<W, P> {
    /// Starts a connection on the given stream (usually a socket, but
    /// other instances of `Write`, such as a tunnel, work too). This
    /// function returns a future resolving into an established
    /// connection.
    fn new(stream: W, parameters: P, parsed_queries: HashMap<Cow<'static, str>, usize>) -> Connecting<W, P> {
        let mut v = Vec::new();
        v.extend(&[0, 0, 0, 0]); // Length
        v.write_u16::<BigEndian>(MAJOR_VERSION).unwrap();
        v.write_u16::<BigEndian>(MINOR_VERSION).unwrap();
        v.write_string(b"user").unwrap();
        v.write_string(parameters.as_ref().user.as_bytes()).unwrap();
        if let Some(ref database) = parameters.as_ref().database {
            v.write_string(b"database").unwrap();
            v.write_string(database.as_bytes()).unwrap();
        }
        // if let Some(ref options) = parameters.options {
        // v.write_string(b"options").unwrap();
        // v.write_string(options.as_bytes()).unwrap();
        // }
        v.write(&[0]).unwrap();
        let len = v.len() as u32;
        BigEndian::write_u32(&mut v, len);
        let (read_half, write_half) = stream.split();
        Connecting(Some(Connection {
            write: Some(WriteState::Write { w: tokio_io::io::write_all(write_half, v) }),
            read: Some(read_length(read_half, Vec::new())),
            ready_for_query: false,
            parameters: parameters,
            // columns: Vec::new(),
            process_id: None,
            secret_key: None,
            parsed_queries: parsed_queries,
        }))
    }


    fn rows<F: HandleRow>(self, f: F, timeout: Option<tokio_timer::Delay>) -> Result<Rows<W, F, P>, Error> {
        // let timeout = Timeout::new(self.parameters.max_wait, &self.handle)?;
        Ok(Rows {
            connection: Some((self, f)),
            timeout,
            last_row_was_halted: false,
        })
    }

    fn timeout(&self) -> tokio_timer::Delay {
        tokio_timer::Delay::new(
            std::time::Instant::now() + self.parameters.as_ref().idle_timeout.unwrap_or(std::time::Duration::from_secs(10))
        )
    }

    /// Perform a complete query, i.e. parse, bind and execute the statement.
    pub fn query<F: HandleRow>(mut self, q: &'static str, args: &[&ToSql], f: F) -> Result<Rows<W, F, P>, Error> {
        {
            let mut buf = self.buffer();
            buf.bind(q, args).execute(0);
        }
        match self.write.take() {
            Some(WriteState::Idle { w, buf }) => {
                self.write = Some(WriteState::Write { w: tokio_io::io::write_all(w, buf) });
            }
            _ => unreachable!()
        }
        let timeout = self.timeout();
        Ok(self.rows(f, Some(timeout))?)
    }

    /// Write the current buffer to this connection. The resulting
    /// future resolves into `self` once the message has been written.
    pub fn write(mut self) -> WriteFuture<W, P> {
        match self.write.take() {
            Some(WriteState::Idle { w, buf }) => {
                self.write = Some(WriteState::Write { w: tokio_io::io::write_all(w, buf) });
                WriteFuture(Some(self))
            }
            _ => unreachable!()
        }
    }

    fn poll_connecting(&mut self) -> Result<Async<()>, Error> {

        // First write anything that needs to be written.
        loop {
            match self.write.take() {
                Some(WriteState::Write { mut w }) => {
                    debug!("write {}: {}", file!(), line!());
                    let (stream, buf) = match w.poll()? {
                        Async::Ready(s) => s,
                        Async::NotReady => {
                            self.write = Some(WriteState::Write { w });
                            return Ok(Async::NotReady);
                        }
                    };
                    self.write = Some(WriteState::Flush { flush: tokio_io::io::flush(stream), buf });
                    continue
                }
                Some(WriteState::Flush { mut flush, buf }) => {
                    debug!("flush {}: {}", file!(), line!());
                    let w = match flush.poll()? {
                        Async::Ready(s) => s,
                        Async::NotReady => {
                            self.write = Some(WriteState::Flush { flush, buf });
                            return Ok(Async::NotReady);
                        }
                    };
                    self.write = Some(WriteState::Idle { w, buf });
                }
                Some(idle) => self.write = Some(idle),
                None => unreachable!(),
            }

            match self.read.take() {
                Some(ReadState::ReadLength(mut r)) => {
                    debug!("readlength: {} {}", file!(), line!());
                    match r.poll()? {
                        Async::Ready((connection, buffer)) => {
                            self.read = Some(read(connection, buffer));
                        },
                        Async::NotReady => {
                            self.read = Some(ReadState::ReadLength(r));
                            return Ok(Async::NotReady);
                        }
                    }
                }
                Some(ReadState::Read { msg, mut body }) => {
                    debug!("read {} {}", line!(), msg as char);
                    let (stream, buf) = match body.poll()? {
                        Async::Ready(s) => s,
                        Async::NotReady => {
                            self.read = Some(ReadState::Read {
                                msg: msg,
                                body: body,
                            });
                            return Ok(Async::NotReady);
                        }
                    };

                    debug!("poll connecting, read, {:?}", buf);
                    match msg {
                        MSG_AUTH => {
                            self.auth_request(&buf);
                            self.read = Some(read_length(stream, buf));
                        }
                        MSG_PARAMETER_STATUS => {
                            try!(parameter_status(&buf));
                            self.read = Some(read_length(stream, buf));
                        }
                        MSG_BACKEND_KEY_DATA => {
                            self.backend_key_data(&buf);
                            self.read = Some(read_length(stream, buf));
                        }
                        MSG_READY_FOR_QUERY => {
                            debug!("ready for query");
                            self.ready_for_query = true;
                            self.read = Some(read_length(stream, buf));
                            return Ok(Async::Ready(()))
                        }
                        MSG_ERROR => {
                            let mut into = String::new();
                            error(&buf, &mut into)?;
                            // self.state = Some(read_length(stream, buf));
                            // Ok(Async::Ready(true))
                            return Err(Error::Postgres { message: into })
                        }
                        msg => {
                            debug!("unknown message {:?}", msg);
                            self.read = Some(read_length(stream, buf));
                        }
                    }
                },
                None => unreachable!()
            }
        }
    }

    fn auth_request(&mut self, read_buf: &[u8]) {
        // Authentication request.
        match self.write.take() {
            Some(WriteState::Idle { w, mut buf }) => {
                debug!("auth request: buf: {:?}", buf);
                let auth_type = BigEndian::read_u32(&read_buf[..]);
                match auth_type {
                    AUTH_OK => {
                        debug!("auth ok");
                        self.write = Some(WriteState::Idle { w, buf })
                    }
                    AUTH_MD5_PASSWORD => {
                        debug!("md5 password");

                        let md5 = md5(&read_buf[4..],
                                      self.parameters.as_ref().user.as_bytes(),
                                      self.parameters.as_ref().password.as_bytes());
                        buf.clear();
                        buf.push(MSG_PASSWORD);
                        buf.extend(&[0, 0, 0, 0]);
                        buf.extend(b"md5");
                        for i in md5.iter() {
                            let i = *i as usize;
                            buf.push(HEX[i >> 4]);
                            buf.push(HEX[i & 0xf]);
                        }
                        buf.push(0);
                        let len = buf.len() - 1;
                        BigEndian::write_u32(&mut buf[1..], len as u32);
                        self.write = Some(WriteState::Write { w: tokio_io::io::write_all(w, buf) })
                    }
                    t => panic!("auth {:?} not implemented", t),
                }
            },
            _ => {}
        }
    }

    fn backend_key_data(&mut self, buf: &[u8]) {
        self.process_id = Some(BigEndian::read_i32(&buf[..]));
        self.secret_key = Some(BigEndian::read_i32(&buf[4..]));
    }
}

fn parameter_status(buf: &[u8]) -> Result<(), Error> {
    if let Some(i) = (&buf[..]).iter().position(|&x| x == 0) {

        if let Some(j) = (&buf[i + 1..]).iter().position(|&x| x == 0) {
            debug!("parameter status: {:?}", std::str::from_utf8(&buf[..i]));
            debug!("parameter status: {:?}",
                   std::str::from_utf8(&buf[i + 1..i + 1 + j]));
            return Ok(());
        }
    }
    Err(Error::Protocol)
}

fn error(buf: &[u8], into: &mut String) -> Result<(), Error> {
    let mut i = 0;
    while i < buf.len() && buf[i] != 0 {
        if let Some(j) = (&buf[i + 1..]).iter().position(|&x| x == 0) {
            let s = std::str::from_utf8(&buf[i + 1..i + 1 + j]);
            error!("Error: {:?}", s);
            into.push_str(s.unwrap());
            into.push('\n');
            i += j + 2
        } else {
            return Err(Error::Protocol);
        }
    }
    Ok(())
}

impl<W: AsyncWrite + AsyncRead, P:AsRef<Parameters>> Future for WriteFuture<W, P> {
    type Item = Connection<W, P>;
    type Error = Error;

    fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
        loop {
            debug!("writefuture poll");
            let is_flushed = if let Some(ref mut c) = self.0 {
                match c.write.take() {
                    Some(WriteState::Write { mut w }) => {
                        match try!(w.poll()) {
                            Async::Ready((stream, buf)) => {
                                debug!("written buf = {:?}", buf);
                                c.write = Some(WriteState::Flush {
                                    flush: tokio_io::io::flush(stream),
                                    buf
                                });
                                false
                            }
                            Async::NotReady => {
                                c.write = Some(WriteState::Write { w });
                                return Ok(Async::NotReady);
                            }
                        }
                    }
                    Some(WriteState::Flush { mut flush, buf }) => {
                        match try!(flush.poll()) {
                            Async::Ready(w) => {
                                c.write = Some(WriteState::Idle { w, buf });
                                true
                            },
                            Async::NotReady => {
                                c.write = Some(WriteState::Flush { flush, buf });
                                return Ok(Async::NotReady);
                            }
                        }
                    }
                    _ => unreachable!(),
                }
            } else {
                false
            };

            if is_flushed {
                return Ok(Async::Ready(self.0.take().unwrap()));
            }
        }
    }
}

/// A future driving the connected connection. Never yields anything.
impl<W: AsyncWrite + AsyncRead, P:AsRef<Parameters>> Future for Connection<W, P> {
    type Item = ();
    type Error = Error;
    fn poll(&mut self) -> Result<Async<()>, Error> {
        loop {
            match self.write.take() {
                Some(WriteState::Write { mut w }) => {
                    match try!(w.poll()) {
                        Async::Ready((stream, buf)) => {
                            self.write = Some(WriteState::Flush {
                                flush: tokio_io::io::flush(stream),
                                buf
                            });
                            continue
                        },
                        Async::NotReady => {
                            self.write = Some(WriteState::Write { w });
                            return Ok(Async::NotReady);
                        }
                    }
                }
                Some(WriteState::Flush{ mut flush, buf }) => {
                    match try!(flush.poll()) {
                        Async::Ready(w) => {
                            self.write = Some(WriteState::Idle { w, buf })
                        },
                        Async::NotReady => {
                            self.write = Some(WriteState::Flush { flush, buf });
                            return Ok(Async::NotReady);
                        }
                    }
                }
                Some(state) => self.write = Some(state),
                None => unreachable!(),
            }

            debug!("connection poll");
            match self.read.take() {
                Some(ReadState::ReadLength(mut r)) => {
                    match r.poll()? {
                        Async::Ready((connection, buffer)) => {
                            self.read = Some(read(connection, buffer));
                        },
                        Async::NotReady => {
                            self.read = Some(ReadState::ReadLength(r));
                            return Ok(Async::NotReady);
                        }
                    }
                }
                Some(ReadState::Read { msg, mut body }) => {

                    let (stream, buf) = match try!(body.poll()) {
                        Async::Ready(s) => s,
                        Async::NotReady => {
                            self.read = Some(ReadState::Read {
                                msg: msg,
                                body: body,
                            });
                            return Ok(Async::NotReady);
                        }
                    };

                    match msg {
                        MSG_ERROR => {
                            let mut into = String::new();
                            try!(error(&buf, &mut into));
                            self.read = Some(read_length(stream, buf));
                            // Ok(Async::Ready(true))
                            // return Err(Error::Postgres { message: into })
                        }
                        msg => {
                            debug!("unknown message {:?}", msg as char);
                            self.read = Some(read_length(stream, buf));
                        }
                    }
                }
                None => unreachable!(),
            }
        }
    }
}

const HEX: &'static [u8] = b"0123456789abcdef";
fn md5(salt: &[u8], user: &[u8], password: &[u8]) -> [u8; 16] {

    let mut md5 = md5::Context::new();
    md5.consume(password);
    md5.consume(user);

    let output = md5.compute();

    let mut md5 = md5::Context::new();
    for i in output.iter() {
        let i = *i as usize;
        md5.consume(&[HEX[i >> 4], HEX[i & 0xf]])
    }
    md5.consume(salt);
    md5.compute().0
}

#[test]
fn test_md5() {
    let salt = [0xc4, 0x4e, 0x74, 0x12];
    let md5 = md5(&salt[..], b"pe", b"password");
    let mut v = Vec::new();
    for i in md5.iter() {
        let i = *i as usize;
        v.push(HEX[i >> 4]);
        v.push(HEX[i & 0xf]);
    }
    assert_eq!(&v[..], b"66008dc01e22d8e920e0458c43584d9e")
}

/// Types that can be converted to postgres commands.
pub trait Request {
    /// Translate this request into a sequence of Postgres commands.
    fn request(&mut self, buf: &mut Buffer);
}

pub trait SubRequest<R>: Sized {
    fn from(self) -> R;
    fn try_into(r: R) -> Result<Self, R>;
}

pub trait SuperRequest<R>: Sized {
    fn from(r: R) -> Self;
    fn try_into(self) -> Result<R, Self>;
}


impl Request for String {
    fn request(&mut self, buf: &mut Buffer) {
        buf.bind_unnamed(self, &[]).execute(0)
    }
}

impl HandleRow for String {}

use futures::sync::oneshot::Sender;

enum SendState<R> {
    Init(R, Sender<Result<R, Error>>),
    Sending,
    Receiving,
}

/// A future ultimately resolving to a processed request.
pub struct SendRequest<R> {
    sender: futures::sync::mpsc::UnboundedSender<Option<(R, futures::sync::oneshot::Sender<Result<R, Error>>)>>,
    receiver: futures::sync::oneshot::Receiver<Result<R, Error>>,
    state: Option<SendState<R>>,
}

use futures::AsyncSink;


impl<R> Future for SendRequest<R> {
    type Item = R;
    type Error = Error;
    fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> {
        loop {
            debug!("send request poll");
            match self.state.take() {
                Some(SendState::Init(r, send)) => {
                    debug!("state init");
                    match self.sender.start_send(Some((r, send)))? {
                        AsyncSink::NotReady(Some((r, send))) => {
                            self.state = Some(SendState::Init(r, send));
                            return Ok(Async::NotReady);
                        }
                        AsyncSink::Ready => {
                            self.state = Some(SendState::Sending)
                        }
                        AsyncSink::NotReady(None) => unreachable!()
                    }
                }
                Some(SendState::Sending) => {
                    debug!("state sending");
                    match self.sender.poll_complete()? {
                        Async::NotReady => {
                            self.state = Some(SendState::Sending);
                            return Ok(Async::NotReady);
                        }
                        Async::Ready(()) => {
                            self.state = Some(SendState::Receiving);
                        }
                    }
                }
                Some(SendState::Receiving) => {
                    debug!("state receiving");
                    match self.receiver.poll()? {
                        Async::NotReady => {
                            debug!("not ready");
                            self.state = Some(SendState::Receiving);
                            return Ok(Async::NotReady);
                        }
                        Async::Ready(r) => {
                            debug!("ready: {:?}", r.is_ok());
                            return Ok(Async::Ready(try!(r)))
                        },
                    }
                }
                None => panic!("sendstate polled after completion"),
            }
        }
    }
}


#[cfg(test)]
mod test {
    use tokio;
    use super::*;
    use futures;
    use env_logger;
    use uuid::Uuid;

    #[test]
    fn basic_connection() {

        use std::sync::Arc;
        use std::net::ToSocketAddrs;
        use futures::Future;

        // A `Request` is the type used for communication with the
        // client event loop. It is used both for sending input and
        // receiving output.

        #[derive(Debug)]
        struct Request {
            login: String,
            id: Option<Uuid>
        }

        // Requests must implement the `pleingres::Request` trait,
        // meaning they can be converted to commands to be sent to
        // the server.
        impl super::Request for Request {
            fn request(&mut self, buf: &mut Buffer) {
                buf.bind("SELECT id FROM users WHERE login=$1", &[&self.login])
                   .execute(0);
            }
        }

        impl HandleRow for Request {
            fn row(&mut self, mut row: Row) -> bool {
                if let Some(id_) = row.next() {
                    debug!("{:?}", std::str::from_utf8(id_));
                    let id_ = std::str::from_utf8(id_)
                        .unwrap().parse().unwrap();
                    self.id = Some(id_)
                }
                true
            }
        }
        env_logger::try_init().unwrap_or(());

        let p = Arc::new(Parameters {
            addr: "127.0.0.1:5432".to_socket_addrs().unwrap().next().unwrap(),
            user: "pe".to_string(),
            password: "password".to_string(),
            database: Some("pijul".to_string()),
            idle_timeout: Some(std::time::Duration::from_millis(20_000)),
            tcp_keepalive: Some(std::time::Duration::from_millis(10000)),
            ssl: None,
        });
        // let mut rt = tokio::runtime::Runtime::new().unwrap();
        tokio::run(futures::lazy(move || {
            let db:Handle<Request> = spawn_connection(p.clone()).unwrap();
            db
                .send_request(
                    Request { login: "me".to_string(), id: None }
                )
                .and_then(move |dbreq| {
                    debug!("{:?}", dbreq);
                    if let Some(ref id) = dbreq.id {
                        debug!("id: {:?}", id)
                    }
                    db.shutdown()
                }).map_err(|_| ())
        }));
        println!("done");
        // rt.shutdown_on_idle().wait().unwrap();
    }


    #[test]
    fn ssl_connection() {

        use std::sync::Arc;
        use futures::Future;

        // A `Request` is the type used for communication with the
        // client event loop. It is used both for sending input and
        // receiving output.

        struct Request {
            login: String,
            id: Option<Uuid>
        }

        // Requests must implement the `pleingres::Request` trait,
        // meaning they can be converted to commands to be sent to
        // the server.
        impl super::Request for Request {
            fn request(&mut self, buf: &mut Buffer) {
                buf.bind("SELECT id FROM users WHERE login=$1", &[&self.login])
                   .execute(0);
            }
        }

        impl HandleRow for Request {
            fn row(&mut self, mut row: Row) -> bool {
                if let Some(id_) = row.next() {
                    debug!("{:?}", std::str::from_utf8(id_));
                    let id_ = std::str::from_utf8(id_)
                        .unwrap().parse().unwrap();
                    self.id = Some(id_)
                }
                true
            }
        }
        env_logger::try_init().unwrap_or(());
        let p = Arc::new(ConfigFile {
            addr: "35.195.27.52:5432".to_string(),
            user: "pijul".to_string(),
            password: "AVRWx3vDYR1V4W4HxnKn".to_string(),
            db: "db".to_string(),
            idle_timeout: Some(20_000),
            tcp_keepalive: Some(10_000),
            ssl: Some(SSLConfigFile {
                ca_root: Some("../sql-server-ca.pem".to_string()),
                private_key: Some("../sql-client-key.pem".to_string()),
                hostname: Some("pijul-163713:nest".to_string()),
            })
        }.to_parameters().unwrap());

        tokio::run(futures::lazy(move || {
            let db:Handle<Request> = spawn_connection(p.clone()).unwrap();
            debug!("spawned");
            db
                .send_request(
                    Request { login: "me".to_string(), id: None }
                )
                .and_then(move |dbreq| {
                    if let Some(ref id) = dbreq.id {
                        debug!("id: {:?}", id)
                    }
                    db.shutdown()
                }).map_err(|_| ())
        }))
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pub const MSG_AUTH: u8 = b'R';
pub const MSG_BACKEND_KEY_DATA: u8 = b'K';
pub const MSG_PARAMETER_STATUS: u8 = b'S';
pub const MSG_PASSWORD: u8 = b'p';
pub const MSG_READY_FOR_QUERY: u8 = b'Z';
pub const MSG_ERROR: u8 = b'E';
// const MSG_ROW_DESCRIPTION: u8 = b'T';
pub const MSG_DATA_ROW: u8 = b'D';
pub const MSG_BIND: u8 = b'B';
pub const MSG_PARSE: u8 = b'P';
pub const MSG_EXECUTE: u8 = b'E';
pub const MSG_FLUSH: u8 = b'H';
pub const MSG_SYNC: u8 = b'S';
pub const MSG_COMMAND_COMPLETE: u8 = b'C';
pub const MSG_CLOSE: u8 = b'C';







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
use {ReadState, WriteState, read_length, read, Error, Connection, ErrorKind, error, Parameters};
use tokio_core::reactor::Timeout;
// use tokio::timer::Delay;
    pub timeout: Option<Timeout>,
                        return Ok(Async::Ready((self.connection.take().unwrap(), Some(ErrorKind::Timeout.into()))))
                                    return Err(ErrorKind::Protocol.into());
                            return Err(ErrorKind::Postgres(into).into())
use futures::{Future, Async, Poll};
use {ReadState, WriteState, read_length, read, Error, Connection, error, Parameters};
use std::str::from_utf8;
use byteorder::{BigEndian, ByteOrder};
use std::fmt;
use msg::*;
use tokio_io::io::flush;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_timer::Delay;


/// A result row, implementing an iterator on fields. Each field is a
/// slice of bytes.
#[derive(Clone)]
pub struct Row<'a> {
    len: u16,
    buf: &'a [u8],
    n: usize,
    pos: usize,
}

impl<'a> fmt::Debug for Row<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let v: Vec<_> = self.clone().map(|x| from_utf8(x)).collect();
        v.fmt(f)
    }
}


impl<'a> Row<'a> {
    /// Number of fields in this row.
    pub fn len(&self) -> usize {
        self.len as usize
    }
}

impl<'a> Iterator for Row<'a> {
    type Item = &'a [u8];
    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.buf.len() {
            None
        } else {
            let pos = self.pos;
            let len = BigEndian::read_i32(&self.buf[pos..]);
            if len >= 0 {
                let len = len as usize;
                let result = &self.buf[pos + 4..pos + 4 + len];
                self.pos += 4 + len;
                self.n += 1;
                Some(result)
            } else {
                self.pos += 4;
                // self.n += 1;
                Some(&self.buf[pos..pos])
            }
        }
    }
}


/// Result rows, returned by the `query` method of
/// `Connection`.
pub struct Rows<W: AsyncRead + AsyncWrite, F: HandleRow, P: AsRef<Parameters>> {
    #[doc(hidden)]
    pub connection: Option<(Connection<W, P>, F)>,
    #[doc(hidden)]
    pub timeout: Option<Delay>,
    #[doc(hidden)]
    pub last_row_was_halted: bool,
}

/// Result from a request.
#[derive(Debug)]
pub enum RowResult<'a> {
    /// An actual row.
    Row(Row<'a>),

    /// A completion signal, with the number of rows modified.
    Complete(u32),

    /// A termination signal, sent when there are no more rows.
    NoMoreRows,

    /// An error.
    Err(&'a str),
}


/// Requests that can handle a resulting row.
#[allow(unused_variables)]
pub trait HandleRow {
    /// Called on each row.
    fn row(&mut self, row: Row) -> bool { true }
    /// Called at the end of the request, with the number of modified rows.
    fn complete<'a>(&mut self, modified: u32) {
        debug!("complete, modified {:?}", modified);
    }
    /// Called when the server is ready for the next request.
    fn ready_for_query<'a>(&mut self) {
        debug!("ready_for_query");
    }
    /// This function gets called when the server returns an error.
    fn err(&mut self, err: &str) {
        debug!("err: {:?}", err);
    }
}

impl<F: Fn(Row) -> bool> HandleRow for F {
    fn row(&mut self, row: Row) -> bool {
        (self)(row)
    }
}

#[derive(PartialEq, Eq)]
enum RowPoll {
    // The last row was halted.
    Halted,
    // All rows have been read (and possibly discarded after a halt).
    Ready,
    // There are still rows to be read.
    NotReady,
}

impl<W: AsyncWrite + AsyncRead, F: HandleRow, P: AsRef<Parameters>> Future for Rows<W, F, P> {
    type Item = ((Connection<W, P>, F), Option<Error>);
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            debug!("rows poll");
            let mut was_err = None;
            let mut async_not_ready = false;
            let ready = if let Some((ref mut c, ref mut f)) = self.connection {
                match c.poll_rows(self.last_row_was_halted, f) {
                    Ok(Async::Ready(RowPoll::Halted)) => {
                        self.last_row_was_halted = true;
                        false
                    }
                    Ok(Async::Ready(RowPoll::Ready)) => true,
                    Ok(Async::Ready(RowPoll::NotReady)) => false,
                    Ok(Async::NotReady) => { async_not_ready = true; false },
                    Err(e) => {
                        error!("{:?}", e);
                        was_err = Some(e);
                        true
                    }
                }
            } else {
                unreachable!()
            };
            debug!("rows: {:?} {:?} {:?}", ready, was_err, async_not_ready);
            if ready {
                return Ok(Async::Ready((self.connection.take().unwrap(), was_err)));
            }

            if async_not_ready {
                if let Some(ref mut timeout) = self.timeout {
                    if let Ok(Async::Ready(())) = timeout.poll() {
                        debug!("Rows timeout fired (file {}, line {})", file!(), line!());
                        return Ok(Async::Ready((self.connection.take().unwrap(), Some(Error::Timeout))))
                    }
                }
                return Ok(Async::NotReady)
            } else {
                // We've received something, the timeout can be cancelled.
                self.timeout = None
            }

        }
    }
}


impl<W: AsyncRead + AsyncWrite, P: AsRef<Parameters>> Connection<W, P> {
    fn poll_rows<R: HandleRow>(&mut self,
                               last_row_was_halted: bool,
                               f: &mut R)
                               -> Poll<RowPoll, Error> {
        loop {
            match self.write.take() {
                Some(WriteState::Write { mut w }) => {
                    match try!(w.poll()) {
                        Async::Ready((stream, buf)) => {
                            self.write = Some(WriteState::Flush {
                                flush: flush(stream),
                                buf
                            });
                        },
                        Async::NotReady => {
                            self.write = Some(WriteState::Write { w });
                            return Ok(Async::NotReady);
                        }
                    }
                }
                Some(WriteState::Flush { mut flush, buf }) => {
                    match try!(flush.poll()) {
                        Async::Ready(w) => {
                            self.write = Some(WriteState::Idle { w, buf });
                            break
                        },
                        Async::NotReady => {
                            self.write = Some(WriteState::Flush { flush, buf });
                            return Ok(Async::NotReady);
                        }
                    }
                }
                Some(state) => {
                    self.write = Some(state);
                    break
                },
                None => {}
            }
        }
        // If we're done writing, start reading.

        loop {
            match self.read.take() {
                Some(ReadState::ReadLength(mut r)) => {
                    match try!(r.poll()) {
                        Async::Ready((w, buf)) => {
                            self.read = Some(read(w, buf))
                        }
                        Async::NotReady => {
                            self.read = Some(ReadState::ReadLength(r));
                            return Ok(Async::NotReady)
                        }
                    }
                }
                Some(ReadState::Read { msg, mut body }) => {

                    let (stream, buf) = match try!(body.poll()) {
                        Async::Ready((w, buf)) => (w, buf),
                        Async::NotReady => {
                            self.read = Some(ReadState::Read {
                                msg: msg,
                                body: body,
                            });
                            return Ok(Async::NotReady);
                        }
                    };
                    match msg {
                        /*MSG_ROW_DESCRIPTION => {
                        // This message type only happens when we send a "quick query".
                        {
                        let mut reader = reader(&buf[..]);
                        let n_fields = try!(reader.read_i16());
                        debug!("n_fields: {:?}", n_fields);
                        self.columns.clear();
                        for _ in 0..n_fields {
                        let name = try!(reader.read_string());
                        let col = Column {
                        table_id: try!(reader.read_i32()),
                        column_num: try!(reader.read_i16()),
                        data_type: try!(reader.read_i32()),
                        data_size: try!(reader.read_i16()),
                        type_modifier: try!(reader.read_i32()),
                        format: try!(reader.read_i16())
                    };
                        debug!("name {:?} {:?}", name, col);
                        self.columns.push(col);
                    }
                    }
                        self.state = Some(read_length(stream, buf));
                        Ok(Async::Ready(false))
                    }*/
                        MSG_DATA_ROW if !last_row_was_halted => {
                            debug!("data row");
                            let query_finished = {
                                let len = BigEndian::read_i16(&buf[..]);
                                let row = Row {
                                    len: len as u16,
                                    buf: &buf[..],
                                    n: 0,
                                    pos: 2,
                                };
                                if f.row(row) {
                                    RowPoll::NotReady
                                } else {
                                    RowPoll::Halted
                                }
                            };
                            self.read = Some(read_length(stream, buf));
                            return Ok(Async::Ready(query_finished))
                        }
                        MSG_COMMAND_COMPLETE => {
                            debug!("command_complete, buf = {:?}", buf);
                            // self.columns.clear();
                            // f.handle_row(RowResult::NoMoreRows);
                            {
                                if let Some(i) = (&buf[..]).iter().position(|&x| x == 0) {
                                    let buf = &buf[..i];
                                    let mut it = buf.split(|x| *x == b' ');
                                    match (it.next(), it.next(), it.next()) {

                                        (Some(b"TABLE"), _, _) => {
                                            f.complete(0);
                                        }
                                        (Some(b"INSERT"), _, Some(rows)) |
                                        (Some(_), Some(rows), _) => {
                                            debug!("rows: {:?}", from_utf8(rows));
                                            let rows:Result<u32, Error> =
                                                from_utf8(rows).map_err(From::from)
                                                .and_then(|x| x.parse::<u32>().map_err(From::from));
                                            if let Ok(rows) = rows {
                                                // debug!("{:?} {:?}", rows, parsed);
                                                f.complete(rows);
                                            }
                                        }
                                        _ => {
                                            debug!("command complete: {:?}", buf);
                                        }
                                    }
                                } else {
                                    return Err(Error::Protocol);
                                }
                            }
                            self.read = Some(read_length(stream, buf));
                            return Ok(Async::Ready(RowPoll::NotReady))
                        }
                        MSG_READY_FOR_QUERY => {
                            // self.columns.clear();
                            f.ready_for_query();
                            self.ready_for_query = true;
                            self.read = Some(read_length(stream, buf));
                            return Ok(Async::Ready(RowPoll::Ready))
                        }
                        MSG_ERROR => {
                            let mut into = String::new();
                            try!(error(&buf, &mut into));
                            self.read = Some(read_length(stream, buf));
                            return Err(Error::Postgres { message: into })
                        }
                        msg => {
                            debug!("unknown message {:?}", msg as char);
                            self.read = Some(read_length(stream, buf));
                            return Ok(Async::Ready(RowPoll::NotReady))
                        }
                    }
                }
                None => unreachable!()
            }
        }
    }
}





























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
use {Rows, Parameters, Error, ErrorKind, Connection, Request, HandleRow, SendState, SendRequest, Connecting, WriteFuture};
use tokio_core::net::TcpStream;
use tokio_core::reactor::Timeout;
use futures::{Poll, Async, Future, Stream};
use tokio_core;
    sender: mpsc::UnboundedSender<(R, oneshot::Sender<Result<R, Error>>)>,
    receiver: mpsc::UnboundedReceiver<(R, oneshot::Sender<Result<R, Error>>)>,
    handle: tokio_core::reactor::Handle,
    Plain(tokio_core::net::TcpStream),
    SSL(SslStream<tokio_core::net::TcpStream>),
    Connect(tokio_core::net::TcpStreamNew, HashMap<Cow<'static, str>, usize>),
        timeout: Option<Timeout>,
                    self.state = Some(DbState::Connect(TcpStream::connect(&self.parameters.as_ref().addr, &self.handle), parsed_queries));
                                        self.handle.clone(),
                            return Err(ErrorKind::SSLDenied.into())
                                self.handle.clone(),
                                    Some(Timeout::new(t, &self.handle)?)
                    } else {
                            Ok(Async::Ready(Some((mut query, reply)))) => {
                            Ok(Async::Ready(None)) => return Ok(Async::Ready(())),
                            let timeout = connection.timeout()?;
                            if let Some(Error(ErrorKind::Timeout, _)) = err {
                                        Some(Timeout::new(t, &self.handle)?)
    pub fn new(handle: tokio_core::reactor::Handle, p: P) -> Self {
            handle,
    sender: mpsc::UnboundedSender<(R, oneshot::Sender<Result<R, Error>>)>,
    (p: P, handle: tokio_core::reactor::Handle)
        let db = DatabaseConnection::new(handle.clone(), p);
        handle.spawn(db.map_err(|err| println!("err {:?}", err)));
use {Rows, Parameters, Error, Connection, Request, HandleRow, SendState, SendRequest, Connecting, WriteFuture};
use tokio::net::TcpStream;
use tokio_timer::Delay;
use futures::sync::{oneshot, mpsc};
use std;
use futures;
use buffer::{Buffer, sync};
use std::collections::HashMap;
use std::borrow::Cow;
use buffer;
use tokio_io::io::{WriteAll, write_all, ReadExact, read_exact, Flush, flush};
use tokio_io::{AsyncRead, AsyncWrite};
// use tokio::prelude::*;
use bytes::buf::Buf;
use tokio_openssl::{SslStream, ConnectAsync, SslConnectorExt, ConnectConfigurationExt};
use futures::{Poll, Async, Future, Stream, Sink, AsyncSink};
use tokio;

/// The type that gets spawned into the event loop.
struct DatabaseConnection<R: Request + HandleRow, P:AsRef<Parameters>> {
    state: Option<DbState<R, P>>,
    parameters: P,
    /// The `sender` field is going to be cloned by handles.
    sender: mpsc::UnboundedSender<Option<(R, oneshot::Sender<Result<R, Error>>)>>,

    /// The `receiver` field is what this connection listens to.
    receiver: mpsc::UnboundedReceiver<Option<(R, oneshot::Sender<Result<R, Error>>)>>,

    query_buffer: Vec<u8>,
    parse_buffer: Vec<u8>,
    leftover_oneshot: Option<(oneshot::Sender<Result<R, Error>>, R)>,
    // handle: tokio::reactor::Handle,
}

enum OptionSSL {
    Plain(tokio::net::TcpStream),
    SSL(SslStream<tokio::net::TcpStream>),
}

impl AsyncWrite for OptionSSL {
    fn shutdown(&mut self) -> Poll<(), std::io::Error> {
        match *self {
            OptionSSL::Plain(ref mut p) => p.shutdown(),
            OptionSSL::SSL(ref mut p) => p.shutdown(),
        }
    }
    fn write_buf<B:Buf>(&mut self, buf: &mut B) -> Poll<usize, std::io::Error> {
        match *self {
            OptionSSL::Plain(ref mut p) => p.write_buf(buf),
            OptionSSL::SSL(ref mut p) => p.write_buf(buf),
        }
    }
}
use std::io::{Write, Read};
impl Read for OptionSSL {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
        match *self {
            OptionSSL::Plain(ref mut p) => p.read(buf),
            OptionSSL::SSL(ref mut p) => p.read(buf),
        }
    }
}
impl AsyncRead for OptionSSL {}
impl Write for OptionSSL {
    fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
        match *self {
            OptionSSL::Plain(ref mut p) => p.write(buf),
            OptionSSL::SSL(ref mut p) => p.write(buf),
        }
    }
    fn flush(&mut self) -> Result<(), std::io::Error> {
        match *self {
            OptionSSL::Plain(ref mut p) => p.flush(),
            OptionSSL::SSL(ref mut p) => p.flush(),
        }
    }
}

enum DbState<R: HandleRow, P: AsRef<Parameters>> {
    Reconnecting(HashMap<Cow<'static, str>, usize>),
    Connect(tokio::net::tcp::ConnectFuture, HashMap<Cow<'static, str>, usize>),
    SSLInit(WriteAll<TcpStream, &'static [u8]>, HashMap<Cow<'static, str>, usize>),
    SSLFlush(Flush<TcpStream>, HashMap<Cow<'static, str>, usize>),
    SSLConfirm(ReadExact<TcpStream, [u8; 1]>, HashMap<Cow<'static, str>, usize>),
    SSLConnect(ConnectAsync<TcpStream>, HashMap<Cow<'static, str>, usize>),

    Init(Connecting<OptionSSL, P>, HashMap<Cow<'static, str>, usize>),
    InitWrite(WriteFuture<OptionSSL, P>),
    Connected {
        connection: Connection<OptionSSL, P>,
        timeout: Option<Delay>,
    },
    Write {
        /// A future writing the request to the connection.
        connection: WriteFuture<OptionSSL, P>,
        /// A handler received through `DatabaseConnection.receiver`
        /// to handle the connection.
        query: R,
        /// The channel to which the reply shall be sent.
        reply: oneshot::Sender<Result<R, Error>>,
    },
    Query {
        rows: Rows<OptionSSL, R, P>,
        reply: oneshot::Sender<Result<R, Error>>,
    },
}

impl<R: Request + HandleRow, P:AsRef<Parameters> + Clone + Send> Future for DatabaseConnection<R, P> {
    type Item = ();
    type Error = Error;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            debug!("polling databaseconnection");
            match self.state.take() {
                Some(DbState::Reconnecting(parsed_queries)) => {
                    debug!("reconnecting");
                    self.state = Some(DbState::Connect(TcpStream::connect(&self.parameters.as_ref().addr), parsed_queries));

                }
                Some(DbState::Connect(mut stream, parsed_queries)) => {
                    debug!("connect");
                    match stream.poll() {
                        Ok(Async::Ready(stream)) => {
                            stream.set_keepalive(self.parameters.as_ref().tcp_keepalive)?;
                            if self.parameters.as_ref().ssl.is_some() {
                                debug!("sending {:?}", [0, 0, 0, 8, 4, 210, 22, 47]);
                                self.state = Some(DbState::SSLInit(
                                    write_all(stream, &[0, 0, 0, 8, 4, 210, 22, 47]),
                                    parsed_queries
                                ))
                            } else {
                                self.state = Some(DbState::Init(
                                    Connection::new(
                                        OptionSSL::Plain(stream),
                                        self.parameters.clone(),
                                        HashMap::new(),
                                    ),
                                    parsed_queries
                                ))
                            }
                        }
                        Ok(Async::NotReady) => {
                            debug!("not ready");
                            self.state = Some(DbState::Connect(stream, parsed_queries));
                            return Ok(Async::NotReady)
                        },
                        Err(e) => {
                            error!("{:?}", e);
                            self.state = Some(DbState::Reconnecting(parsed_queries))
                        }
                    }
                }
                Some(DbState::SSLInit(mut w, parsed_queries)) => {
                    debug!("SSLInit");
                    if let Async::Ready((w, _)) = w.poll()? {
                        debug!("flush");
                        self.state = Some(DbState::SSLFlush(flush(w), parsed_queries))
                    } else {
                        debug!("still init");
                        self.state = Some(DbState::SSLInit(w, parsed_queries));
                        return Ok(Async::NotReady)
                    }
                }
                Some(DbState::SSLFlush(mut w, parsed_queries)) => {
                    debug!("SSLFlush");
                    if let Async::Ready(w) = w.poll()? {
                        debug!("confirm");
                        self.state = Some(DbState::SSLConfirm(read_exact(w, [0; 1]), parsed_queries))
                    } else {
                        debug!("still flush");
                        self.state = Some(DbState::SSLFlush(w, parsed_queries));
                        return Ok(Async::NotReady)
                    }
                }
                Some(DbState::SSLConfirm(mut r, parsed_queries)) => {
                    debug!("SSLConfirm");
                    if let Async::Ready((r, buf)) = r.poll()? {
                        if buf[0] == b'S' {
                            // Now expect a "yes" response.
                            let connect =
                                if let Some(ref ssl) = self.parameters.as_ref().ssl {
                                    if let Some(ref hostname) = ssl.hostname {
                                        debug!("hostname {:?}", hostname);
                                        ssl.config.connect_async(hostname, r)
                                    } else {
                                        debug!("no host name");
                                        ssl.config.configure()?
                                            .verify_hostname(false)
                                            .connect_async("", r)
                                    }
                                } else {
                                    unreachable!()
                                };
                            self.state = Some(DbState::SSLConnect(
                                connect,
                                parsed_queries,
                            ))
                        } else {
                            debug!("buf = {:?}", buf);
                            return Err(Error::SSLDenied)
                        }
                    } else {
                        debug!("confirm not ready");
                        self.state = Some(DbState::SSLConfirm(r, parsed_queries));
                        return Ok(Async::NotReady)
                    }
                }
                Some(DbState::SSLConnect(mut w, parsed_queries)) => {
                    debug!("SSLConnect");
                    if let Async::Ready(w) = w.poll()? {
                        debug!("Connected");
                        self.state = Some(DbState::Init(
                            Connection::new(
                                OptionSSL::SSL(w),
                                self.parameters.clone(),
                                HashMap::new()
                            ),
                            parsed_queries
                        ))
                    } else {
                        debug!("SSLConnect not ready");
                        self.state = Some(DbState::SSLConnect(w, parsed_queries));
                        return Ok(Async::NotReady)
                    }
                }
                Some(DbState::Init(mut connected, parsed_queries)) => {
                    debug!("init");
                    match connected.poll() {
                        Ok(Async::Ready(mut connected)) => {
                            {
                                let mut buf = connected.buffer();
                                for (a, b) in parsed_queries.iter() {
                                    buf.parse(&buffer::name(*b), a, &[]);
                                }
                            }
                            connected.parsed_queries = parsed_queries;
                            self.state = Some(DbState::InitWrite(connected.write()));
                        }
                        Ok(Async::NotReady) => {
                            self.state = Some(DbState::Init(connected, parsed_queries));
                            return Ok(Async::NotReady)
                        }
                        Err(e) => {
                            error!("{:?}", e);
                            self.state = Some(DbState::Reconnecting(parsed_queries))
                        }
                    }
                },
                Some(DbState::InitWrite(mut connected)) => {
                    debug!("initwrite");
                    match connected.poll() {
                        Ok(Async::Ready(connected)) => {
                            self.state = Some(DbState::Connected {
                                connection: connected,
                                timeout: if let Some(t) = self.parameters.as_ref().idle_timeout {
                                    Some(Delay::new(std::time::Instant::now() + t))
                                } else {
                                    None
                                }
                            })
                        }
                        Ok(Async::NotReady) => {
                            self.state = Some(DbState::InitWrite(connected));
                            return Ok(Async::NotReady)
                        }
                        Err(e) => {
                            error!("{:?}", e);
                            self.state = Some(DbState::Reconnecting(
                                connected.0.take().unwrap().parsed_queries
                            ))
                        }
                    }
                },
                Some(DbState::Connected { mut connection, mut timeout }) => {
                    debug!("connected");
                    if let Some((reply, query)) = self.leftover_oneshot.take() {
                        debug!("self.query_buffer = {:?}", self.query_buffer);
                        connection.buffer().clone_from_buf(&self.query_buffer);
                        self.state = Some(DbState::Write {
                            connection: connection.write(),
                            reply: reply,
                            query: query,
                        });

                    } else if connection.ready_for_query {
                        debug!("receiver polled");
                        match self.receiver.poll() {
                            Ok(Async::Ready(Some(Some((mut query, reply))))) => {
                                self.query_buffer.clear();
                                self.parse_buffer.clear();
                                debug!("ready ? {:?}", connection.ready_for_query);
                                query.request(&mut Buffer::buf(&mut self.query_buffer, &mut self.parse_buffer, &mut connection.parsed_queries));
                                sync(&mut self.query_buffer);
                                {
                                    let mut b = connection.buffer();
                                    b.clone_from_buf(&self.parse_buffer);
                                    b.extend(&self.query_buffer);
                                }

                                connection.ready_for_query = false;
                                self.state = Some(DbState::Write {
                                    connection: connection.write(),
                                    reply: reply,
                                    query: query,
                                });
                            }
                            Ok(Async::Ready(_)) => return Ok(Async::Ready(())),
                            Ok(Async::NotReady) => {

                                let timeout_is_ready = if let Some(ref mut timeout) = timeout {
                                    match timeout.poll() {
                                        Ok(Async::Ready(_)) => true,
                                        _ => false
                                    }
                                } else { false };

                                if timeout_is_ready {
                                    self.state = Some(DbState::Reconnecting(connection.parsed_queries));
                                } else {
                                    self.state = Some(DbState::Connected {
                                        connection, timeout
                                    });
                                    return Ok(Async::NotReady);
                                }

                            }
                            Err(e) => {
                                error!("{:?}", e);
                                self.state = Some(DbState::Reconnecting(connection.parsed_queries))
                            }
                        }
                    } else {
                        match connection.poll_connecting() {
                            Ok(Async::Ready(())) => {
                                self.state = Some(DbState::Connected {
                                    connection, timeout
                                });
                            },
                            Ok(Async::NotReady) => {
                                self.state = Some(DbState::Connected { connection, timeout });
                                return Ok(Async::NotReady)
                            }
                            Err(e) => {
                                // continue
                            }
                        }
                    }
                }
                Some(DbState::Write { mut connection, reply, query }) => {
                    debug!("write");
                    match connection.poll() {
                        Ok(Async::Ready(connection)) => {
                            let timeout = connection.timeout();
                            self.state = Some(DbState::Query {
                                rows: connection.rows(query, Some(timeout))?,
                                reply: reply,
                            })
                        }
                        Ok(Async::NotReady) => {
                            self.state = Some(DbState::Write {
                                connection: connection,
                                query: query,
                                reply: reply,
                            });
                            return Ok(Async::NotReady);
                        },
                        Err(e) => {
                            error!("{:?}", e);
                            self.state = Some(DbState::Reconnecting(
                                connection.0.take().unwrap().parsed_queries
                            ))
                        }
                    }
                }
                Some(DbState::Query { reply, mut rows }) => {
                    debug!("polling rows");
                    match rows.poll() {
                        Ok(Async::Ready(((connection, query), err))) => {
                            if let Some(Error::Timeout) = err {
                                // timed out, reconnecting
                                self.leftover_oneshot = Some((reply, query));
                                self.state = Some(DbState::Reconnecting(connection.parsed_queries));
                            } else {
                                let reply_msg = if let Some(err) = err {
                                    Err(err)
                                } else {
                                    Ok(query)
                                };

                                if reply.send(reply_msg).is_err() {
                                    error!("Could not send result")
                                }
                                self.state = Some(DbState::Connected {
                                    connection,
                                    timeout: if let Some(t) = self.parameters.as_ref().idle_timeout {
                                        Some(Delay::new(std::time::Instant::now() + t))
                                    } else {
                                        None
                                    }
                                });
                            }
                            continue
                        },
                        Ok(Async::NotReady) => {},
                        Err(e) => {
                            error!("{:?}", e);
                            if reply.send(Err(e)).is_err() {
                                error!("Could not even send error");
                            }
                            self.state = Some(DbState::Reconnecting(
                                rows.connection.take().unwrap().0.parsed_queries
                            ));
                            continue
                        }
                    }
                    self.state = Some(DbState::Query {
                        rows: rows,
                        reply: reply,
                    });
                    return Ok(Async::NotReady);
                }
                None => panic!("None"),
            }
        }
    }
}




impl<R: Request + HandleRow, P: AsRef<Parameters> + Send> DatabaseConnection<R, P> {
    /// Create a `DatabaseConnection` type, which can be spawned into
    /// an event loop and talked to via handles.
    pub fn new(p: P) -> Self {
        let (se, re) = mpsc::unbounded();
        DatabaseConnection {
            parameters: p,
            state: Some(DbState::Reconnecting(HashMap::new())),
            receiver: re,
            sender: se,
            query_buffer: Vec::new(),
            parse_buffer: Vec::new(),
            leftover_oneshot: None,
        }
    }

    /// Create a handle to this spawned connection.
    pub fn handle(&self) -> Handle<R> {
        Handle { sender: self.sender.clone() }
    }

}

/// A handle to a database connection that has been spawn to an event
/// loop. This is actually a synchronization channel.
pub struct Handle<R> {
    // The "shutdown signal" is implemented by sending `None` into
    // this sender.
    sender: mpsc::UnboundedSender<Option<(R, oneshot::Sender<Result<R, Error>>)>>,
}

impl<R> Clone for Handle<R> {
    fn clone(&self) -> Self {
        Handle { sender: self.sender.clone() }
    }
}

impl<R: Request + HandleRow> Handle<R> {
    /// Send a request to this handle. Methods from the `Request` and
    /// `HandleRow` traits will be called as needed.
    ///
    /// The request will be sent through a `futures::mpsc` channel,
    /// along with a `futures::channel::oneshot` channel to "wait" the
    /// result on.
    pub fn send_request<F>(&self, r: F) -> SendRequest<R>
        where R: std::convert::From<F>
    {
        let (sender, receiver) = futures::sync::oneshot::channel();
        SendRequest {
            sender: self.sender.clone(),
            receiver: receiver,
            state: Some(SendState::Init(r.into(), sender))
        }
    }

    pub fn shutdown(&self) -> ShutdownFuture<R> {
        debug!("shutting down send ?");
        ShutdownFuture { sender: self.sender.clone(), shutdown: false }
    }
}

pub struct ShutdownFuture<R> {
    sender: futures::sync::mpsc::UnboundedSender<Option<(R, futures::sync::oneshot::Sender<Result<R, Error>>)>>,
    shutdown: bool
}

impl<R> Future for ShutdownFuture<R> {
    type Item = ();
    type Error = Error;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        debug!("shutting down sender");
        loop {
            if self.shutdown {
                return Ok(self.sender.close()?)
            } else {
                match self.sender.start_send(None)? {
                    AsyncSink::NotReady(None) => return Ok(Async::NotReady),
                    AsyncSink::Ready => self.shutdown = true,
                    AsyncSink::NotReady(_) => unreachable!()
                }
            }
        }
    }
}


/// Setup a complete database connection. This is a high-level
/// function combining the connection of a `TcpStream`, a postgres
/// `Connection`, an initializer function (which can be used for
/// instance to parse named statements) and a `DatabaseConnection`,
/// and returning a handle into the spawned future.
pub fn spawn_connection<R: HandleRow + Request + Send + 'static, P: AsRef<Parameters> + Clone + Send + 'static>
    (p: P)
     -> Result<Handle<R>, Error> {
        let db = DatabaseConnection::new(p);
        let db_handle = db.handle();
        tokio::spawn(db.map_err(|err| println!("err {:?}", err)));
        Ok(db_handle)
    }

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
        write!(w, "{}", self.hyphenated()).unwrap();
use chrono;
use uuid;
use std::net::{SocketAddr, IpAddr};
use std::fmt;
use std::io::Write;
use std::str::from_utf8;
use std::borrow::Cow;

/// SQL format code (text or binary).
#[repr(i16)]
pub enum FormatCode {
    /// Text format
    Text = 0,
    /// Binary format
    Binary = 1,
}

/// Postgres code for types.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(i32)]
pub enum SqlType {
    /// Dynamic type
    None = 0,
}


/// Trait used to convert a type to its SQL representation.
pub trait ToSql {
    /// Postgres type code for this type.
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    /// Postgres format code for this type.
    fn format_code(&self) -> FormatCode {
        FormatCode::Text
    }
    /// How to serialize this type in a Postgres-compatible way.
    /// Returns true if and only if *self is not serialized to SQL
    /// NULL.
    fn write_sql(&self, w: &mut Vec<u8>) -> bool;
}

/// Trait to produce types from their SQL representation.
pub trait FromSql<'a>: Sized {
    /// Deserialise from the given buffer.
    fn from_sql(s: &'a [u8]) -> Option<Self>;
}

impl<T:ToSql> ToSql for std::sync::Arc<T> {
    fn sql_type(&self) -> SqlType {
        self.as_ref().sql_type()
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        self.as_ref().write_sql(w)
    }
}

impl<T:ToSql> ToSql for std::rc::Rc<T> {
    fn sql_type(&self) -> SqlType {
        self.as_ref().sql_type()
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        self.as_ref().write_sql(w)
    }
}

impl ToSql for bool {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        if *self {
            write!(w, "TRUE").unwrap()
        } else {
            write!(w, "FALSE").unwrap()
        }
        true
    }
}

impl<'a> FromSql<'a> for bool {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        Some(s == b"t")
    }
}


impl<S:ToSql> ToSql for Option<S> {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        if let Some(ref x) = *self {
            x.write_sql(w);
            true
        } else {
            false
        }
    }
}

impl<'a, S:FromSql<'a>> FromSql<'a> for Option<S> {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        if s.is_empty() {
            Some(None)
        } else {
            S::from_sql(s).map(Some)
        }
    }
}




impl<Tz: chrono::TimeZone> ToSql for chrono::DateTime<Tz>
    where Tz::Offset: fmt::Display
{
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        debug!("RFC3339: {:?}", self.to_rfc3339());
        w.write(self.to_rfc3339().as_bytes()).unwrap();
        true
    }
}

impl<'a> FromSql<'a> for chrono::DateTime<chrono::Utc> {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        debug!("parse_timestamp: {:?}", s);
        from_utf8(s).ok().and_then(|s| {
            if let Ok(t) = chrono::NaiveDateTime::parse_from_str(s, "%F %T%.f+00") {
                Some(chrono::DateTime::<chrono::Utc>::from_utc(t, chrono::Utc))
            } else {
                None
            }
        })
    }
}


impl ToSql for i64 {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", *self).unwrap();
        true
    }
}

impl<'a> FromSql<'a> for i64 {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        from_utf8(s).ok().and_then(|s| s.parse().ok())
    }
}

impl ToSql for f64 {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", *self).unwrap();
        true
    }
}

impl<'a> FromSql<'a> for f64 {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        from_utf8(s).ok().and_then(|s| s.parse().ok())
    }
}

impl ToSql for f32 {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", *self).unwrap();
        true
    }
}

impl<'a> FromSql<'a> for f32 {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        from_utf8(s).ok().and_then(|s| s.parse().ok())
    }
}

impl ToSql for i32 {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", *self).unwrap();
        true
    }
}

impl<'a> FromSql<'a> for i32 {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        from_utf8(s).ok().and_then(|s| s.parse().ok())
    }
}

impl ToSql for String {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", self).unwrap();
        true
    }
}

impl<'a> FromSql<'a> for String {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        FromSql::from_sql(s).map(|s: &str| s.to_string())
    }
}

impl<'a> ToSql for Cow<'a, str> {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", self).unwrap();
        true
    }
}

impl<'a> FromSql<'a> for Cow<'a, str> {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        FromSql::from_sql(s).map(Cow::Borrowed)
    }
}

impl<'a> ToSql for &'a str {
    fn sql_type(&self) -> SqlType {
        SqlType::None
    }
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", self).unwrap();
        true
    }
}
impl<'a> FromSql<'a> for &'a str {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        from_utf8(s).ok()
    }
}

impl ToSql for uuid::Uuid {
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", self.to_hyphenated()).unwrap();
        true
    }
}

impl<'a> FromSql<'a> for uuid::Uuid {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        from_utf8(s).ok().and_then(|s| s.parse().ok())
    }
}

impl ToSql for SocketAddr {
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", self).unwrap();
        true
    }
}
impl<'a> FromSql<'a> for SocketAddr {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        from_utf8(s).ok().and_then(|s| s.parse().ok())
    }
}

impl ToSql for IpAddr {
    fn write_sql(&self, w: &mut Vec<u8>) -> bool {
        write!(w, "{}", self).unwrap();
        true
    }
}
impl<'a> FromSql<'a> for IpAddr {
    fn from_sql(s: &'a [u8]) -> Option<Self> {
        from_utf8(s).ok().and_then(|s| s.parse().ok())
    }
}

/// Types representing statements.
pub trait Statement {
    /// SQL statement.
    fn statement(&self) -> &str;

    /// Statement names. The default implementation returns the "unname".
    fn name(&self) -> &str {
        ""
    }
}

impl<'a, S: Statement> Statement for &'a S {
    fn name(&self) -> &str {
        (*self).name()
    }
    fn statement(&self) -> &str {
        (*self).statement()
    }
}

impl<'a> Statement for &'a str {
    fn statement(&self) -> &str {
        self
    }
}

impl<'a, 'b> Statement for (&'a str, &'b str) {
    fn statement(&self) -> &str {
        self.1
    }
    fn name(&self) -> &str {
        self.0
    }
}
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
use futures::{Async, Poll, Future};
use std::io::Read;
use {Error, ReadState, WriteState, read_length, error, read, Wait, Connection};
use msg::*;
use tokio_io::AsyncWrite;
use tokio_io;

impl<W: Read + AsyncWrite> Connection<W> {
    /// Wait for a readiness signal to occur on this connection.
    pub fn wait_complete(self, msg: Wait) -> WaitUntil<W> {
        WaitUntil {
            msg: msg,
            connection: Some(self),
        }
    }
}


/// Future resolving to the connection once a readiness signal has
/// been sent by the server.
pub struct WaitUntil<W: Read + AsyncWrite> {
    msg: Wait,
    connection: Option<Connection<W>>,
}



impl<W: AsyncWrite + Read> Future for WaitUntil<W> {
    type Item = Connection<W>;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            debug!("waituntil poll");
            let ready = if let Some(ref mut c) = self.connection {
                try_ready!(c.poll_wait_until(self.msg))
            } else {
                unreachable!()
            };
            if ready {
                return Ok(Async::Ready(self.connection.take().unwrap()));
            }
        }
    }
}

impl<W: AsyncWrite + Read> Connection<W> {
    fn poll_wait_until(&mut self, wait_until: Wait) -> Poll<bool, Error> {
        match self.state.take() {
            Some(ReadState::ReadLength(mut r)) => {
                match try!(read(&mut r)) {
                    Async::Ready(s) => self.state = Some(s),
                    Async::NotReady => {
                        self.state = Some(ReadState::ReadLength(r));
                        return Ok(Async::NotReady);
                    }
                }
                Ok(Async::Ready(false))
            }
            Some(State::Read { msg, mut body }) => {

                let (stream, buf) = match try!(body.poll()) {
                    Async::Ready(s) => s,
                    Async::NotReady => {
                        self.state = Some(State::Read {
                            msg: msg,
                            body: body,
                        });
                        return Ok(Async::NotReady);
                    }
                };
                match msg {
                    MSG_ERROR => {
                        let mut into = String::new();
                        try!(error(&buf, &mut into));
                        // self.state = Some(read_length(stream, buf));
                        // Ok(Async::Ready(true))
                        Err(Error::Postgres { message: into })
                    }
                    msg => {
                        debug!("message {:?}", msg as char);
                        self.state = Some(read_length(stream, buf));
                        Ok(Async::Ready(msg == wait_until as u8))
                    }
                }
            }
            Some(State::Write(mut w)) => {
                let (stream, buf) = match try!(w.poll()) {
                    Async::Ready(s) => s,
                    Async::NotReady => {
                        self.state = Some(State::Write(w));
                        return Ok(Async::NotReady);
                    }
                };
                self.state = Some(State::Flush(tokio_io::io::flush(stream), buf));
                Ok(Async::Ready(false))
            }
            Some(State::Flush(mut f, buf)) => {
                let stream = match try!(f.poll()) {
                    Async::Ready(s) => s,
                    Async::NotReady => {
                        self.state = Some(State::Flush(f, buf));
                        return Ok(Async::NotReady);
                    }
                };
                self.state = Some(read_length(stream, buf));
                Ok(Async::Ready(false))
            }
            None => unreachable!(),
        }
    }
}
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
use std;
use futures::{Poll, Future, Async};
use tokio_io::AsyncWrite;

pub struct WriteExact<W: AsyncWrite> {
    w: Option<(W, Vec<u8>)>,
    first: usize,
    len: usize,
}

pub fn write_exact<W:AsyncWrite>(w: W, v: Vec<u8>, first: usize, len: usize) -> WriteExact<W> {
    WriteExact {
        w: Some((w, v)),
        first: first,
        len: first + len
    }
}

impl<W: AsyncWrite> Future for WriteExact<W> {

    type Item = (W, Vec<u8>, usize);

    type Error = std::io::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            if self.first >= self.len {
                let (a, b) = self.w.take().unwrap();
                return Ok(Async::Ready((a, b, self.len)))
            }
            if let Some((ref mut w, ref mut v)) = self.w {
                self.first += try_nb!(w.write(&v[ self.first .. self.len ]));
            }
        }
    }
}