-
-
Notifications
You must be signed in to change notification settings - Fork 476
/
Copy pathmain.rs
1000 lines (848 loc) · 25.6 KB
/
main.rs
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
#![warn(rust_2018_idioms)]
use bytes::{Bytes, BytesMut};
use futures_channel::mpsc;
use futures_util::{
future, join, pin_mut, stream, try_join, Future, FutureExt, SinkExt, StreamExt, TryStreamExt,
};
use pin_project_lite::pin_project;
use std::fmt::Write;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::time;
use tokio_postgres::error::SqlState;
use tokio_postgres::tls::{NoTls, NoTlsStream};
use tokio_postgres::types::{Kind, Type};
use tokio_postgres::{
AsyncMessage, Client, Config, Connection, Error, IsolationLevel, SimpleQueryMessage,
};
mod binary_copy;
mod parse;
#[cfg(feature = "runtime")]
mod runtime;
mod types;
pin_project! {
/// Polls `F` at most `polls_left` times returning `Some(F::Output)` if
/// [`Future`] returned [`Poll::Ready`] or [`None`] otherwise.
struct Cancellable<F> {
#[pin]
fut: F,
polls_left: usize,
}
}
impl<F: Future> Future for Cancellable<F> {
type Output = Option<F::Output>;
fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match this.fut.poll(ctx) {
Poll::Ready(r) => Poll::Ready(Some(r)),
Poll::Pending => {
*this.polls_left = this.polls_left.saturating_sub(1);
if *this.polls_left == 0 {
Poll::Ready(None)
} else {
Poll::Pending
}
}
}
}
}
async fn connect_raw(s: &str) -> Result<(Client, Connection<TcpStream, NoTlsStream>), Error> {
let socket = TcpStream::connect("127.0.0.1:5433").await.unwrap();
let config = s.parse::<Config>().unwrap();
config.connect_raw(socket, NoTls).await
}
async fn connect(s: &str) -> Client {
let (client, connection) = connect_raw(s).await.unwrap();
let connection = connection.map(|r| r.unwrap());
tokio::spawn(connection);
client
}
async fn current_transaction_id(client: &Client) -> i64 {
client
.query("SELECT txid_current()", &[])
.await
.unwrap()
.pop()
.unwrap()
.get::<_, i64>("txid_current")
}
async fn in_transaction(client: &Client) -> bool {
current_transaction_id(client).await == current_transaction_id(client).await
}
#[tokio::test]
async fn plain_password_missing() {
connect_raw("user=pass_user dbname=postgres")
.await
.err()
.unwrap();
}
#[tokio::test]
async fn plain_password_wrong() {
match connect_raw("user=pass_user password=foo dbname=postgres").await {
Ok(_) => panic!("unexpected success"),
Err(ref e) if e.code() == Some(&SqlState::INVALID_PASSWORD) => {}
Err(e) => panic!("{}", e),
}
}
#[tokio::test]
async fn plain_password_ok() {
connect("user=pass_user password=password dbname=postgres").await;
}
#[tokio::test]
async fn md5_password_missing() {
connect_raw("user=md5_user dbname=postgres")
.await
.err()
.unwrap();
}
#[tokio::test]
async fn md5_password_wrong() {
match connect_raw("user=md5_user password=foo dbname=postgres").await {
Ok(_) => panic!("unexpected success"),
Err(ref e) if e.code() == Some(&SqlState::INVALID_PASSWORD) => {}
Err(e) => panic!("{}", e),
}
}
#[tokio::test]
async fn md5_password_ok() {
connect("user=md5_user password=password dbname=postgres").await;
}
#[tokio::test]
async fn scram_password_missing() {
connect_raw("user=scram_user dbname=postgres")
.await
.err()
.unwrap();
}
#[tokio::test]
async fn scram_password_wrong() {
match connect_raw("user=scram_user password=foo dbname=postgres").await {
Ok(_) => panic!("unexpected success"),
Err(ref e) if e.code() == Some(&SqlState::INVALID_PASSWORD) => {}
Err(e) => panic!("{}", e),
}
}
#[tokio::test]
async fn scram_password_ok() {
connect("user=scram_user password=password dbname=postgres").await;
}
#[tokio::test]
async fn pipelined_prepare() {
let client = connect("user=postgres").await;
let prepare1 = client.prepare("SELECT $1::HSTORE[]");
let prepare2 = client.prepare("SELECT $1::BIGINT");
let (statement1, statement2) = try_join!(prepare1, prepare2).unwrap();
assert_eq!(statement1.params()[0].name(), "_hstore");
assert_eq!(statement1.columns()[0].type_().name(), "_hstore");
assert_eq!(statement2.params()[0], Type::INT8);
assert_eq!(statement2.columns()[0].type_(), &Type::INT8);
}
#[tokio::test]
async fn insert_select() {
let client = connect("user=postgres").await;
client
.batch_execute("CREATE TEMPORARY TABLE foo (id SERIAL, name TEXT)")
.await
.unwrap();
let insert = client.prepare("INSERT INTO foo (name) VALUES ($1), ($2)");
let select = client.prepare("SELECT id, name FROM foo ORDER BY id");
let (insert, select) = try_join!(insert, select).unwrap();
let insert = client.execute(&insert, &[&"alice", &"bob"]);
let select = client.query(&select, &[]);
let (_, rows) = try_join!(insert, select).unwrap();
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].get::<_, i32>(0), 1);
assert_eq!(rows[0].get::<_, &str>(1), "alice");
assert_eq!(rows[1].get::<_, i32>(0), 2);
assert_eq!(rows[1].get::<_, &str>(1), "bob");
}
#[tokio::test]
async fn custom_enum() {
let client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TYPE pg_temp.mood AS ENUM (
'sad',
'ok',
'happy'
)",
)
.await
.unwrap();
let select = client.prepare("SELECT $1::mood").await.unwrap();
let ty = &select.params()[0];
assert_eq!("mood", ty.name());
assert_eq!(
&Kind::Enum(vec![
"sad".to_string(),
"ok".to_string(),
"happy".to_string(),
]),
ty.kind(),
);
}
#[tokio::test]
async fn custom_domain() {
let client = connect("user=postgres").await;
client
.batch_execute("CREATE DOMAIN pg_temp.session_id AS bytea CHECK(octet_length(VALUE) = 16)")
.await
.unwrap();
let select = client.prepare("SELECT $1::session_id").await.unwrap();
let ty = &select.params()[0];
assert_eq!("session_id", ty.name());
assert_eq!(&Kind::Domain(Type::BYTEA), ty.kind());
}
#[tokio::test]
async fn custom_array() {
let client = connect("user=postgres").await;
let select = client.prepare("SELECT $1::HSTORE[]").await.unwrap();
let ty = &select.params()[0];
assert_eq!("_hstore", ty.name());
match ty.kind() {
Kind::Array(ty) => {
assert_eq!("hstore", ty.name());
assert_eq!(&Kind::Simple, ty.kind());
}
_ => panic!("unexpected kind"),
}
}
#[tokio::test]
async fn custom_composite() {
let client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TYPE pg_temp.inventory_item AS (
name TEXT,
supplier INTEGER,
price NUMERIC
)",
)
.await
.unwrap();
let select = client.prepare("SELECT $1::inventory_item").await.unwrap();
let ty = &select.params()[0];
assert_eq!(ty.name(), "inventory_item");
match ty.kind() {
Kind::Composite(fields) => {
assert_eq!(fields[0].name(), "name");
assert_eq!(fields[0].type_(), &Type::TEXT);
assert_eq!(fields[1].name(), "supplier");
assert_eq!(fields[1].type_(), &Type::INT4);
assert_eq!(fields[2].name(), "price");
assert_eq!(fields[2].type_(), &Type::NUMERIC);
}
_ => panic!("unexpected kind"),
}
}
#[tokio::test]
async fn custom_range() {
let client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TYPE pg_temp.floatrange AS RANGE (
subtype = float8,
subtype_diff = float8mi
)",
)
.await
.unwrap();
let select = client.prepare("SELECT $1::floatrange").await.unwrap();
let ty = &select.params()[0];
assert_eq!("floatrange", ty.name());
assert_eq!(&Kind::Range(Type::FLOAT8), ty.kind());
}
#[tokio::test]
#[allow(clippy::get_first)]
async fn simple_query() {
let client = connect("user=postgres").await;
let messages = client
.simple_query(
"CREATE TEMPORARY TABLE foo (
id SERIAL,
name TEXT
);
INSERT INTO foo (name) VALUES ('steven'), ('joe');
SELECT * FROM foo ORDER BY id;",
)
.await
.unwrap();
match messages[0] {
SimpleQueryMessage::CommandComplete(0) => {}
_ => panic!("unexpected message"),
}
match messages[1] {
SimpleQueryMessage::CommandComplete(2) => {}
_ => panic!("unexpected message"),
}
match &messages[2] {
SimpleQueryMessage::Row(row) => {
assert_eq!(row.columns().get(0).map(|c| c.name()), Some("id"));
assert_eq!(row.columns().get(1).map(|c| c.name()), Some("name"));
assert_eq!(row.get(0), Some("1"));
assert_eq!(row.get(1), Some("steven"));
}
_ => panic!("unexpected message"),
}
match &messages[3] {
SimpleQueryMessage::Row(row) => {
assert_eq!(row.columns().get(0).map(|c| c.name()), Some("id"));
assert_eq!(row.columns().get(1).map(|c| c.name()), Some("name"));
assert_eq!(row.get(0), Some("2"));
assert_eq!(row.get(1), Some("joe"));
}
_ => panic!("unexpected message"),
}
match messages[4] {
SimpleQueryMessage::CommandComplete(2) => {}
_ => panic!("unexpected message"),
}
assert_eq!(messages.len(), 5);
}
#[tokio::test]
async fn cancel_query_raw() {
let client = connect("user=postgres").await;
let socket = TcpStream::connect("127.0.0.1:5433").await.unwrap();
let cancel_token = client.cancel_token();
let cancel = cancel_token.cancel_query_raw(socket, NoTls);
let cancel = time::sleep(Duration::from_millis(100)).then(|()| cancel);
let sleep = client.batch_execute("SELECT pg_sleep(100)");
match join!(sleep, cancel) {
(Err(ref e), Ok(())) if e.code() == Some(&SqlState::QUERY_CANCELED) => {}
t => panic!("unexpected return: {:?}", t),
}
}
#[tokio::test]
async fn transaction_commit() {
let mut client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo(
id SERIAL,
name TEXT
)",
)
.await
.unwrap();
let transaction = client.transaction().await.unwrap();
transaction
.batch_execute("INSERT INTO foo (name) VALUES ('steven')")
.await
.unwrap();
transaction.commit().await.unwrap();
let stmt = client.prepare("SELECT name FROM foo").await.unwrap();
let rows = client.query(&stmt, &[]).await.unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].get::<_, &str>(0), "steven");
}
#[tokio::test]
async fn transaction_rollback() {
let mut client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo(
id SERIAL,
name TEXT
)",
)
.await
.unwrap();
let transaction = client.transaction().await.unwrap();
transaction
.batch_execute("INSERT INTO foo (name) VALUES ('steven')")
.await
.unwrap();
transaction.rollback().await.unwrap();
let stmt = client.prepare("SELECT name FROM foo").await.unwrap();
let rows = client.query(&stmt, &[]).await.unwrap();
assert_eq!(rows.len(), 0);
}
#[tokio::test]
async fn transaction_future_cancellation() {
let mut client = connect("user=postgres").await;
for i in 0.. {
let done = {
let txn = client.transaction();
let fut = Cancellable {
fut: txn,
polls_left: i,
};
fut.await
.map(|res| res.expect("transaction failed"))
.is_some()
};
assert!(!in_transaction(&client).await);
if done {
break;
}
}
}
#[tokio::test]
async fn transaction_commit_future_cancellation() {
let mut client = connect("user=postgres").await;
for i in 0.. {
let done = {
let txn = client.transaction().await.unwrap();
let commit = txn.commit();
let fut = Cancellable {
fut: commit,
polls_left: i,
};
fut.await
.map(|res| res.expect("transaction failed"))
.is_some()
};
assert!(!in_transaction(&client).await);
if done {
break;
}
}
}
#[tokio::test]
async fn transaction_rollback_future_cancellation() {
let mut client = connect("user=postgres").await;
for i in 0.. {
let done = {
let txn = client.transaction().await.unwrap();
let rollback = txn.rollback();
let fut = Cancellable {
fut: rollback,
polls_left: i,
};
fut.await
.map(|res| res.expect("transaction failed"))
.is_some()
};
assert!(!in_transaction(&client).await);
if done {
break;
}
}
}
#[tokio::test]
async fn transaction_rollback_drop() {
let mut client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo(
id SERIAL,
name TEXT
)",
)
.await
.unwrap();
let transaction = client.transaction().await.unwrap();
transaction
.batch_execute("INSERT INTO foo (name) VALUES ('steven')")
.await
.unwrap();
drop(transaction);
let stmt = client.prepare("SELECT name FROM foo").await.unwrap();
let rows = client.query(&stmt, &[]).await.unwrap();
assert_eq!(rows.len(), 0);
}
#[tokio::test]
async fn transaction_builder() {
let mut client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo(
id SERIAL,
name TEXT
)",
)
.await
.unwrap();
let transaction = client
.build_transaction()
.isolation_level(IsolationLevel::Serializable)
.read_only(true)
.deferrable(true)
.start()
.await
.unwrap();
transaction
.batch_execute("INSERT INTO foo (name) VALUES ('steven')")
.await
.unwrap();
transaction.commit().await.unwrap();
let stmt = client.prepare("SELECT name FROM foo").await.unwrap();
let rows = client.query(&stmt, &[]).await.unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].get::<_, &str>(0), "steven");
}
#[tokio::test]
async fn copy_in() {
let client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo (
id INTEGER,
name TEXT
)",
)
.await
.unwrap();
let mut stream = stream::iter(
vec![
Bytes::from_static(b"1\tjim\n"),
Bytes::from_static(b"2\tjoe\n"),
]
.into_iter()
.map(Ok::<_, Error>),
);
let sink = client.copy_in("COPY foo FROM STDIN").await.unwrap();
pin_mut!(sink);
sink.send_all(&mut stream).await.unwrap();
let rows = sink.finish().await.unwrap();
assert_eq!(rows, 2);
let rows = client
.query("SELECT id, name FROM foo ORDER BY id", &[])
.await
.unwrap();
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].get::<_, i32>(0), 1);
assert_eq!(rows[0].get::<_, &str>(1), "jim");
assert_eq!(rows[1].get::<_, i32>(0), 2);
assert_eq!(rows[1].get::<_, &str>(1), "joe");
}
#[tokio::test]
async fn copy_in_large() {
let client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo (
id INTEGER,
name TEXT
)",
)
.await
.unwrap();
let a = Bytes::from_static(b"0\tname0\n");
let mut b = BytesMut::new();
for i in 1..5_000 {
writeln!(b, "{0}\tname{0}", i).unwrap();
}
let mut c = BytesMut::new();
for i in 5_000..10_000 {
writeln!(c, "{0}\tname{0}", i).unwrap();
}
let mut stream = stream::iter(
vec![a, b.freeze(), c.freeze()]
.into_iter()
.map(Ok::<_, Error>),
);
let sink = client.copy_in("COPY foo FROM STDIN").await.unwrap();
pin_mut!(sink);
sink.send_all(&mut stream).await.unwrap();
let rows = sink.finish().await.unwrap();
assert_eq!(rows, 10_000);
}
#[tokio::test]
async fn copy_in_error() {
let client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo (
id INTEGER,
name TEXT
)",
)
.await
.unwrap();
{
let sink = client.copy_in("COPY foo FROM STDIN").await.unwrap();
pin_mut!(sink);
sink.send(Bytes::from_static(b"1\tsteven")).await.unwrap();
}
let rows = client
.query("SELECT id, name FROM foo ORDER BY id", &[])
.await
.unwrap();
assert_eq!(rows.len(), 0);
}
#[tokio::test]
async fn copy_out() {
let client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo (
id SERIAL,
name TEXT
);
INSERT INTO foo (name) VALUES ('jim'), ('joe');",
)
.await
.unwrap();
let stmt = client.prepare("COPY foo TO STDOUT").await.unwrap();
let data = client
.copy_out(&stmt)
.await
.unwrap()
.try_fold(BytesMut::new(), |mut buf, chunk| async move {
buf.extend_from_slice(&chunk);
Ok(buf)
})
.await
.unwrap();
assert_eq!(&data[..], b"1\tjim\n2\tjoe\n");
}
#[tokio::test]
async fn notices() {
let long_name = "x".repeat(65);
let (client, mut connection) =
connect_raw(&format!("user=postgres application_name={}", long_name,))
.await
.unwrap();
let (tx, rx) = mpsc::unbounded();
let stream =
stream::poll_fn(move |cx| connection.poll_message(cx)).map_err(|e| panic!("{}", e));
let connection = stream.forward(tx).map(|r| r.unwrap());
tokio::spawn(connection);
client
.batch_execute("DROP DATABASE IF EXISTS noexistdb")
.await
.unwrap();
drop(client);
let notices = rx
.filter_map(|m| match m {
AsyncMessage::Notice(n) => future::ready(Some(n)),
_ => future::ready(None),
})
.collect::<Vec<_>>()
.await;
assert_eq!(notices.len(), 2);
assert_eq!(
notices[0].message(),
"identifier \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" \
will be truncated to \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\""
);
assert_eq!(
notices[1].message(),
"database \"noexistdb\" does not exist, skipping"
);
}
#[tokio::test]
async fn notifications() {
let (client, mut connection) = connect_raw("user=postgres").await.unwrap();
let (tx, rx) = mpsc::unbounded();
let stream =
stream::poll_fn(move |cx| connection.poll_message(cx)).map_err(|e| panic!("{}", e));
let connection = stream.forward(tx).map(|r| r.unwrap());
tokio::spawn(connection);
client
.batch_execute(
"LISTEN test_notifications;
NOTIFY test_notifications, 'hello';
NOTIFY test_notifications, 'world';",
)
.await
.unwrap();
drop(client);
let notifications = rx
.filter_map(|m| match m {
AsyncMessage::Notification(n) => future::ready(Some(n)),
_ => future::ready(None),
})
.collect::<Vec<_>>()
.await;
assert_eq!(notifications.len(), 2);
assert_eq!(notifications[0].channel(), "test_notifications");
assert_eq!(notifications[0].payload(), "hello");
assert_eq!(notifications[1].channel(), "test_notifications");
assert_eq!(notifications[1].payload(), "world");
}
#[tokio::test]
async fn query_portal() {
let mut client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE foo (
id SERIAL,
name TEXT
);
INSERT INTO foo (name) VALUES ('alice'), ('bob'), ('charlie');",
)
.await
.unwrap();
let stmt = client
.prepare("SELECT id, name FROM foo ORDER BY id")
.await
.unwrap();
let transaction = client.transaction().await.unwrap();
let portal = transaction.bind(&stmt, &[]).await.unwrap();
let f1 = transaction.query_portal(&portal, 2);
let f2 = transaction.query_portal(&portal, 2);
let f3 = transaction.query_portal(&portal, 2);
let (r1, r2, r3) = try_join!(f1, f2, f3).unwrap();
assert_eq!(r1.len(), 2);
assert_eq!(r1[0].get::<_, i32>(0), 1);
assert_eq!(r1[0].get::<_, &str>(1), "alice");
assert_eq!(r1[1].get::<_, i32>(0), 2);
assert_eq!(r1[1].get::<_, &str>(1), "bob");
assert_eq!(r2.len(), 1);
assert_eq!(r2[0].get::<_, i32>(0), 3);
assert_eq!(r2[0].get::<_, &str>(1), "charlie");
assert_eq!(r3.len(), 0);
}
#[tokio::test]
async fn require_channel_binding() {
connect_raw("user=postgres channel_binding=require")
.await
.err()
.unwrap();
}
#[tokio::test]
async fn prefer_channel_binding() {
connect("user=postgres channel_binding=prefer").await;
}
#[tokio::test]
async fn disable_channel_binding() {
connect("user=postgres channel_binding=disable").await;
}
#[tokio::test]
async fn check_send() {
fn is_send<T: Send>(_: &T) {}
let f = connect("user=postgres");
is_send(&f);
let mut client = f.await;
let f = client.prepare("SELECT $1::TEXT");
is_send(&f);
let stmt = f.await.unwrap();
let f = client.query(&stmt, &[&"hello"]);
is_send(&f);
drop(f);
let f = client.execute(&stmt, &[&"hello"]);
is_send(&f);
drop(f);
let f = client.transaction();
is_send(&f);
let trans = f.await.unwrap();
let f = trans.query(&stmt, &[&"hello"]);
is_send(&f);
drop(f);
let f = trans.execute(&stmt, &[&"hello"]);
is_send(&f);
drop(f);
}
#[tokio::test]
async fn query_one() {
let client = connect("user=postgres").await;
client
.batch_execute(
"
CREATE TEMPORARY TABLE foo (
name TEXT
);
INSERT INTO foo (name) VALUES ('alice'), ('bob'), ('carol');
",
)
.await
.unwrap();
client
.query_one("SELECT * FROM foo WHERE name = 'dave'", &[])
.await
.err()
.unwrap();
client
.query_one("SELECT * FROM foo WHERE name = 'alice'", &[])
.await
.unwrap();
client
.query_one("SELECT * FROM foo", &[])
.await
.err()
.unwrap();
}
#[tokio::test]
async fn query_opt() {
let client = connect("user=postgres").await;
client
.batch_execute(
"
CREATE TEMPORARY TABLE foo (
name TEXT
);
INSERT INTO foo (name) VALUES ('alice'), ('bob'), ('carol');
",
)
.await
.unwrap();
assert!(client
.query_opt("SELECT * FROM foo WHERE name = 'dave'", &[])
.await
.unwrap()
.is_none());
client
.query_opt("SELECT * FROM foo WHERE name = 'alice'", &[])
.await
.unwrap()
.unwrap();
client
.query_one("SELECT * FROM foo", &[])
.await
.err()
.unwrap();
}
#[tokio::test]
async fn deferred_constraint() {
let client = connect("user=postgres").await;
client
.batch_execute(
"
CREATE TEMPORARY TABLE t (
i INT,
UNIQUE (i) DEFERRABLE INITIALLY DEFERRED
);
",
)
.await
.unwrap();
client
.execute("INSERT INTO t (i) VALUES (1)", &[])
.await
.unwrap();
client
.execute("INSERT INTO t (i) VALUES (1)", &[])
.await
.unwrap_err();
}
#[tokio::test]
async fn query_opt_scalar() {
let client = connect("user=postgres").await;
client
.batch_execute(
"CREATE TEMPORARY TABLE person (
id serial,
name text NOT NULL,
age integer
);
INSERT INTO person (name, age) VALUES ('steven', 18);
INSERT INTO person (name, age) VALUES ('fred', NULL);
",
)
.await
.unwrap();
let age: Option<i32> = client
.query_opt_scalar("SELECT age FROM person WHERE name = $1", &[&"steven"])
.await
.unwrap();
assert_eq!(age, Some(18));
let age: Option<Option<i32>> = client
.query_opt_scalar("SELECT age FROM person WHERE name = $1", &[&"fred"])
.await
.unwrap();
assert_eq!(age, Some(None));
let age: Option<Option<i32>> = client
.query_opt_scalar("SELECT age FROM person WHERE name = $1", &[&"steven"])
.await
.unwrap();
assert_eq!(age, Some(Some(18)));
let age: Option<Option<i32>> = client
.query_opt_scalar("SELECT age FROM person WHERE name = $1", &[&"barney"])
.await
.unwrap();
assert_eq!(age, None);
}