-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathpostgres.rs
2102 lines (1663 loc) · 59 KB
/
postgres.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
use futures::{Stream, StreamExt, TryStreamExt};
use sqlx::postgres::types::Oid;
use sqlx::postgres::{
PgAdvisoryLock, PgConnectOptions, PgConnection, PgDatabaseError, PgErrorPosition, PgListener,
PgPoolOptions, PgRow, PgSeverity, Postgres,
};
use sqlx::{Column, Connection, Executor, Row, Statement, TypeInfo};
use sqlx_core::{bytes::Bytes, error::BoxDynError};
use sqlx_test::{new, pool, setup_if_needed};
use std::env;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
#[sqlx_macros::test]
async fn it_connects() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let value = sqlx::query("select 1 + 1")
.try_map(|row: PgRow| row.try_get::<i32, _>(0))
.fetch_one(&mut conn)
.await?;
assert_eq!(2i32, value);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_select_void() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
// pg_notify just happens to be a function that returns void
let _: () = sqlx::query_scalar("select pg_notify('chan', 'message');")
.fetch_one(&mut conn)
.await?;
Ok(())
}
#[sqlx_macros::test]
async fn it_pings() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.ping().await?;
Ok(())
}
#[sqlx_macros::test]
async fn it_pings_after_suspended_query() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
sqlx::raw_sql("create temporary table processed_row(val int4 primary key)")
.execute(&mut conn)
.await?;
// This query wants to return 50 rows but we only read the first one.
// This will return a `SuspendedPortal` that the driver currently ignores.
let _: i32 = sqlx::query_scalar(
r#"
insert into processed_row(val)
select * from generate_series(1, 50)
returning val
"#,
)
.fetch_one(&mut conn)
.await?;
// `Sync` closes the current autocommit transaction which presumably includes closing any
// suspended portals.
conn.ping().await?;
// Make sure that all the values got inserted even though we only read the first one back.
let count: i64 = sqlx::query_scalar("select count(*) from processed_row")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 50);
Ok(())
}
#[sqlx_macros::test]
async fn it_maths() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let value = sqlx::query("select 1 + $1::int")
.bind(5_i32)
.try_map(|row: PgRow| row.try_get::<i32, _>(0))
.fetch_one(&mut conn)
.await?;
assert_eq!(6i32, value);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_inspect_errors() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let res: Result<_, sqlx::Error> = sqlx::query("select f").execute(&mut conn).await;
let err = res.unwrap_err();
// can also do [as_database_error] or use `match ..`
let err = err.into_database_error().unwrap();
assert_eq!(err.message(), "column \"f\" does not exist");
assert_eq!(err.code().as_deref(), Some("42703"));
// can also do [downcast_ref]
let err: Box<PgDatabaseError> = err.downcast();
assert_eq!(err.severity(), PgSeverity::Error);
assert_eq!(err.message(), "column \"f\" does not exist");
assert_eq!(err.code(), "42703");
assert_eq!(err.position(), Some(PgErrorPosition::Original(8)));
assert_eq!(err.routine(), Some("errorMissingColumn"));
assert_eq!(err.constraint(), None);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_inspect_constraint_errors() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let res: Result<_, sqlx::Error> =
sqlx::query("INSERT INTO products VALUES (1, 'Product 1', 0);")
.execute(&mut conn)
.await;
let err = res.unwrap_err();
// can also do [as_database_error] or use `match ..`
let err = err.into_database_error().unwrap();
assert_eq!(
err.message(),
"new row for relation \"products\" violates check constraint \"products_price_check\""
);
assert_eq!(err.code().as_deref(), Some("23514"));
// can also do [downcast_ref]
let err: Box<PgDatabaseError> = err.downcast();
assert_eq!(err.severity(), PgSeverity::Error);
assert_eq!(
err.message(),
"new row for relation \"products\" violates check constraint \"products_price_check\""
);
assert_eq!(err.code(), "23514");
assert_eq!(err.position(), None);
assert_eq!(err.routine(), Some("ExecConstraints"));
assert_eq!(err.constraint(), Some("products_price_check"));
Ok(())
}
#[sqlx_macros::test]
async fn it_executes() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let _ = conn
.execute(
r#"
CREATE TEMPORARY TABLE users (id INTEGER PRIMARY KEY);
"#,
)
.await?;
for index in 1..=10_i32 {
let done = sqlx::query("INSERT INTO users (id) VALUES ($1)")
.bind(index)
.execute(&mut conn)
.await?;
assert_eq!(done.rows_affected(), 1);
}
let sum: i32 = sqlx::query("SELECT id FROM users")
.try_map(|row: PgRow| row.try_get::<i32, _>(0))
.fetch(&mut conn)
.try_fold(0_i32, |acc, x| async move { Ok(acc + x) })
.await?;
assert_eq!(sum, 55);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_nest_map() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let res = sqlx::query("SELECT 5")
.map(|row: PgRow| row.get(0))
.map(|int: i32| int.to_string())
.fetch_one(&mut conn)
.await?;
assert_eq!(res, "5");
Ok(())
}
#[cfg(feature = "json")]
#[sqlx_macros::test]
async fn it_describes_and_inserts_json_and_jsonb() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let _ = conn
.execute(
r#"
CREATE TEMPORARY TABLE json_stuff (obj json, obj2 jsonb);
"#,
)
.await?;
let query = "INSERT INTO json_stuff (obj, obj2) VALUES ($1, $2)";
let _ = conn.describe(query).await?;
let done = sqlx::query(query)
.bind(serde_json::json!({ "a": "a" }))
.bind(serde_json::json!({ "a": "a" }))
.execute(&mut conn)
.await?;
assert_eq!(done.rows_affected(), 1);
Ok(())
}
#[sqlx_macros::test]
async fn it_works_with_cache_disabled() -> anyhow::Result<()> {
setup_if_needed();
let mut url = url::Url::parse(&env::var("DATABASE_URL")?)?;
url.query_pairs_mut()
.append_pair("statement-cache-capacity", "0");
let mut conn = PgConnection::connect(url.as_ref()).await?;
for index in 1..=10_i32 {
let _ = sqlx::query("SELECT $1")
.bind(index)
.execute(&mut conn)
.await?;
}
Ok(())
}
#[sqlx_macros::test]
async fn it_executes_with_pool() -> anyhow::Result<()> {
let pool = sqlx_test::pool::<Postgres>().await?;
let rows = pool.fetch_all("SELECT 1; SElECT 2").await?;
assert_eq!(rows.len(), 2);
Ok(())
}
// https://github.com/launchbadge/sqlx/issues/104
#[sqlx_macros::test]
async fn it_can_return_interleaved_nulls_issue_104() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let tuple = sqlx::query("SELECT NULL, 10::INT, NULL, 20::INT, NULL, 40::INT, NULL, 80::INT")
.map(|row: PgRow| {
(
row.get::<Option<i32>, _>(0),
row.get::<Option<i32>, _>(1),
row.get::<Option<i32>, _>(2),
row.get::<Option<i32>, _>(3),
row.get::<Option<i32>, _>(4),
row.get::<Option<i32>, _>(5),
row.get::<Option<i32>, _>(6),
row.get::<Option<i32>, _>(7),
)
})
.fetch_one(&mut conn)
.await?;
assert_eq!(tuple.0, None);
assert_eq!(tuple.1, Some(10));
assert_eq!(tuple.2, None);
assert_eq!(tuple.3, Some(20));
assert_eq!(tuple.4, None);
assert_eq!(tuple.5, Some(40));
assert_eq!(tuple.6, None);
assert_eq!(tuple.7, Some(80));
Ok(())
}
#[sqlx_macros::test]
async fn it_can_fail_and_recover() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
for i in 0..10 {
// make a query that will fail
let res = conn
.execute("INSERT INTO not_found (column) VALUES (10)")
.await;
assert!(res.is_err());
// now try and use the connection
let val: i32 = conn.fetch_one(&*format!("SELECT {i}::int4")).await?.get(0);
assert_eq!(val, i);
}
Ok(())
}
#[sqlx_macros::test]
async fn it_can_fail_and_recover_with_pool() -> anyhow::Result<()> {
let pool = sqlx_test::pool::<Postgres>().await?;
for i in 0..10 {
// make a query that will fail
let res = pool
.execute("INSERT INTO not_found (column) VALUES (10)")
.await;
assert!(res.is_err());
// now try and use the connection
let val: i32 = pool.fetch_one(&*format!("SELECT {i}::int4")).await?.get(0);
assert_eq!(val, i);
}
Ok(())
}
#[sqlx_macros::test]
async fn it_can_query_scalar() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let scalar: i32 = sqlx::query_scalar("SELECT 42").fetch_one(&mut conn).await?;
assert_eq!(scalar, 42);
let scalar: Option<i32> = sqlx::query_scalar("SELECT 42").fetch_one(&mut conn).await?;
assert_eq!(scalar, Some(42));
let scalar: Option<i32> = sqlx::query_scalar("SELECT NULL")
.fetch_one(&mut conn)
.await?;
assert_eq!(scalar, None);
let scalar: Option<i64> = sqlx::query_scalar("SELECT 42::bigint")
.fetch_optional(&mut conn)
.await?;
assert_eq!(scalar, Some(42));
let scalar: Option<i16> = sqlx::query_scalar("").fetch_optional(&mut conn).await?;
assert_eq!(scalar, None);
Ok(())
}
#[sqlx_macros::test]
/// This is separate from `it_can_query_scalar` because while implementing it I ran into a
/// bug which that prevented `Vec<i32>` from compiling but allowed Vec<Option<i32>>.
async fn it_can_query_all_scalar() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let scalar: Vec<i32> = sqlx::query_scalar("SELECT $1")
.bind(42)
.fetch_all(&mut conn)
.await?;
assert_eq!(scalar, vec![42]);
let scalar: Vec<Option<i32>> = sqlx::query_scalar("SELECT $1 UNION ALL SELECT NULL")
.bind(42)
.fetch_all(&mut conn)
.await?;
assert_eq!(scalar, vec![Some(42), None]);
Ok(())
}
#[ignore]
#[sqlx_macros::test]
async fn copy_can_work_with_failed_transactions() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
// We're using a (local) statement_timeout to simulate a runtime failure, as opposed to
// a parse/plan failure.
let mut tx = conn.begin().await?;
let _ = sqlx::query("SELECT pg_catalog.set_config($1, $2, true)")
.bind("statement_timeout")
.bind("1ms")
.execute(tx.as_mut())
.await?;
let mut copy_out: Pin<
Box<dyn Stream<Item = Result<Bytes, sqlx::Error>> + Send>,
> = (&mut tx)
.copy_out_raw("COPY (SELECT nspname FROM pg_catalog.pg_namespace WHERE pg_sleep(0.001) IS NULL) TO STDOUT")
.await?;
while copy_out.try_next().await.is_ok() {}
drop(copy_out);
tx.rollback().await?;
// conn should be usable again, as we explictly rolled back the transaction
let got: i32 = sqlx::query_scalar("SELECT 1")
.fetch_one(conn.as_mut())
.await?;
assert_eq!(1, got);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_work_with_failed_transactions() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
// We're using a (local) statement_timeout to simulate a runtime failure, as opposed to
// a parse/plan failure.
let mut tx = conn.begin().await?;
let _ = sqlx::query("SELECT pg_catalog.set_config($1, $2, true)")
.bind("statement_timeout")
.bind("1ms")
.execute(tx.as_mut())
.await?;
assert!(sqlx::query("SELECT 1 WHERE pg_sleep(0.30) IS NULL")
.fetch_one(tx.as_mut())
.await
.is_err());
tx.rollback().await?;
// conn should be usable again, as we explictly rolled back the transaction
let got: i32 = sqlx::query_scalar("SELECT 1")
.fetch_one(conn.as_mut())
.await?;
assert_eq!(1, got);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_work_with_transactions() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_1922 (id INTEGER PRIMARY KEY)")
.await?;
conn.execute("TRUNCATE _sqlx_users_1922").await?;
// begin .. rollback
let mut tx = conn.begin().await?;
sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
.bind(10_i32)
.execute(&mut *tx)
.await?;
tx.rollback().await?;
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 0);
// begin .. commit
let mut tx = conn.begin().await?;
sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
.bind(10_i32)
.execute(&mut *tx)
.await?;
tx.commit().await?;
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 1);
// begin .. (drop)
{
let mut tx = conn.begin().await?;
sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
.bind(20_i32)
.execute(&mut *tx)
.await?;
}
conn = new::<Postgres>().await?;
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 1);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_work_with_nested_transactions() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_2523 (id INTEGER PRIMARY KEY)")
.await?;
conn.execute("TRUNCATE _sqlx_users_2523").await?;
// begin
let mut tx = conn.begin().await?; // transaction
// insert a user
sqlx::query("INSERT INTO _sqlx_users_2523 (id) VALUES ($1)")
.bind(50_i32)
.execute(&mut *tx)
.await?;
// begin once more
let mut tx2 = tx.begin().await?; // savepoint
// insert another user
sqlx::query("INSERT INTO _sqlx_users_2523 (id) VALUES ($1)")
.bind(10_i32)
.execute(&mut *tx2)
.await?;
// never mind, rollback
tx2.rollback().await?; // roll that one back
// did we really?
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_2523")
.fetch_one(&mut *tx)
.await?;
assert_eq!(count, 1);
// actually, commit
tx.commit().await?;
// did we really?
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_2523")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 1);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_drop_multiple_transactions() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_3952 (id INTEGER PRIMARY KEY)")
.await?;
conn.execute("TRUNCATE _sqlx_users_3952").await?;
// begin .. (drop)
// run 2 times to see what happens if we drop transactions repeatedly
for _ in 0..2 {
{
let mut tx = conn.begin().await?;
// do actually something before dropping
let _user = sqlx::query("INSERT INTO _sqlx_users_3952 (id) VALUES ($1) RETURNING id")
.bind(20_i32)
.fetch_one(&mut *tx)
.await?;
}
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_3952")
.fetch_one(&mut conn)
.await?;
assert_eq!(count, 0);
}
Ok(())
}
// run with `cargo test --features postgres -- --ignored --nocapture pool_smoke_test`
#[ignore]
#[sqlx_macros::test]
async fn pool_smoke_test() -> anyhow::Result<()> {
use futures::{future, task::Poll, Future};
eprintln!("starting pool");
let pool = PgPoolOptions::new()
.acquire_timeout(Duration::from_secs(5))
.min_connections(1)
.max_connections(1)
.connect(&dotenvy::var("DATABASE_URL")?)
.await?;
// spin up more tasks than connections available, and ensure we don't deadlock
for i in 0..200 {
let pool = pool.clone();
sqlx_core::rt::spawn(async move {
for j in 0.. {
if let Err(e) = sqlx::query("select 1 + 1").execute(&pool).await {
// normal error at termination of the test
if matches!(e, sqlx::Error::PoolClosed) {
eprintln!("pool task {i} exiting normally after {j} iterations");
} else {
eprintln!("pool task {i} dying due to {e} after {j} iterations");
}
break;
}
// shouldn't be necessary if the pool is fair
// sqlx_core::rt::yield_now().await;
}
});
}
// spawn a bunch of tasks that attempt to acquire but give up to ensure correct handling
// of cancellations
for _ in 0..50 {
let pool = pool.clone();
sqlx_core::rt::spawn(async move {
while !pool.is_closed() {
let acquire = pool.acquire();
futures::pin_mut!(acquire);
// poll the acquire future once to put the waiter in the queue
future::poll_fn(move |cx| {
let _ = acquire.as_mut().poll(cx);
Poll::Ready(())
})
.await;
// this one is necessary since this is a hot loop,
// otherwise this task will never be descheduled
sqlx_core::rt::yield_now().await;
}
});
}
eprintln!("sleeping for 30 seconds");
sqlx_core::rt::sleep(Duration::from_secs(30)).await;
// assert_eq!(pool.size(), 10);
eprintln!("closing pool");
sqlx_core::rt::timeout(Duration::from_secs(30), pool.close()).await?;
eprintln!("pool closed successfully");
Ok(())
}
#[sqlx_macros::test]
async fn test_invalid_query() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
conn.execute("definitely not a correct query")
.await
.unwrap_err();
let mut s = conn.fetch("select 1");
let row = s.try_next().await?.unwrap();
assert_eq!(row.get::<i32, _>(0), 1i32);
Ok(())
}
/// Tests the edge case of executing a completely empty query string.
///
/// This gets flagged as an `EmptyQueryResponse` in Postgres. We
/// catch this and just return no rows.
#[sqlx_macros::test]
async fn test_empty_query() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let done = conn.execute("").await?;
assert_eq!(done.rows_affected(), 0);
Ok(())
}
/// Test a simple select expression. This should return the row.
#[sqlx_macros::test]
async fn test_select_expression() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let mut s = conn.fetch("SELECT 5");
let row = s.try_next().await?.unwrap();
assert!(5i32 == row.try_get::<i32, _>(0)?);
Ok(())
}
/// Test that we can interleave reads and writes to the database
/// in one simple query. Using the `Cursor` API we should be
/// able to fetch from both queries in sequence.
#[sqlx_macros::test]
async fn test_multi_read_write() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let mut s = conn.fetch(
"
CREATE TABLE IF NOT EXISTS _sqlx_test_postgres_5112 (
id BIGSERIAL PRIMARY KEY,
text TEXT NOT NULL
);
SELECT 'Hello World' as _1;
INSERT INTO _sqlx_test_postgres_5112 (text) VALUES ('this is a test');
SELECT id, text FROM _sqlx_test_postgres_5112;
",
);
let row = s.try_next().await?.unwrap();
assert!("Hello World" == row.try_get::<&str, _>("_1")?);
let row = s.try_next().await?.unwrap();
let id: i64 = row.try_get("id")?;
let text: &str = row.try_get("text")?;
assert_eq!(1_i64, id);
assert_eq!("this is a test", text);
Ok(())
}
#[sqlx_macros::test]
async fn it_caches_statements() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
for i in 0..2 {
let row = sqlx::query("SELECT $1 AS val")
.bind(Oid(i))
.persistent(true)
.fetch_one(&mut conn)
.await?;
let val: Oid = row.get("val");
assert_eq!(Oid(i), val);
}
assert_eq!(1, conn.cached_statements_size());
conn.clear_cached_statements().await?;
assert_eq!(0, conn.cached_statements_size());
for i in 0..2 {
let row = sqlx::query("SELECT $1 AS val")
.bind(Oid(i))
.persistent(false)
.fetch_one(&mut conn)
.await?;
let val: Oid = row.get("val");
assert_eq!(Oid(i), val);
}
assert_eq!(0, conn.cached_statements_size());
Ok(())
}
#[sqlx_macros::test]
async fn it_closes_statement_from_cache_issue_470() -> anyhow::Result<()> {
sqlx_test::setup_if_needed();
let mut options: PgConnectOptions = env::var("DATABASE_URL")?.parse().unwrap();
// a capacity of 1 means that before each statement (after the first)
// we will close the previous statement
options = options.statement_cache_capacity(1);
let mut conn = PgConnection::connect_with(&options).await?;
for i in 0..5 {
let row = sqlx::query(&*format!("SELECT {i}::int4 AS val"))
.fetch_one(&mut conn)
.await?;
let val: i32 = row.get("val");
assert_eq!(i, val);
}
assert_eq!(1, conn.cached_statements_size());
Ok(())
}
#[sqlx_macros::test]
async fn it_sets_application_name() -> anyhow::Result<()> {
sqlx_test::setup_if_needed();
let mut options: PgConnectOptions = env::var("DATABASE_URL")?.parse().unwrap();
options = options.application_name("some-name");
let mut conn = PgConnection::connect_with(&options).await?;
let row = sqlx::query("select current_setting('application_name') as app_name")
.fetch_one(&mut conn)
.await?;
let val: String = row.get("app_name");
assert_eq!("some-name", &val);
Ok(())
}
#[sqlx_macros::test]
async fn it_can_handle_parameter_status_message_issue_484() -> anyhow::Result<()> {
new::<Postgres>().await?.execute("SET NAMES 'UTF8'").await?;
Ok(())
}
#[sqlx_macros::test]
async fn it_can_prepare_then_execute() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let mut tx = conn.begin().await?;
let tweet_id: i64 =
sqlx::query_scalar("INSERT INTO tweet ( text ) VALUES ( 'Hello, World' ) RETURNING id")
.fetch_one(&mut *tx)
.await?;
let statement = tx.prepare("SELECT * FROM tweet WHERE id = $1").await?;
assert_eq!(statement.column(0).name(), "id");
assert_eq!(statement.column(1).name(), "created_at");
assert_eq!(statement.column(2).name(), "text");
assert_eq!(statement.column(3).name(), "owner_id");
assert_eq!(statement.column(0).type_info().name(), "INT8");
assert_eq!(statement.column(1).type_info().name(), "TIMESTAMPTZ");
assert_eq!(statement.column(2).type_info().name(), "TEXT");
assert_eq!(statement.column(3).type_info().name(), "INT8");
let row = statement.query().bind(tweet_id).fetch_one(&mut *tx).await?;
let tweet_text: &str = row.try_get("text")?;
assert_eq!(tweet_text, "Hello, World");
Ok(())
}
// repro is more reliable with the basic scheduler used by `#[tokio::test]`
#[cfg(feature = "_rt-tokio")]
#[tokio::test]
async fn test_issue_622() -> anyhow::Result<()> {
use std::time::Instant;
setup_if_needed();
let pool = PgPoolOptions::new()
.max_connections(1) // also fails with higher counts, e.g. 5
.connect(&std::env::var("DATABASE_URL").unwrap())
.await?;
println!("pool state: {pool:?}");
let mut handles = vec![];
// given repro spawned 100 tasks but I found it reliably reproduced with 3
for i in 0..3 {
let pool = pool.clone();
handles.push(sqlx_core::rt::spawn(async move {
{
let mut conn = pool.acquire().await.unwrap();
let _ = sqlx::query("SELECT 1").fetch_one(&mut *conn).await.unwrap();
// conn gets dropped here and should be returned to the pool
}
// (do some other work here without holding on to a connection)
// this actually fixes the issue, depending on the timeout used
// sqlx_core::rt::sleep(Duration::from_millis(500)).await;
{
let start = Instant::now();
match pool.acquire().await {
Ok(conn) => {
println!("{} acquire took {:?}", i, start.elapsed());
drop(conn);
}
Err(e) => panic!("{i} acquire returned error: {e} pool state: {pool:?}"),
}
}
Result::<(), anyhow::Error>::Ok(())
}));
}
futures::future::try_join_all(handles).await?;
Ok(())
}
#[sqlx_macros::test]
async fn test_describe_outer_join_nullable() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
// test nullability inference for various joins
// inner join, nullability should not be overridden
// language=PostgreSQL
let describe = conn
.describe(
"select tweet.id
from tweet
inner join products on products.name = tweet.text",
)
.await?;
assert_eq!(describe.nullable(0), Some(false));
// language=PostgreSQL
let describe = conn
.describe(
"select tweet.id
from (values (null)) vals(val)
left join tweet on false",
)
.await?;
// tweet.id is marked NOT NULL but it's brought in from a left-join here
// which should make it nullable
assert_eq!(describe.nullable(0), Some(true));
// make sure we don't mis-infer for the outer half of the join
// language=PostgreSQL
let describe = conn
.describe(
"select tweet1.id, tweet2.id
from tweet tweet1
left join tweet tweet2 on false",
)
.await?;
assert_eq!(describe.nullable(0), Some(false));
assert_eq!(describe.nullable(1), Some(true));
// right join, nullability should be inverted
// language=PostgreSQL
let describe = conn
.describe(
"select tweet1.id, tweet2.id
from tweet tweet1
right join tweet tweet2 on false",
)
.await?;
assert_eq!(describe.nullable(0), Some(true));
assert_eq!(describe.nullable(1), Some(false));
// full outer join, both tables are nullable
// language=PostgreSQL
let describe = conn
.describe(
"select tweet1.id, tweet2.id
from tweet tweet1
full join tweet tweet2 on false",
)
.await?;
assert_eq!(describe.nullable(0), Some(true));
assert_eq!(describe.nullable(1), Some(true));
Ok(())
}
#[sqlx_macros::test]
async fn test_listener_cleanup() -> anyhow::Result<()> {