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
#![feature(type_ascription, integer_atomics)]
extern crate futures;
#[macro_use] extern crate gstuff;
extern crate itertools;
#[cfg(test)] #[macro_use] extern crate lazy_static;
extern crate libc;
extern crate nix;
extern crate serde_json;
use futures::{Future, Poll, Async};
use futures::task::{park, Task};
use libc::{c_char, c_int, c_void, size_t};
use nix::poll::{self, EventFlags, PollFd};
use nix::fcntl::{O_NONBLOCK, O_CLOEXEC};
use serde_json::{self as json, Value as Json};
use std::collections::{BTreeMap, VecDeque};
use std::convert::From;
use std::error::Error;
use std::ffi::{CString, CStr};
use std::fmt;
use std::io;
use std::ptr::null_mut;
use std::slice::from_raw_parts;
use std::str::{from_utf8_unchecked, from_utf8, Utf8Error};
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver, SendError, TryRecvError};
use std::thread::JoinHandle;
#[cfg(test)] mod tests;
#[derive(Debug)]
pub enum PgQueryPiece {
Static (&'static str),
Plain (String),
Literal (String),
Bytea (Vec<u8>)}
#[derive (Debug)]
pub enum PgSchedulingMode {
AnythingGoes,
PinToConnection (u8)}
#[derive (Debug)]
pub struct PgOperation {
pub query_pieces: Vec<PgQueryPiece>,
pub statements: u32,
pub scheduling: PgSchedulingMode}
pub trait IntoQueryPieces {
fn into_query_pieces (self) -> PgOperation;}
impl IntoQueryPieces for String {
fn into_query_pieces (self) -> PgOperation {
PgOperation {statements: 1, query_pieces: vec! [PgQueryPiece::Plain (self)], scheduling: PgSchedulingMode::AnythingGoes}}}
impl IntoQueryPieces for &'static str {
fn into_query_pieces (self) -> PgOperation {
PgOperation {statements: 1, query_pieces: vec! [PgQueryPiece::Static (self)], scheduling: PgSchedulingMode::AnythingGoes}}}
impl IntoQueryPieces for Vec<PgQueryPiece> {
fn into_query_pieces (self) -> PgOperation {
PgOperation {statements: 1, query_pieces: self, scheduling: PgSchedulingMode::AnythingGoes}}}
impl IntoQueryPieces for (u32, &'static str) {
fn into_query_pieces (self) -> PgOperation {
PgOperation {statements: self.0, query_pieces: vec! [PgQueryPiece::Static (self.1)], scheduling: PgSchedulingMode::AnythingGoes}}}
impl IntoQueryPieces for (u32, String) {
fn into_query_pieces (self) -> PgOperation {
PgOperation {statements: self.0, query_pieces: vec! [PgQueryPiece::Plain (self.1)], scheduling: PgSchedulingMode::AnythingGoes}}}
impl IntoQueryPieces for (u32, Vec<PgQueryPiece>) {
fn into_query_pieces (self) -> PgOperation {
PgOperation {statements: self.0, query_pieces: self.1, scheduling: PgSchedulingMode::AnythingGoes}}}
impl IntoQueryPieces for PgOperation {
fn into_query_pieces (self) -> PgOperation {self}}
pub struct PgRow<'a> (&'a PgResult, u32);
impl<'a> PgRow<'a> {
pub fn is_null (&self, column: u32) -> bool {
if column > self.0.columns {panic! ("Column index {} is out of range (0..{})", column, self.0.columns)}
1 == unsafe {pq::PQgetisnull ((self.0).res, self.1 as c_int, column as c_int)}}
pub fn ftype (&self, column: u32) -> pq::Oid {
if column > self.0.columns {panic! ("Column index {} is out of range (0..{})", column, self.0.columns)}
unsafe {pq::PQftype ((self.0).res, column as c_int)}}
pub fn fname (&'a self, column: u32) -> Result<&'a str, Utf8Error> {
self.0.fname (column)}
pub fn num (&self) -> u32 {self.1}
pub fn len (&self) -> u32 {self.0.columns}
pub fn col (&self, column: u32) -> &'a [u8] {
if column > self.0.columns {panic! ("Column index {} is out of range (0..{})", column, self.0.columns)}
let len = unsafe {pq::PQgetlength ((self.0).res, self.1 as c_int, column as c_int)};
let val = unsafe {pq::PQgetvalue ((self.0).res, self.1 as c_int, column as c_int)};
unsafe {from_raw_parts (val as *const u8, len as usize)}}
pub fn col_str (&self, column: u32) -> Result<&'a str, std::str::Utf8Error> {
if column > self.0.columns {panic! ("Column index {} is out of range (0..{})", column, self.0.columns)}
unsafe {CStr::from_ptr (pq::PQgetvalue ((self.0).res, self.1 as c_int, column as c_int))} .to_str()}
pub fn bytea (&self, column: u32) -> Vec<u8> {
if column > self.0.columns {panic! ("Column index {} is out of range (0..{})", column, self.0.columns)}
let mut len: size_t = 0;
let mut vec = Vec::new();
unsafe {
let value = pq::PQgetvalue ((self.0).res, self.1 as c_int, column as c_int);
let bytes = pq::PQunescapeBytea (value as *const u8, &mut len);
if bytes != null_mut() {
vec.reserve_exact (len);
vec.extend_from_slice (from_raw_parts (bytes, len));
pq::PQfreemem (bytes as *mut c_void);}}
vec}
pub fn to_json (&self) -> Result<Json, PgFutureErr> {
let mut jrow: BTreeMap<String, Json> = BTreeMap::new();
for column in 0 .. self.0.columns {
let name = self.fname (column)?;
let jval = if self.is_null (column) {
Json::Null
} else {
match self.ftype (column) {
20 | 21 | 23 => Json::I64 (self.col_str (column) ?. parse() ?),
25 | 1042 | 1043 | 3614 => Json::String (from_utf8 (self.col (column)) ?.into()),
700 | 701 => Json::F64 (self.col_str (column) ?. parse() ?),
114 | 3802 => json::from_str (self.col_str (column) ?) ?,
oid if oid > 16000 => {
let bytes = self.col (column);
if bytes.is_empty() {return Err (PgFutureErr::UnknownType (String::from (name), oid))}
for &ch in bytes.iter() {
if !is_alphabetic (ch) && !is_digit (ch) && ch != b'_' && ch != b'-' && ch != b'.' {
return Err (PgFutureErr::UnknownType (String::from (name), oid))}}
Json::String (unsafe {from_utf8_unchecked (bytes)} .into())},
oid => return Err (PgFutureErr::UnknownType (String::from (name), oid))}};
jrow.insert (String::from (name), jval);}
Ok (Json::Object (jrow))}}
fn is_alphabetic (ch:u8) -> bool {
(ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A)}
fn is_digit (ch: u8) -> bool {
ch >= 0x30 && ch <= 0x39}
pub struct PgResult {
pub res: *mut pq::PGresult,
pub rows: u32,
pub columns: u32}
unsafe impl Sync for PgResult {}
unsafe impl Send for PgResult {}
impl PgResult {
pub fn is_empty (&self) -> bool {self.rows == 0}
pub fn len (&self) -> u32 {self.rows}
pub fn ftype (&self, column: u32) -> pq::Oid {
if column > self.columns {panic! ("Column index {} is out of range (0..{})", column, self.columns)}
unsafe {pq::PQftype (self.res, column as c_int)}}
pub fn fname<'a> (&'a self, column: u32) -> Result<&'a str, Utf8Error> {
let name = unsafe {pq::PQfname (self.res, column as c_int)};
if name == null_mut() {panic! ("Column index {} is out of range (0..{})", column, self.columns)}
unsafe {CStr::from_ptr (name)} .to_str()}
pub fn row (&self, row: u32) -> PgRow {
if row >= self.rows {panic! ("Row index {} is out of range (0..{})", row, self.rows)}
PgRow (self, row)}
pub fn iter<'a> (&'a self) -> PgResultIt<'a> {
PgResultIt {pr: self, row: 0}}
pub fn to_json (&self) -> Result<Json, PgFutureErr> {
let mut jrows: Vec<Json> = Vec::with_capacity (self.len() as usize);
for row in self.iter() {jrows.push (row.to_json()?)}
Ok (Json::Array (jrows))}}
impl Drop for PgResult {
fn drop (&mut self) {
assert! (self.res != null_mut());
unsafe {pq::PQclear (self.res)}}}
impl fmt::Debug for PgResult {
fn fmt (&self, ft: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write! (ft, "PgResult")}}
pub struct PgResultIt<'a> {pr: &'a PgResult, row: u32}
impl<'a> Iterator for PgResultIt<'a> {
type Item = PgRow<'a>;
fn next (&mut self) -> Option<PgRow<'a>> {
if self.row < self.pr.rows {
let row = PgRow (self.pr, self.row);
self.row += 1;
Some (row)
} else {None}}}
struct PgFutureSync {
results: Vec<PgResult>,
task: Option<Task>}
struct PgFutureImpl {
id: u64,
op: PgOperation,
sync: Mutex<PgFutureSync>,
miscarried: Option<Box<PgFutureErr>>}
#[derive(Clone)]
pub struct PgSqlErr {
imp: Arc<PgFutureImpl>,
pub num: u32,
pub status: &'static str,
pub sqlstate: String,
pub message: String}
#[derive(Clone)]
pub enum PgFutureErr {
PoisonError,
SendError (String),
NixError (nix::Error),
Utf8Error (Utf8Error),
Sql (PgSqlErr),
Json (Arc<serde_json::Error>),
Int (std::num::ParseIntError),
Float (std::num::ParseFloatError),
UnknownType (String, pq::Oid)}
impl fmt::Debug for PgFutureErr {
fn fmt (&self, ft: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
&PgFutureErr::PoisonError => ft.write_str ("PgFutureErr::PoisonError"),
&PgFutureErr::SendError (ref err) => write! (ft, "PgFutureErr::SendError ({})", err),
&PgFutureErr::NixError (ref err) => write! (ft, "PgFutureErr::NixError ({:?})", err),
&PgFutureErr::Utf8Error (ref err) => write! (ft, "PgFutureErr::Utf8Error ({:?})", err),
&PgFutureErr::Sql (ref se) => write! (ft, "PgFutureErr ({:?}, {}, {})", se.imp.op.query_pieces, se.sqlstate, se.message),
&PgFutureErr::Json (ref err) => write! (ft, "PgFutureErr::Json ({:?})", err),
&PgFutureErr::Int (ref err) => write! (ft, "PgFutureErr::Int ({:?})", err),
&PgFutureErr::Float (ref err) => write! (ft, "PgFutureErr::Float ({:?})", err),
&PgFutureErr::UnknownType (ref fname, oid) => write! (ft, "PgFutureErr::UnknownType (fname '{}', oid {})", fname, oid)}}}
impl fmt::Display for PgFutureErr {
fn fmt (&self, ft: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
&PgFutureErr::PoisonError => ft.write_str ("PgFutureErr::PoisonError"),
&PgFutureErr::SendError (ref err) => write! (ft, "PgFutureErr::SendError ({})", err),
&PgFutureErr::NixError (ref err) => write! (ft, "PgFutureErr::NixError ({})", err),
&PgFutureErr::Utf8Error (ref err) => write! (ft, "PgFutureErr::Utf8Error ({})", err),
&PgFutureErr::Sql (ref se) => ft.write_str (&se.message),
&PgFutureErr::Json (ref err) => write! (ft, "PgFutureErr::Json ({})", err),
&PgFutureErr::Int (ref err) => write! (ft, "PgFutureErr::Int ({})", err),
&PgFutureErr::Float (ref err) => write! (ft, "PgFutureErr::Float ({})", err),
&PgFutureErr::UnknownType (ref fname, oid) => write! (ft, "Column '{}' has unfamiliar OID {}", fname, oid)}}}
impl Error for PgFutureErr {
fn description (&self) -> &str {
match self {
&PgFutureErr::PoisonError => "PgFutureErr::PoisonError",
&PgFutureErr::SendError (_) => "PgFutureErr::SendError",
&PgFutureErr::NixError (_) => "PgFutureErr::NixError",
&PgFutureErr::Utf8Error (_) => "PgFutureErr::Utf8Error",
&PgFutureErr::Sql (ref se) => &se.message[..],
&PgFutureErr::Json (_) => "PgFutureErr::Json",
&PgFutureErr::Int (_) => "PgFutureErr::Int",
&PgFutureErr::Float (_) => "PgFutureErr::Float",
&PgFutureErr::UnknownType (..) => "PgFutureErr::UnknownType"}}}
impl<T> From<PoisonError<T>> for PgFutureErr {
fn from (_err: PoisonError<T>) -> PgFutureErr {
PgFutureErr::PoisonError}}
impl From<Utf8Error> for PgFutureErr {
fn from (err: Utf8Error) -> PgFutureErr {
PgFutureErr::Utf8Error (err)}}
impl From<serde_json::Error> for PgFutureErr {
fn from (err: serde_json::Error) -> PgFutureErr {
PgFutureErr::Json (Arc::new (err))}}
impl From<std::num::ParseIntError> for PgFutureErr {
fn from (err: std::num::ParseIntError) -> PgFutureErr {
PgFutureErr::Int (err)}}
impl From<std::num::ParseFloatError> for PgFutureErr {
fn from (err: std::num::ParseFloatError) -> PgFutureErr {
PgFutureErr::Float (err)}}
impl<T> From<SendError<T>> for PgFutureErr {
fn from (err: SendError<T>) -> PgFutureErr {
PgFutureErr::SendError (format! ("{}", err))}}
impl From<nix::Error> for PgFutureErr {
fn from (err: nix::Error) -> PgFutureErr {
PgFutureErr::NixError (err)}}
#[derive(Clone)]
pub struct PgFuture (Arc<PgFutureImpl>);
impl PgFuture {
fn new (id: u64, op: PgOperation) -> PgFuture {
PgFuture (Arc::new (PgFutureImpl {
id: id,
op: op,
sync: Mutex::new (PgFutureSync {
results: Vec::new(),
task: None}),
miscarried: None}))}
fn error (err: PgFutureErr) -> PgFuture {
PgFuture (Arc::new (PgFutureImpl {
id: 0,
op: PgOperation {
query_pieces: Vec::new(),
statements: 0,
scheduling: PgSchedulingMode::AnythingGoes},
sync: Mutex::new (PgFutureSync {
results: Vec::new(),
task: None}),
miscarried: Some (Box::new (err))}))}}
impl fmt::Debug for PgFuture {
fn fmt (&self, ft: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if let Some (ref err) = self.0.miscarried {
write! (ft, "PgFuture ({:?})", err)
} else {
write! (ft, "PgFuture ({}, {:?})", self.0.id, self.0.op)}}}
impl Future for PgFuture {
type Item = Vec<PgResult>;
type Error = PgFutureErr;
fn poll (&mut self) -> Poll<Vec<PgResult>, PgFutureErr> {
if let Some (ref err) = self.0.miscarried {return Err (*err.clone())}
let mut sync = self.0.sync.lock()?;
if sync.results.is_empty() {
sync.task = Some (park());
return Ok (Async::NotReady)}
for (pr, num) in sync.results.iter().zip (0..) {
if let Some (status) = error_in_result (pr.res) {
let status = unsafe {CStr::from_ptr (pq::PQresStatus (status))} .to_str()?;
let sqlstate = unsafe {CStr::from_ptr (pq::PQresultErrorField (pr.res, pq::PG_DIAG_SQLSTATE))} .to_str()?;
let err = unsafe {CStr::from_ptr (pq::PQresultErrorMessage (pr.res))} .to_str()?;
return Err (PgFutureErr::Sql (PgSqlErr {
imp: self.0.clone(),
num: num,
status: status,
sqlstate: sqlstate.into(),
message: format! ("Error in statement {}: {}; {}", num, status, err)}))}}
let mut res = Vec::with_capacity (sync.results.len());
res.append (&mut sync.results);
Ok (Async::Ready (res))}}
#[derive(Debug)]
enum Message {
Connect (String, u8),
Execute (PgFuture),
Drop}
#[derive(Debug)]
struct Connection {
dsn: String,
handle: *mut pq::PGconn,
in_flight: VecDeque<PgFuture>,
pinned_pending_futures: VecDeque<PgFuture>,
connection_pending: bool,
in_flight_init: bool}
impl Connection {
fn free (&self) -> bool {
self.in_flight.is_empty() && !self.in_flight_init}}
fn error_in_result (res: *const pq::PGresult) -> Option<pq::ExecStatusType> {
let status = unsafe {pq::PQresultStatus (res)};
if status != pq::PGRES_COMMAND_OK && status != pq::PGRES_TUPLES_OK {Some (status)} else {None}}
const PIPELINE_LIM_COMMANDS: usize = 128;
const PIPELINE_LIM_BYTES: usize = 16384;
fn reconnect_heuristic (err: &str) -> bool {
err.starts_with ("server closed the connection unexpectedly") ||
err.starts_with ("SSL SYSCALL error")}
fn event_loop (rx: Receiver<Message>, read_end: c_int) {
use std::fmt::Write;
let mut connections: Vec<Connection> = Vec::new();
let mut pending_futures: VecDeque<PgFuture> = VecDeque::new();
let mut sql = String::with_capacity (PIPELINE_LIM_BYTES + 1024);
let mut sql_futures = Vec::with_capacity (PIPELINE_LIM_COMMANDS);
macro_rules! schedule {($pg_future: ident) => {{
match $pg_future.0.op.scheduling {
PgSchedulingMode::AnythingGoes => pending_futures.push_back ($pg_future),
PgSchedulingMode::PinToConnection (n) => connections[n as usize].pinned_pending_futures.push_back ($pg_future)}}}};
macro_rules! reschedule {($conn: ident, $pg_future: ident) => {{
match $pg_future.0.op.scheduling {
PgSchedulingMode::AnythingGoes => pending_futures.push_back ($pg_future),
PgSchedulingMode::PinToConnection (_) => $conn.pinned_pending_futures.push_back ($pg_future)}}}};
let mut fds = Vec::new();
'event_loop: loop {
{ let mut tmp: [u8; 256] = unsafe {std::mem::uninitialized()}; let _ = nix::unistd::read (read_end, &mut tmp); }
loop {match rx.try_recv() {
Err (TryRecvError::Disconnected) => break 'event_loop,
Err (TryRecvError::Empty) => break,
Ok (message) => match message {
Message::Connect (dsn, mul) => {
let dsn_c = CString::new (&dsn[..]) .expect ("!dsn");
for _ in 0 .. mul {
let conn = unsafe {pq::PQconnectStart (dsn_c.as_ptr())};
if conn == null_mut() {panic! ("!PQconnectStart")}
connections.push (Connection {
dsn: dsn.clone(),
handle: conn,
in_flight: VecDeque::new(),
pinned_pending_futures: VecDeque::new(),
connection_pending: true,
in_flight_init: false});}},
Message::Execute (pg_future) => schedule! (pg_future),
Message::Drop => break 'event_loop}}}
fds.clear();
for conn in connections.iter_mut().filter (|conn| conn.connection_pending) {
let status = unsafe {pq::PQstatus (conn.handle)};
if status == pq::CONNECTION_BAD {
unsafe {pq::PQreset (conn.handle)};
} else if status == pq::CONNECTION_OK {
let rc = unsafe {pq::PQsetnonblocking (conn.handle, 1)};
if rc != 0 {panic! ("!PQsetnonblocking: {}", error_message (conn.handle))}
let rc = unsafe {pq::PQsendQuery (conn.handle, "SET synchronous_commit = off\0".as_ptr() as *const c_char)};
if rc == 0 {panic! ("!PQsendQuery: {}", error_message (conn.handle))}
conn.connection_pending = false;
conn.in_flight_init = true;
} else {
let sock = unsafe {pq::PQsocket (conn.handle)};
match unsafe {pq::PQconnectPoll (conn.handle)} {
pq::PGRES_POLLING_READING => fds.push (PollFd::new (sock, poll::POLLIN, EventFlags::empty())),
pq::PGRES_POLLING_WRITING => fds.push (PollFd::new (sock, poll::POLLOUT, EventFlags::empty())),
_ => ()};}}
for conn in connections.iter_mut().filter (|conn| !conn.connection_pending && conn.free()) {
if pending_futures.is_empty() && conn.pinned_pending_futures.is_empty() {continue}
sql.clear();
sql_futures.clear();
let mut first = true;
loop {
if sql.len() >= PIPELINE_LIM_BYTES {break}
if sql_futures.len() + 1 >= PIPELINE_LIM_COMMANDS {break}
let pending = match pending_futures.pop_front() {
Some (f) => f,
None => match conn.pinned_pending_futures.pop_front() {
Some (f) => f,
None => break}};
if first {first = false} else {sql.push_str ("; ")}
write! (&mut sql, "BEGIN; SELECT {} AS future_id; ", pending.0.id) .expect ("!write");
for piece in pending.0.op.query_pieces.iter() {
match piece {
&PgQueryPiece::Static (ref ss) => sql.push_str (ss),
&PgQueryPiece::Plain (ref plain) => sql.push_str (&plain),
&PgQueryPiece::Literal (ref literal) => {
let esc = unsafe {pq::PQescapeLiteral (conn.handle, literal.as_ptr() as *const c_char, literal.len())};
if esc == null_mut() {panic! ("!PQescapeLiteral: {}", error_message (conn.handle))}
sql.push_str (unsafe {CStr::from_ptr (esc)} .to_str().expect ("!esc"));
unsafe {pq::PQfreemem (esc as *mut c_void)};},
&PgQueryPiece::Bytea (ref bytes) => {
let mut escaped_size: size_t = 0;
let esc = unsafe {pq::PQescapeByteaConn (conn.handle, bytes.as_ptr(), bytes.len(), &mut escaped_size)};
if esc == null_mut() {panic! ("!PQescapeByteaConn: {}", error_message (conn.handle))}
assert! (escaped_size > 0);
let esc_slice = unsafe {from_raw_parts (esc, escaped_size - 1)};
sql.push_str (unsafe {from_utf8_unchecked (esc_slice)});
unsafe {pq::PQfreemem (esc as *mut c_void)};}}}
sql.push_str ("; COMMIT");
sql_futures.push (pending)}
let res = unsafe {pq::PQgetResult (conn.handle)};
if res != null_mut() {panic! ("Stray result detected before PQsendQuery! {:?}", res);}
let sql = CString::new (&sql[..]) .expect ("sql !CString");
let rc = unsafe {pq::PQsendQuery (conn.handle, sql.as_ptr())};
if rc == 0 {
let err = error_message (conn.handle);
if reconnect_heuristic (&err) {
unsafe {pq::PQreset (conn.handle)};
conn.connection_pending = true;
for future in sql_futures.drain (..) {reschedule! (conn, future)}
continue}
panic! ("!PQsendQuery: {}", error_message (conn.handle))}
conn.in_flight.extend (sql_futures.drain (..));}
'connections_loop: for conn in connections.iter_mut().filter (|conn| !conn.connection_pending) {
if !conn.free() {
let sock = unsafe {pq::PQsocket (conn.handle)};
let rc = unsafe {pq::PQconsumeInput (conn.handle)};
if rc != 1 {
let err = error_message (conn.handle);
if reconnect_heuristic (&err) {
unsafe {pq::PQreset (conn.handle)};
conn.connection_pending = true;
for future in conn.in_flight.drain (..) {reschedule! (conn, future)}
continue 'connections_loop}
panic! ("!PQconsumeInput: {}", err)}
let rc = unsafe {pq::PQflush (conn.handle)};
if rc == 1 {fds.push (PollFd::new (sock, poll::POLLOUT, EventFlags::empty()))}
loop {
if unsafe {pq::PQisBusy (conn.handle)} == 1 {break}
let mut error = false;
let mut after_future = false;
if conn.in_flight_init {
conn.in_flight_init = false;
let res = unsafe {pq::PQgetResult (conn.handle)};
if res == null_mut() {panic! ("Got no result for in_flight_init statement")}
error = error_in_result (res) .is_some()
} else {
let pg_future = match conn.in_flight.pop_front() {Some (f) => f, None => break};
after_future = true;
{ let begin_res = unsafe {pq::PQgetResult (conn.handle)};
if begin_res == null_mut() {panic! ("Got no BEGIN result for {:?}", pg_future)}
if let Some (error_status) = error_in_result (begin_res) {
let sqlstate = unsafe {CStr::from_ptr (pq::PQresultErrorField (begin_res, pq::PG_DIAG_SQLSTATE))} .to_str() .expect ("!to_str");
if sqlstate == "57P01" {
unsafe {pq::PQreset (conn.handle)};
conn.connection_pending = true;
reschedule! (conn, pg_future);
for future in conn.in_flight.drain (..) {reschedule! (conn, future)}
continue 'connections_loop}
let status = unsafe {CStr::from_ptr (pq::PQresStatus (error_status))} .to_str() .expect ("!to_str");
let err = unsafe {CStr::from_ptr (pq::PQresultErrorMessage (begin_res))} .to_str() .expect ("!to_str");
panic! ("BEGIN failed. Probably a syntax error in one of the pipelined SQL statements. {}, {},\n{}", status, sqlstate, err);}
unsafe {pq::PQclear (begin_res)} }
let mut sync = pg_future.0.sync.lock().expect ("!lock");
if !error {
let id_res = unsafe {pq::PQgetResult (conn.handle)};
if id_res == null_mut() {panic! ("Got no ID result for {:?}", pg_future)}
if error_in_result (id_res) .is_some() {panic! ("Error in ID")}
assert_eq! (unsafe {pq::PQntuples (id_res)}, 1);
assert_eq! (unsafe {pq::PQnfields (id_res)}, 1);
let id = unsafe {CStr::from_ptr (pq::PQgetvalue (id_res, 0, 0))} .to_str() .expect ("!to_str");
let id: u64 = id.parse().expect ("!id");
assert_eq! (id, pg_future.0.id);
unsafe {pq::PQclear (id_res)} }
let expect_results = pg_future.0.op.statements as usize + 1;
sync.results.reserve_exact (expect_results);
for num in 0..expect_results {
if error {break}
let statement_res = unsafe {pq::PQgetResult (conn.handle)};
if statement_res == null_mut() {panic! ("Got no statement {} result for {:?}", num, pg_future)}
error = error_in_result (statement_res) .is_some();
sync.results.push (PgResult {
res: statement_res,
rows: unsafe {pq::PQntuples (statement_res)} as u32,
columns: unsafe {pq::PQnfields (statement_res)} as u32});}
if let Some (ref task) = sync.task {task.unpark()}}
if error {
if after_future {
let res = unsafe {pq::PQgetResult (conn.handle)};
if res != null_mut() {panic! ("Unexpected result after an error")}
let rc = unsafe {pq::PQsendQuery (conn.handle, "ROLLBACK\0".as_ptr() as *const c_char)};
if rc == 0 {panic! ("!PQsendQuery: {}", error_message (conn.handle))}
conn.in_flight_init = true}
for future in conn.in_flight.drain (..) {reschedule! (conn, future)}}}
fds.push (PollFd::new (sock, poll::POLLIN, EventFlags::empty()))}}
fds.push (PollFd::new (read_end, poll::POLLIN, EventFlags::empty()));
let rc = poll::poll (&mut fds, 100) .expect ("!poll");
if rc == -1 {panic! ("!poll: {}", io::Error::last_os_error())}}
for conn in connections {unsafe {pq::PQfinish (conn.handle)}}}
pub struct Cluster {
thread: Option<JoinHandle<()>>,
tx: Mutex<Sender<Message>>,
write_end: c_int,
command_num: AtomicU64}
impl Cluster {
pub fn new() -> Result<Cluster, String> {
let (tx, rx) = channel();
let (read_end, write_end) = try_s! (nix::unistd::pipe2 (O_NONBLOCK | O_CLOEXEC));
let thread = try_s! (std::thread::Builder::new().name ("pg_async".into()) .spawn (move || event_loop (rx, read_end)));
Ok (Cluster {
thread: Some (thread),
tx: Mutex::new (tx),
write_end: write_end,
command_num: AtomicU64::new (0)})}
pub fn connect (&self, dsn: String, mul: u8) -> Result<(), String> {
try_s! (try_s! (self.tx.lock()) .send (Message::Connect (dsn, mul)));
try_s! (nix::unistd::write (self.write_end, &[1]));
Ok(())}
pub fn execute<I: IntoQueryPieces> (&self, sql: I) -> PgFuture {
self.command_num.compare_and_swap (u64::max_value(), 0, Ordering::Relaxed);
let id = self.command_num.fetch_add (1, Ordering::Relaxed) + 1;
let pg_future = PgFuture::new (id, sql.into_query_pieces());
{ let tx = match self.tx.lock() {Ok (k) => k, Err (err) => return PgFuture::error (err.into())};
if let Err (err) = tx.send (Message::Execute (pg_future.clone())) {return PgFuture::error (err.into())}; }
if let Err (err) = nix::unistd::write (self.write_end, &[2]) {panic! ("!write on write_end: {}", err)};
pg_future}}
impl Drop for Cluster {
fn drop (&mut self) {
if let Ok (tx) = self.tx.lock() {
let _ = tx.send (Message::Drop);}
let _ = nix::unistd::write (self.write_end, &[3]);
let mut thread = None;
std::mem::swap (&mut thread, &mut self.thread);
if let Some (thread) = thread {let _ = thread.join();}}}
fn error_message (conn: *const pq::PGconn) -> String {
let err = unsafe {pq::PQerrorMessage (conn)};
let err = unsafe {CStr::from_ptr (err)};
err.to_string_lossy().into()}
pub mod pq {
use libc::{c_char, c_int, c_uint, c_void, size_t};
pub enum PGconn {}
pub type ConnStatusType = c_uint;
pub const CONNECTION_OK: c_uint = 0;
pub const CONNECTION_BAD: c_uint = 1;
pub const CONNECTION_STARTED: c_uint = 2;
pub const CONNECTION_MADE: c_uint = 3;
pub const CONNECTION_AWAITING_RESPONSE: c_uint = 4;
pub const CONNECTION_AUTH_OK: c_uint = 5;
pub const CONNECTION_SETENV: c_uint = 6;
pub const CONNECTION_SSL_STARTUP: c_uint = 7;
pub const CONNECTION_NEEDED: c_uint = 8;
pub type PostgresPollingStatusType = c_uint;
pub const PGRES_POLLING_FAILED: c_uint = 0;
pub const PGRES_POLLING_READING: c_uint = 1;
pub const PGRES_POLLING_WRITING: c_uint = 2;
pub const PGRES_POLLING_OK: c_uint = 3;
pub const PGRES_POLLING_ACTIVE: c_uint = 4;
pub enum PGresult {}
pub type ExecStatusType = c_uint;
pub const PGRES_EMPTY_QUERY: c_uint = 0;
pub const PGRES_COMMAND_OK: c_uint = 1;
pub const PGRES_TUPLES_OK: c_uint = 2;
pub const PGRES_COPY_OUT: c_uint = 3;
pub const PGRES_COPY_IN: c_uint = 4;
pub const PGRES_BAD_RESPONSE: c_uint = 5;
pub const PGRES_NONFATAL_ERROR: c_uint = 6;
pub const PGRES_FATAL_ERROR: c_uint = 7;
pub const PGRES_COPY_BOTH: c_uint = 8;
pub const PGRES_SINGLE_TUPLE: c_uint = 9;
pub type Oid = c_uint;
pub const PG_DIAG_SQLSTATE: c_int = 'C' as c_int;
#[link(name = "pq")] extern {
pub fn PQisthreadsafe() -> c_int;
pub fn PQconnectdb (conninfo: *const c_char) -> *mut PGconn;
pub fn PQconnectStart (conninfo: *const c_char) -> *mut PGconn;
pub fn PQstatus (conn: *const PGconn) -> ConnStatusType;
pub fn PQreset (conn: *const PGconn);
pub fn PQconnectPoll (conn: *mut PGconn) -> PostgresPollingStatusType;
pub fn PQsocket (conn: *const PGconn) -> c_int;
pub fn PQsetnonblocking (conn: *mut PGconn, arg: c_int) -> c_int;
pub fn PQfinish (conn: *mut PGconn);
pub fn PQescapeLiteral (conn: *const PGconn, str: *const c_char, len: size_t) -> *mut c_char;
pub fn PQescapeByteaConn (conn: *const PGconn, from: *const u8, from_length: size_t, to_length: *mut size_t) -> *mut u8;
pub fn PQunescapeBytea (from: *const u8, to_length: *mut size_t)-> *mut u8;
pub fn PQfreemem (ptr: *mut c_void);
pub fn PQsendQuery (conn: *mut PGconn, command: *const c_char) -> c_int;
pub fn PQflush (conn: *mut PGconn) -> c_int;
pub fn PQconsumeInput (conn: *mut PGconn) -> c_int;
pub fn PQisBusy (conn: *mut PGconn) -> c_int;
pub fn PQgetResult (conn: *mut PGconn) -> *mut PGresult;
pub fn PQresultStatus (res: *const PGresult) -> ExecStatusType;
pub fn PQresStatus (status: ExecStatusType) -> *mut c_char;
pub fn PQresultErrorMessage (res: *const PGresult) -> *mut c_char;
pub fn PQresultErrorField (res: *const PGresult, fieldcode: c_int) -> *mut c_char;
pub fn PQntuples (res: *const PGresult) -> c_int;
pub fn PQnfields (res: *const PGresult) -> c_int;
pub fn PQfname (res: *const PGresult, field_num: c_int) -> *mut c_char;
pub fn PQftype (res: *const PGresult, field_num: c_int) -> Oid;
pub fn PQgetisnull (res: *const PGresult, tup_num: c_int, field_num: c_int) -> c_int;
pub fn PQgetvalue (res: *const PGresult, tup_num: c_int, field_num: c_int) -> *mut c_char;
pub fn PQgetlength (res: *const PGresult, tup_num: c_int, field_num: c_int) -> c_int;
pub fn PQcmdStatus (res: *mut PGresult) -> *mut c_char;
pub fn PQcmdTuples (res: *mut PGresult) -> *mut c_char;
pub fn PQoidValue (res: *const PGresult) -> Oid;
pub fn PQclear (result: *mut PGresult);
pub fn PQerrorMessage (conn: *const PGconn) -> *const c_char;}}