Debian Codegraph @

tests/postgres/postgres.rs

raw symbols SCIP
1 use futures::{Stream, StreamExt, TryStreamExt};
2
3 use sqlx::postgres::types::Oid;
4 use sqlx::postgres::{
5 PgAdvisoryLock, PgConnectOptions, PgConnection, PgDatabaseError, PgErrorPosition, PgListener,
6 PgPoolOptions, PgRow, PgSeverity, Postgres,
7 };
8 use sqlx::{Column, Connection, Executor, Row, Statement, TypeInfo};
9 use sqlx_core::{bytes::Bytes, error::BoxDynError};
10 use sqlx_test::{new, pool, setup_if_needed};
11 use std::env;
12 use std::pin::Pin;
13 use std::sync::Arc;
14 use std::time::Duration;
15
16 #[sqlx_macros::test]
17 async fn it_connects() -> anyhow::Result<()> {
18 let mut conn = new::<Postgres>().await?;
19
20 let value = sqlx::query("select 1 + 1")
21 .try_map(|row: PgRow| row.try_get::<i32, _>(0))
22 .fetch_one(&mut conn)
23 .await?;
24
25 assert_eq!(2i32, value);
26
27 Ok(())
28 }
29
30 #[sqlx_macros::test]
31 async fn it_can_select_void() -> anyhow::Result<()> {
32 let mut conn = new::<Postgres>().await?;
33
34 // pg_notify just happens to be a function that returns void
35 let _: () = sqlx::query_scalar("select pg_notify('chan', 'message');")
36 .fetch_one(&mut conn)
37 .await?;
38
39 Ok(())
40 }
41
42 #[sqlx_macros::test]
43 async fn it_pings() -> anyhow::Result<()> {
44 let mut conn = new::<Postgres>().await?;
45
46 conn.ping().await?;
47
48 Ok(())
49 }
50
51 #[sqlx_macros::test]
52 async fn it_pings_after_suspended_query() -> anyhow::Result<()> {
53 let mut conn = new::<Postgres>().await?;
54
55 sqlx::raw_sql("create temporary table processed_row(val int4 primary key)")
56 .execute(&mut conn)
57 .await?;
58
59 // This query wants to return 50 rows but we only read the first one.
60 // This will return a `SuspendedPortal` that the driver currently ignores.
61 let _: i32 = sqlx::query_scalar(
62 r#"
63 insert into processed_row(val)
64 select * from generate_series(1, 50)
65 returning val
66 "#,
67 )
68 .fetch_one(&mut conn)
69 .await?;
70
71 // `Sync` closes the current autocommit transaction which presumably includes closing any
72 // suspended portals.
73 conn.ping().await?;
74
75 // Make sure that all the values got inserted even though we only read the first one back.
76 let count: i64 = sqlx::query_scalar("select count(*) from processed_row")
77 .fetch_one(&mut conn)
78 .await?;
79
80 assert_eq!(count, 50);
81
82 Ok(())
83 }
84
85 #[sqlx_macros::test]
86 async fn it_maths() -> anyhow::Result<()> {
87 let mut conn = new::<Postgres>().await?;
88
89 let value = sqlx::query("select 1 + $1::int")
90 .bind(5_i32)
91 .try_map(|row: PgRow| row.try_get::<i32, _>(0))
92 .fetch_one(&mut conn)
93 .await?;
94
95 assert_eq!(6i32, value);
96
97 Ok(())
98 }
99
100 #[sqlx_macros::test]
101 async fn it_can_inspect_errors() -> anyhow::Result<()> {
102 let mut conn = new::<Postgres>().await?;
103
104 let res: Result<_, sqlx::Error> = sqlx::query("select f").execute(&mut conn).await;
105 let err = res.unwrap_err();
106
107 // can also do [as_database_error] or use `match ..`
108 let err = err.into_database_error().unwrap();
109
110 assert_eq!(err.message(), "column \"f\" does not exist");
111 assert_eq!(err.code().as_deref(), Some("42703"));
112
113 // can also do [downcast_ref]
114 let err: Box<PgDatabaseError> = err.downcast();
115
116 assert_eq!(err.severity(), PgSeverity::Error);
117 assert_eq!(err.message(), "column \"f\" does not exist");
118 assert_eq!(err.code(), "42703");
119 assert_eq!(err.position(), Some(PgErrorPosition::Original(8)));
120 assert_eq!(err.routine(), Some("errorMissingColumn"));
121 assert_eq!(err.constraint(), None);
122
123 Ok(())
124 }
125
126 #[sqlx_macros::test]
127 async fn it_can_inspect_constraint_errors() -> anyhow::Result<()> {
128 let mut conn = new::<Postgres>().await?;
129
130 let res: Result<_, sqlx::Error> =
131 sqlx::query("INSERT INTO products VALUES (1, 'Product 1', 0);")
132 .execute(&mut conn)
133 .await;
134 let err = res.unwrap_err();
135
136 // can also do [as_database_error] or use `match ..`
137 let err = err.into_database_error().unwrap();
138
139 assert_eq!(
140 err.message(),
141 "new row for relation \"products\" violates check constraint \"products_price_check\""
142 );
143 assert_eq!(err.code().as_deref(), Some("23514"));
144
145 // can also do [downcast_ref]
146 let err: Box<PgDatabaseError> = err.downcast();
147
148 assert_eq!(err.severity(), PgSeverity::Error);
149 assert_eq!(
150 err.message(),
151 "new row for relation \"products\" violates check constraint \"products_price_check\""
152 );
153 assert_eq!(err.code(), "23514");
154 assert_eq!(err.position(), None);
155 assert_eq!(err.routine(), Some("ExecConstraints"));
156 assert_eq!(err.constraint(), Some("products_price_check"));
157
158 Ok(())
159 }
160
161 #[sqlx_macros::test]
162 async fn it_executes() -> anyhow::Result<()> {
163 let mut conn = new::<Postgres>().await?;
164
165 let _ = conn
166 .execute(
167 r#"
168 CREATE TEMPORARY TABLE users (id INTEGER PRIMARY KEY);
169 "#,
170 )
171 .await?;
172
173 for index in 1..=10_i32 {
174 let done = sqlx::query("INSERT INTO users (id) VALUES ($1)")
175 .bind(index)
176 .execute(&mut conn)
177 .await?;
178
179 assert_eq!(done.rows_affected(), 1);
180 }
181
182 let sum: i32 = sqlx::query("SELECT id FROM users")
183 .try_map(|row: PgRow| row.try_get::<i32, _>(0))
184 .fetch(&mut conn)
185 .try_fold(0_i32, |acc, x| async move { Ok(acc + x) })
186 .await?;
187
188 assert_eq!(sum, 55);
189
190 Ok(())
191 }
192
193 #[sqlx_macros::test]
194 async fn it_can_nest_map() -> anyhow::Result<()> {
195 let mut conn = new::<Postgres>().await?;
196
197 let res = sqlx::query("SELECT 5")
198 .map(|row: PgRow| row.get(0))
199 .map(|int: i32| int.to_string())
200 .fetch_one(&mut conn)
201 .await?;
202
203 assert_eq!(res, "5");
204
205 Ok(())
206 }
207
208 #[cfg(feature = "json")]
209 #[sqlx_macros::test]
210 async fn it_describes_and_inserts_json_and_jsonb() -> anyhow::Result<()> {
211 let mut conn = new::<Postgres>().await?;
212
213 let _ = conn
214 .execute(
215 r#"
216 CREATE TEMPORARY TABLE json_stuff (obj json, obj2 jsonb);
217 "#,
218 )
219 .await?;
220
221 let query = "INSERT INTO json_stuff (obj, obj2) VALUES ($1, $2)";
222 let _ = conn.describe(query).await?;
223
224 let done = sqlx::query(query)
225 .bind(serde_json::json!({ "a": "a" }))
226 .bind(serde_json::json!({ "a": "a" }))
227 .execute(&mut conn)
228 .await?;
229
230 assert_eq!(done.rows_affected(), 1);
231
232 Ok(())
233 }
234
235 #[sqlx_macros::test]
236 async fn it_works_with_cache_disabled() -> anyhow::Result<()> {
237 setup_if_needed();
238
239 let mut url = url::Url::parse(&env::var("DATABASE_URL")?)?;
240 url.query_pairs_mut()
241 .append_pair("statement-cache-capacity", "0");
242
243 let mut conn = PgConnection::connect(url.as_ref()).await?;
244
245 for index in 1..=10_i32 {
246 let _ = sqlx::query("SELECT $1")
247 .bind(index)
248 .execute(&mut conn)
249 .await?;
250 }
251
252 Ok(())
253 }
254
255 #[sqlx_macros::test]
256 async fn it_executes_with_pool() -> anyhow::Result<()> {
257 let pool = sqlx_test::pool::<Postgres>().await?;
258
259 let rows = pool.fetch_all("SELECT 1; SElECT 2").await?;
260
261 assert_eq!(rows.len(), 2);
262
263 Ok(())
264 }
265
266 // https://github.com/launchbadge/sqlx/issues/104
267 #[sqlx_macros::test]
268 async fn it_can_return_interleaved_nulls_issue_104() -> anyhow::Result<()> {
269 let mut conn = new::<Postgres>().await?;
270
271 let tuple = sqlx::query("SELECT NULL, 10::INT, NULL, 20::INT, NULL, 40::INT, NULL, 80::INT")
272 .map(|row: PgRow| {
273 (
274 row.get::<Option<i32>, _>(0),
275 row.get::<Option<i32>, _>(1),
276 row.get::<Option<i32>, _>(2),
277 row.get::<Option<i32>, _>(3),
278 row.get::<Option<i32>, _>(4),
279 row.get::<Option<i32>, _>(5),
280 row.get::<Option<i32>, _>(6),
281 row.get::<Option<i32>, _>(7),
282 )
283 })
284 .fetch_one(&mut conn)
285 .await?;
286
287 assert_eq!(tuple.0, None);
288 assert_eq!(tuple.1, Some(10));
289 assert_eq!(tuple.2, None);
290 assert_eq!(tuple.3, Some(20));
291 assert_eq!(tuple.4, None);
292 assert_eq!(tuple.5, Some(40));
293 assert_eq!(tuple.6, None);
294 assert_eq!(tuple.7, Some(80));
295
296 Ok(())
297 }
298
299 #[sqlx_macros::test]
300 async fn it_can_fail_and_recover() -> anyhow::Result<()> {
301 let mut conn = new::<Postgres>().await?;
302
303 for i in 0..10 {
304 // make a query that will fail
305 let res = conn
306 .execute("INSERT INTO not_found (column) VALUES (10)")
307 .await;
308
309 assert!(res.is_err());
310
311 // now try and use the connection
312 let val: i32 = conn.fetch_one(&*format!("SELECT {i}::int4")).await?.get(0);
313
314 assert_eq!(val, i);
315 }
316
317 Ok(())
318 }
319
320 #[sqlx_macros::test]
321 async fn it_can_fail_and_recover_with_pool() -> anyhow::Result<()> {
322 let pool = sqlx_test::pool::<Postgres>().await?;
323
324 for i in 0..10 {
325 // make a query that will fail
326 let res = pool
327 .execute("INSERT INTO not_found (column) VALUES (10)")
328 .await;
329
330 assert!(res.is_err());
331
332 // now try and use the connection
333 let val: i32 = pool.fetch_one(&*format!("SELECT {i}::int4")).await?.get(0);
334
335 assert_eq!(val, i);
336 }
337
338 Ok(())
339 }
340
341 #[sqlx_macros::test]
342 async fn it_can_query_scalar() -> anyhow::Result<()> {
343 let mut conn = new::<Postgres>().await?;
344
345 let scalar: i32 = sqlx::query_scalar("SELECT 42").fetch_one(&mut conn).await?;
346 assert_eq!(scalar, 42);
347
348 let scalar: Option<i32> = sqlx::query_scalar("SELECT 42").fetch_one(&mut conn).await?;
349 assert_eq!(scalar, Some(42));
350
351 let scalar: Option<i32> = sqlx::query_scalar("SELECT NULL")
352 .fetch_one(&mut conn)
353 .await?;
354 assert_eq!(scalar, None);
355
356 let scalar: Option<i64> = sqlx::query_scalar("SELECT 42::bigint")
357 .fetch_optional(&mut conn)
358 .await?;
359 assert_eq!(scalar, Some(42));
360
361 let scalar: Option<i16> = sqlx::query_scalar("").fetch_optional(&mut conn).await?;
362 assert_eq!(scalar, None);
363
364 Ok(())
365 }
366
367 #[sqlx_macros::test]
368 /// This is separate from `it_can_query_scalar` because while implementing it I ran into a
369 /// bug which that prevented `Vec<i32>` from compiling but allowed Vec<Option<i32>>.
370 async fn it_can_query_all_scalar() -> anyhow::Result<()> {
371 let mut conn = new::<Postgres>().await?;
372
373 let scalar: Vec<i32> = sqlx::query_scalar("SELECT $1")
374 .bind(42)
375 .fetch_all(&mut conn)
376 .await?;
377 assert_eq!(scalar, vec![42]);
378
379 let scalar: Vec<Option<i32>> = sqlx::query_scalar("SELECT $1 UNION ALL SELECT NULL")
380 .bind(42)
381 .fetch_all(&mut conn)
382 .await?;
383 assert_eq!(scalar, vec![Some(42), None]);
384
385 Ok(())
386 }
387
388 #[ignore]
389 #[sqlx_macros::test]
390 async fn copy_can_work_with_failed_transactions() -> anyhow::Result<()> {
391 let mut conn = new::<Postgres>().await?;
392
393 // We're using a (local) statement_timeout to simulate a runtime failure, as opposed to
394 // a parse/plan failure.
395 let mut tx = conn.begin().await?;
396 let _ = sqlx::query("SELECT pg_catalog.set_config($1, $2, true)")
397 .bind("statement_timeout")
398 .bind("1ms")
399 .execute(tx.as_mut())
400 .await?;
401
402 let mut copy_out: Pin<
403 Box<dyn Stream<Item = Result<Bytes, sqlx::Error>> + Send>,
404 > = (&mut tx)
405 .copy_out_raw("COPY (SELECT nspname FROM pg_catalog.pg_namespace WHERE pg_sleep(0.001) IS NULL) TO STDOUT")
406 .await?;
407
408 while copy_out.try_next().await.is_ok() {}
409 drop(copy_out);
410
411 tx.rollback().await?;
412
413 // conn should be usable again, as we explictly rolled back the transaction
414 let got: i32 = sqlx::query_scalar("SELECT 1")
415 .fetch_one(conn.as_mut())
416 .await?;
417 assert_eq!(1, got);
418
419 Ok(())
420 }
421
422 #[sqlx_macros::test]
423 async fn it_can_work_with_failed_transactions() -> anyhow::Result<()> {
424 let mut conn = new::<Postgres>().await?;
425
426 // We're using a (local) statement_timeout to simulate a runtime failure, as opposed to
427 // a parse/plan failure.
428 let mut tx = conn.begin().await?;
429 let _ = sqlx::query("SELECT pg_catalog.set_config($1, $2, true)")
430 .bind("statement_timeout")
431 .bind("1ms")
432 .execute(tx.as_mut())
433 .await?;
434
435 assert!(sqlx::query("SELECT 1 WHERE pg_sleep(0.30) IS NULL")
436 .fetch_one(tx.as_mut())
437 .await
438 .is_err());
439 tx.rollback().await?;
440
441 // conn should be usable again, as we explictly rolled back the transaction
442 let got: i32 = sqlx::query_scalar("SELECT 1")
443 .fetch_one(conn.as_mut())
444 .await?;
445 assert_eq!(1, got);
446
447 Ok(())
448 }
449
450 #[sqlx_macros::test]
451 async fn it_can_work_with_transactions() -> anyhow::Result<()> {
452 let mut conn = new::<Postgres>().await?;
453
454 conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_1922 (id INTEGER PRIMARY KEY)")
455 .await?;
456
457 conn.execute("TRUNCATE _sqlx_users_1922").await?;
458
459 // begin .. rollback
460
461 let mut tx = conn.begin().await?;
462
463 sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
464 .bind(10_i32)
465 .execute(&mut *tx)
466 .await?;
467
468 tx.rollback().await?;
469
470 let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
471 .fetch_one(&mut conn)
472 .await?;
473
474 assert_eq!(count, 0);
475
476 // begin .. commit
477
478 let mut tx = conn.begin().await?;
479
480 sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
481 .bind(10_i32)
482 .execute(&mut *tx)
483 .await?;
484
485 tx.commit().await?;
486
487 let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
488 .fetch_one(&mut conn)
489 .await?;
490
491 assert_eq!(count, 1);
492
493 // begin .. (drop)
494
495 {
496 let mut tx = conn.begin().await?;
497
498 sqlx::query("INSERT INTO _sqlx_users_1922 (id) VALUES ($1)")
499 .bind(20_i32)
500 .execute(&mut *tx)
501 .await?;
502 }
503
504 conn = new::<Postgres>().await?;
505
506 let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_1922")
507 .fetch_one(&mut conn)
508 .await?;
509
510 assert_eq!(count, 1);
511
512 Ok(())
513 }
514
515 #[sqlx_macros::test]
516 async fn it_can_work_with_nested_transactions() -> anyhow::Result<()> {
517 let mut conn = new::<Postgres>().await?;
518
519 conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_2523 (id INTEGER PRIMARY KEY)")
520 .await?;
521
522 conn.execute("TRUNCATE _sqlx_users_2523").await?;
523
524 // begin
525 let mut tx = conn.begin().await?; // transaction
526
527 // insert a user
528 sqlx::query("INSERT INTO _sqlx_users_2523 (id) VALUES ($1)")
529 .bind(50_i32)
530 .execute(&mut *tx)
531 .await?;
532
533 // begin once more
534 let mut tx2 = tx.begin().await?; // savepoint
535
536 // insert another user
537 sqlx::query("INSERT INTO _sqlx_users_2523 (id) VALUES ($1)")
538 .bind(10_i32)
539 .execute(&mut *tx2)
540 .await?;
541
542 // never mind, rollback
543 tx2.rollback().await?; // roll that one back
544
545 // did we really?
546 let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_2523")
547 .fetch_one(&mut *tx)
548 .await?;
549
550 assert_eq!(count, 1);
551
552 // actually, commit
553 tx.commit().await?;
554
555 // did we really?
556 let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_2523")
557 .fetch_one(&mut conn)
558 .await?;
559
560 assert_eq!(count, 1);
561
562 Ok(())
563 }
564
565 #[sqlx_macros::test]
566 async fn it_can_drop_multiple_transactions() -> anyhow::Result<()> {
567 let mut conn = new::<Postgres>().await?;
568
569 conn.execute("CREATE TABLE IF NOT EXISTS _sqlx_users_3952 (id INTEGER PRIMARY KEY)")
570 .await?;
571
572 conn.execute("TRUNCATE _sqlx_users_3952").await?;
573
574 // begin .. (drop)
575
576 // run 2 times to see what happens if we drop transactions repeatedly
577 for _ in 0..2 {
578 {
579 let mut tx = conn.begin().await?;
580
581 // do actually something before dropping
582 let _user = sqlx::query("INSERT INTO _sqlx_users_3952 (id) VALUES ($1) RETURNING id")
583 .bind(20_i32)
584 .fetch_one(&mut *tx)
585 .await?;
586 }
587
588 let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM _sqlx_users_3952")
589 .fetch_one(&mut conn)
590 .await?;
591
592 assert_eq!(count, 0);
593 }
594
595 Ok(())
596 }
597
598 // run with `cargo test --features postgres -- --ignored --nocapture pool_smoke_test`
599 #[ignore]
600 #[sqlx_macros::test]
601 async fn pool_smoke_test() -> anyhow::Result<()> {
602 use futures::{future, task::Poll, Future};
603
604 eprintln!("starting pool");
605
606 let pool = PgPoolOptions::new()
607 .acquire_timeout(Duration::from_secs(5))
608 .min_connections(1)
609 .max_connections(1)
610 .connect(&dotenvy::var("DATABASE_URL")?)
611 .await?;
612
613 // spin up more tasks than connections available, and ensure we don't deadlock
614 for i in 0..200 {
615 let pool = pool.clone();
616 sqlx_core::rt::spawn(async move {
617 for j in 0.. {
618 if let Err(e) = sqlx::query("select 1 + 1").execute(&pool).await {
619 // normal error at termination of the test
620 if matches!(e, sqlx::Error::PoolClosed) {
621 eprintln!("pool task {i} exiting normally after {j} iterations");
622 } else {
623 eprintln!("pool task {i} dying due to {e} after {j} iterations");
624 }
625 break;
626 }
627
628 // shouldn't be necessary if the pool is fair
629 // sqlx_core::rt::yield_now().await;
630 }
631 });
632 }
633
634 // spawn a bunch of tasks that attempt to acquire but give up to ensure correct handling
635 // of cancellations
636 for _ in 0..50 {
637 let pool = pool.clone();
638 sqlx_core::rt::spawn(async move {
639 while !pool.is_closed() {
640 let acquire = pool.acquire();
641 futures::pin_mut!(acquire);
642
643 // poll the acquire future once to put the waiter in the queue
644 future::poll_fn(move |cx| {
645 let _ = acquire.as_mut().poll(cx);
646 Poll::Ready(())
647 })
648 .await;
649
650 // this one is necessary since this is a hot loop,
651 // otherwise this task will never be descheduled
652 sqlx_core::rt::yield_now().await;
653 }
654 });
655 }
656
657 eprintln!("sleeping for 30 seconds");
658
659 sqlx_core::rt::sleep(Duration::from_secs(30)).await;
660
661 // assert_eq!(pool.size(), 10);
662
663 eprintln!("closing pool");
664
665 sqlx_core::rt::timeout(Duration::from_secs(30), pool.close()).await?;
666
667 eprintln!("pool closed successfully");
668
669 Ok(())
670 }
671
672 #[sqlx_macros::test]
673 async fn test_invalid_query() -> anyhow::Result<()> {
674 let mut conn = new::<Postgres>().await?;
675
676 conn.execute("definitely not a correct query")
677 .await
678 .unwrap_err();
679
680 let mut s = conn.fetch("select 1");
681 let row = s.try_next().await?.unwrap();
682
683 assert_eq!(row.get::<i32, _>(0), 1i32);
684
685 Ok(())
686 }
687
688 /// Tests the edge case of executing a completely empty query string.
689 ///
690 /// This gets flagged as an `EmptyQueryResponse` in Postgres. We
691 /// catch this and just return no rows.
692 #[sqlx_macros::test]
693 async fn test_empty_query() -> anyhow::Result<()> {
694 let mut conn = new::<Postgres>().await?;
695 let done = conn.execute("").await?;
696
697 assert_eq!(done.rows_affected(), 0);
698
699 Ok(())
700 }
701
702 /// Test a simple select expression. This should return the row.
703 #[sqlx_macros::test]
704 async fn test_select_expression() -> anyhow::Result<()> {
705 let mut conn = new::<Postgres>().await?;
706
707 let mut s = conn.fetch("SELECT 5");
708 let row = s.try_next().await?.unwrap();
709
710 assert!(5i32 == row.try_get::<i32, _>(0)?);
711
712 Ok(())
713 }
714
715 /// Test that we can interleave reads and writes to the database
716 /// in one simple query. Using the `Cursor` API we should be
717 /// able to fetch from both queries in sequence.
718 #[sqlx_macros::test]
719 async fn test_multi_read_write() -> anyhow::Result<()> {
720 let mut conn = new::<Postgres>().await?;
721
722 let mut s = conn.fetch(
723 "
724 CREATE TABLE IF NOT EXISTS _sqlx_test_postgres_5112 (
725 id BIGSERIAL PRIMARY KEY,
726 text TEXT NOT NULL
727 );
728
729 SELECT 'Hello World' as _1;
730
731 INSERT INTO _sqlx_test_postgres_5112 (text) VALUES ('this is a test');
732
733 SELECT id, text FROM _sqlx_test_postgres_5112;
734 ",
735 );
736
737 let row = s.try_next().await?.unwrap();
738
739 assert!("Hello World" == row.try_get::<&str, _>("_1")?);
740
741 let row = s.try_next().await?.unwrap();
742
743 let id: i64 = row.try_get("id")?;
744 let text: &str = row.try_get("text")?;
745
746 assert_eq!(1_i64, id);
747 assert_eq!("this is a test", text);
748
749 Ok(())
750 }
751
752 #[sqlx_macros::test]
753 async fn it_caches_statements() -> anyhow::Result<()> {
754 let mut conn = new::<Postgres>().await?;
755
756 for i in 0..2 {
757 let row = sqlx::query("SELECT $1 AS val")
758 .bind(Oid(i))
759 .persistent(true)
760 .fetch_one(&mut conn)
761 .await?;
762
763 let val: Oid = row.get("val");
764
765 assert_eq!(Oid(i), val);
766 }
767
768 assert_eq!(1, conn.cached_statements_size());
769 conn.clear_cached_statements().await?;
770 assert_eq!(0, conn.cached_statements_size());
771
772 for i in 0..2 {
773 let row = sqlx::query("SELECT $1 AS val")
774 .bind(Oid(i))
775 .persistent(false)
776 .fetch_one(&mut conn)
777 .await?;
778
779 let val: Oid = row.get("val");
780
781 assert_eq!(Oid(i), val);
782 }
783
784 assert_eq!(0, conn.cached_statements_size());
785
786 Ok(())
787 }
788
789 #[sqlx_macros::test]
790 async fn it_closes_statement_from_cache_issue_470() -> anyhow::Result<()> {
791 sqlx_test::setup_if_needed();
792
793 let mut options: PgConnectOptions = env::var("DATABASE_URL")?.parse().unwrap();
794
795 // a capacity of 1 means that before each statement (after the first)
796 // we will close the previous statement
797 options = options.statement_cache_capacity(1);
798
799 let mut conn = PgConnection::connect_with(&options).await?;
800
801 for i in 0..5 {
802 let row = sqlx::query(&*format!("SELECT {i}::int4 AS val"))
803 .fetch_one(&mut conn)
804 .await?;
805
806 let val: i32 = row.get("val");
807
808 assert_eq!(i, val);
809 }
810
811 assert_eq!(1, conn.cached_statements_size());
812
813 Ok(())
814 }
815
816 #[sqlx_macros::test]
817 async fn it_sets_application_name() -> anyhow::Result<()> {
818 sqlx_test::setup_if_needed();
819
820 let mut options: PgConnectOptions = env::var("DATABASE_URL")?.parse().unwrap();
821 options = options.application_name("some-name");
822
823 let mut conn = PgConnection::connect_with(&options).await?;
824
825 let row = sqlx::query("select current_setting('application_name') as app_name")
826 .fetch_one(&mut conn)
827 .await?;
828
829 let val: String = row.get("app_name");
830
831 assert_eq!("some-name", &val);
832
833 Ok(())
834 }
835
836 #[sqlx_macros::test]
837 async fn it_can_handle_parameter_status_message_issue_484() -> anyhow::Result<()> {
838 new::<Postgres>().await?.execute("SET NAMES 'UTF8'").await?;
839 Ok(())
840 }
841
842 #[sqlx_macros::test]
843 async fn it_can_prepare_then_execute() -> anyhow::Result<()> {
844 let mut conn = new::<Postgres>().await?;
845 let mut tx = conn.begin().await?;
846
847 let tweet_id: i64 =
848 sqlx::query_scalar("INSERT INTO tweet ( text ) VALUES ( 'Hello, World' ) RETURNING id")
849 .fetch_one(&mut *tx)
850 .await?;
851
852 let statement = tx.prepare("SELECT * FROM tweet WHERE id = $1").await?;
853
854 assert_eq!(statement.column(0).name(), "id");
855 assert_eq!(statement.column(1).name(), "created_at");
856 assert_eq!(statement.column(2).name(), "text");
857 assert_eq!(statement.column(3).name(), "owner_id");
858
859 assert_eq!(statement.column(0).type_info().name(), "INT8");
860 assert_eq!(statement.column(1).type_info().name(), "TIMESTAMPTZ");
861 assert_eq!(statement.column(2).type_info().name(), "TEXT");
862 assert_eq!(statement.column(3).type_info().name(), "INT8");
863
864 let row = statement.query().bind(tweet_id).fetch_one(&mut *tx).await?;
865 let tweet_text: &str = row.try_get("text")?;
866
867 assert_eq!(tweet_text, "Hello, World");
868
869 Ok(())
870 }
871
872 // repro is more reliable with the basic scheduler used by `#[tokio::test]`
873 #[cfg(feature = "_rt-tokio")]
874 #[tokio::test]
875 async fn test_issue_622() -> anyhow::Result<()> {
876 use std::time::Instant;
877
878 setup_if_needed();
879
880 let pool = PgPoolOptions::new()
881 .max_connections(1) // also fails with higher counts, e.g. 5
882 .connect(&std::env::var("DATABASE_URL").unwrap())
883 .await?;
884
885 println!("pool state: {pool:?}");
886
887 let mut handles = vec![];
888
889 // given repro spawned 100 tasks but I found it reliably reproduced with 3
890 for i in 0..3 {
891 let pool = pool.clone();
892
893 handles.push(sqlx_core::rt::spawn(async move {
894 {
895 let mut conn = pool.acquire().await.unwrap();
896
897 let _ = sqlx::query("SELECT 1").fetch_one(&mut *conn).await.unwrap();
898
899 // conn gets dropped here and should be returned to the pool
900 }
901
902 // (do some other work here without holding on to a connection)
903 // this actually fixes the issue, depending on the timeout used
904 // sqlx_core::rt::sleep(Duration::from_millis(500)).await;
905
906 {
907 let start = Instant::now();
908 match pool.acquire().await {
909 Ok(conn) => {
910 println!("{} acquire took {:?}", i, start.elapsed());
911 drop(conn);
912 }
913 Err(e) => panic!("{i} acquire returned error: {e} pool state: {pool:?}"),
914 }
915 }
916
917 Result::<(), anyhow::Error>::Ok(())
918 }));
919 }
920
921 futures::future::try_join_all(handles).await?;
922
923 Ok(())
924 }
925
926 #[sqlx_macros::test]
927 async fn test_describe_outer_join_nullable() -> anyhow::Result<()> {
928 let mut conn = new::<Postgres>().await?;
929
930 // test nullability inference for various joins
931
932 // inner join, nullability should not be overridden
933 // language=PostgreSQL
934 let describe = conn
935 .describe(
936 "select tweet.id
937 from tweet
938 inner join products on products.name = tweet.text",
939 )
940 .await?;
941
942 assert_eq!(describe.nullable(0), Some(false));
943
944 // language=PostgreSQL
945 let describe = conn
946 .describe(
947 "select tweet.id
948 from (values (null)) vals(val)
949 left join tweet on false",
950 )
951 .await?;
952
953 // tweet.id is marked NOT NULL but it's brought in from a left-join here
954 // which should make it nullable
955 assert_eq!(describe.nullable(0), Some(true));
956
957 // make sure we don't mis-infer for the outer half of the join
958 // language=PostgreSQL
959 let describe = conn
960 .describe(
961 "select tweet1.id, tweet2.id
962 from tweet tweet1
963 left join tweet tweet2 on false",
964 )
965 .await?;
966
967 assert_eq!(describe.nullable(0), Some(false));
968 assert_eq!(describe.nullable(1), Some(true));
969
970 // right join, nullability should be inverted
971 // language=PostgreSQL
972 let describe = conn
973 .describe(
974 "select tweet1.id, tweet2.id
975 from tweet tweet1
976 right join tweet tweet2 on false",
977 )
978 .await?;
979
980 assert_eq!(describe.nullable(0), Some(true));
981 assert_eq!(describe.nullable(1), Some(false));
982
983 // full outer join, both tables are nullable
984 // language=PostgreSQL
985 let describe = conn
986 .describe(
987 "select tweet1.id, tweet2.id
988 from tweet tweet1
989 full join tweet tweet2 on false",
990 )
991 .await?;
992
993 assert_eq!(describe.nullable(0), Some(true));
994 assert_eq!(describe.nullable(1), Some(true));
995
996 Ok(())
997 }
998
999 #[sqlx_macros::test]
1000 async fn test_listener_cleanup() -> anyhow::Result<()> {
1001 use sqlx_core::rt::timeout;
1002
1003 use sqlx::pool::PoolOptions;
1004 use sqlx::postgres::PgListener;
1005
1006 // Create a connection on which to send notifications
1007 let mut notify_conn = new::<Postgres>().await?;
1008
1009 // Create a pool with exactly one connection so we can
1010 // deterministically test the cleanup.
1011 let pool = PoolOptions::<Postgres>::new()
1012 .min_connections(1)
1013 .max_connections(1)
1014 .test_before_acquire(true)
1015 .connect(&env::var("DATABASE_URL")?)
1016 .await?;
1017
1018 let mut listener = PgListener::connect_with(&pool).await?;
1019 listener.listen("test_channel").await?;
1020
1021 // Checks for a notification on the test channel
1022 async fn try_recv(listener: &mut PgListener) -> anyhow::Result<bool> {
1023 match timeout(Duration::from_millis(100), listener.recv()).await {
1024 Ok(res) => {
1025 res?;
1026 Ok(true)
1027 }
1028 Err(_) => Ok(false),
1029 }
1030 }
1031
1032 // Check no notification is received before one is sent
1033 assert!(!try_recv(&mut listener).await?, "Notification not sent");
1034
1035 // Check notification is sent and received
1036 notify_conn.execute("NOTIFY test_channel").await?;
1037 assert!(
1038 try_recv(&mut listener).await?,
1039 "Notification sent and received"
1040 );
1041 assert!(
1042 !try_recv(&mut listener).await?,
1043 "Notification is not duplicated"
1044 );
1045
1046 // Test that cleanup stops listening on the channel
1047 drop(listener);
1048 let mut listener = PgListener::connect_with(&pool).await?;
1049
1050 // Check notification is sent but not received
1051 notify_conn.execute("NOTIFY test_channel").await?;
1052 assert!(
1053 !try_recv(&mut listener).await?,
1054 "Notification is not received on fresh listener"
1055 );
1056
1057 Ok(())
1058 }
1059
1060 #[sqlx_macros::test]
1061 async fn test_listener_try_recv_buffered() -> anyhow::Result<()> {
1062 use sqlx_core::rt::timeout;
1063
1064 use sqlx::pool::PoolOptions;
1065 use sqlx::postgres::PgListener;
1066
1067 // Create a connection on which to send notifications
1068 let mut notify_conn = new::<Postgres>().await?;
1069
1070 let pool = PoolOptions::<Postgres>::new()
1071 .min_connections(1)
1072 .max_connections(1)
1073 .test_before_acquire(true)
1074 .connect(&env::var("DATABASE_URL")?)
1075 .await?;
1076
1077 let mut listener = PgListener::connect_with(&pool).await?;
1078 listener.listen("test_channel2").await?;
1079
1080 // Checks for a notification on the test channel
1081 async fn try_recv(listener: &mut PgListener) -> anyhow::Result<bool> {
1082 match timeout(Duration::from_millis(100), listener.recv()).await {
1083 Ok(res) => {
1084 res?;
1085 Ok(true)
1086 }
1087 Err(_) => Ok(false),
1088 }
1089 }
1090
1091 // Check no notification is buffered, since we haven't sent one.
1092 assert!(listener.next_buffered().is_none());
1093
1094 // Send five notifications transactionally, so they all arrive at once.
1095 {
1096 let mut txn = notify_conn.begin().await?;
1097 for i in 0..5 {
1098 txn.execute(format!("NOTIFY test_channel2, 'payload {i}'").as_str())
1099 .await?;
1100 }
1101 txn.commit().await?;
1102 }
1103
1104 // Still no notifications buffered, since we haven't awaited the listener yet.
1105 assert!(listener.next_buffered().is_none());
1106
1107 // Activate connection.
1108 sqlx::query!("SELECT 1 AS one")
1109 .fetch_all(&mut listener)
1110 .await?;
1111
1112 // The next five notifications should now be buffered.
1113 for i in 0..5 {
1114 assert!(
1115 listener.next_buffered().is_some(),
1116 "Notification {i} was not buffered"
1117 );
1118 }
1119
1120 // Should be no more.
1121 assert!(listener.next_buffered().is_none());
1122
1123 // Even if we wait.
1124 assert!(!try_recv(&mut listener).await?, "Notification received");
1125
1126 Ok(())
1127 }
1128
1129 #[sqlx_macros::test]
1130 async fn test_pg_listener_allows_pool_to_close() -> anyhow::Result<()> {
1131 let pool = pool::<Postgres>().await?;
1132
1133 // acquires and holds a connection which would normally prevent the pool from closing
1134 let mut listener = PgListener::connect_with(&pool).await?;
1135
1136 sqlx_core::rt::spawn(async move {
1137 listener.recv().await.unwrap();
1138 });
1139
1140 // would previously hang forever since `PgListener` had no way to know the pool wanted to close
1141 pool.close().await;
1142
1143 Ok(())
1144 }
1145
1146 #[sqlx_macros::test]
1147 async fn test_pg_listener_implements_acquire() -> anyhow::Result<()> {
1148 use sqlx::Acquire;
1149
1150 let pool = pool::<Postgres>().await?;
1151
1152 let mut listener = PgListener::connect_with(&pool).await?;
1153 listener
1154 .listen("test_pg_listener_implements_acquire")
1155 .await?;
1156
1157 // Start a transaction on the underlying connection
1158 let mut txn = listener.begin().await?;
1159
1160 // This will reuse the same connection, so this connection should be listening to the channel
1161 let channels: Vec<String> = sqlx::query_scalar("SELECT pg_listening_channels()")
1162 .fetch_all(&mut *txn)
1163 .await?;
1164
1165 assert_eq!(channels, vec!["test_pg_listener_implements_acquire"]);
1166
1167 // Send a notification
1168 sqlx::query("NOTIFY test_pg_listener_implements_acquire, 'hello'")
1169 .execute(&mut *txn)
1170 .await?;
1171
1172 txn.commit().await?;
1173
1174 // And now we can receive the notification we sent in the transaction
1175 let notification = listener.recv().await?;
1176 assert_eq!(
1177 notification.channel(),
1178 "test_pg_listener_implements_acquire"
1179 );
1180 assert_eq!(notification.payload(), "hello");
1181
1182 Ok(())
1183 }
1184
1185 #[sqlx_macros::test]
1186 async fn it_supports_domain_types_in_composite_domain_types() -> anyhow::Result<()> {
1187 // Only supported in Postgres 11+
1188 let mut conn = new::<Postgres>().await?;
1189 if matches!(conn.server_version_num(), Some(version) if version < 110000) {
1190 return Ok(());
1191 }
1192
1193 conn.execute(
1194 r#"
1195 DROP TABLE IF EXISTS heating_bills;
1196 DROP DOMAIN IF EXISTS winter_year_month;
1197 DROP TYPE IF EXISTS year_month;
1198 DROP DOMAIN IF EXISTS month_id;
1199
1200 CREATE DOMAIN month_id AS INT2 CHECK (1 <= value AND value <= 12);
1201 CREATE TYPE year_month AS (year INT4, month month_id);
1202 CREATE DOMAIN winter_year_month AS year_month CHECK ((value).month <= 3);
1203 CREATE TABLE heating_bills (
1204 month winter_year_month NOT NULL PRIMARY KEY,
1205 cost INT4 NOT NULL
1206 );
1207 "#,
1208 )
1209 .await?;
1210
1211 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1212 struct MonthId(i16);
1213
1214 impl sqlx::Type<Postgres> for MonthId {
1215 fn type_info() -> sqlx::postgres::PgTypeInfo {
1216 sqlx::postgres::PgTypeInfo::with_name("month_id")
1217 }
1218
1219 fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
1220 *ty == Self::type_info()
1221 }
1222 }
1223
1224 impl<'r> sqlx::Decode<'r, Postgres> for MonthId {
1225 fn decode(
1226 value: sqlx::postgres::PgValueRef<'r>,
1227 ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
1228 Ok(Self(<i16 as sqlx::Decode<Postgres>>::decode(value)?))
1229 }
1230 }
1231
1232 impl<'q> sqlx::Encode<'q, Postgres> for MonthId {
1233 fn encode_by_ref(
1234 &self,
1235 buf: &mut sqlx::postgres::PgArgumentBuffer,
1236 ) -> Result<sqlx::encode::IsNull, BoxDynError> {
1237 <i16 as sqlx::Encode<Postgres>>::encode(self.0, buf)
1238 }
1239 }
1240
1241 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1242 struct WinterYearMonth {
1243 year: i32,
1244 month: MonthId,
1245 }
1246
1247 impl sqlx::Type<Postgres> for WinterYearMonth {
1248 fn type_info() -> sqlx::postgres::PgTypeInfo {
1249 sqlx::postgres::PgTypeInfo::with_name("winter_year_month")
1250 }
1251
1252 fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
1253 *ty == Self::type_info()
1254 }
1255 }
1256
1257 impl<'r> sqlx::Decode<'r, Postgres> for WinterYearMonth {
1258 fn decode(
1259 value: sqlx::postgres::PgValueRef<'r>,
1260 ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
1261 let mut decoder = sqlx::postgres::types::PgRecordDecoder::new(value)?;
1262
1263 let year = decoder.try_decode::<i32>()?;
1264 let month = decoder.try_decode::<MonthId>()?;
1265
1266 Ok(Self { year, month })
1267 }
1268 }
1269
1270 impl<'q> sqlx::Encode<'q, Postgres> for WinterYearMonth {
1271 fn encode_by_ref(
1272 &self,
1273 buf: &mut sqlx::postgres::PgArgumentBuffer,
1274 ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
1275 let mut encoder = sqlx::postgres::types::PgRecordEncoder::new(buf);
1276 encoder.encode(self.year)?;
1277 encoder.encode(self.month)?;
1278 encoder.finish();
1279 Ok(sqlx::encode::IsNull::No)
1280 }
1281 }
1282 let mut conn = new::<Postgres>().await?;
1283
1284 let result = sqlx::query("DELETE FROM heating_bills;")
1285 .execute(&mut conn)
1286 .await;
1287
1288 let result = result.unwrap();
1289 assert_eq!(result.rows_affected(), 0);
1290
1291 let result =
1292 sqlx::query("INSERT INTO heating_bills(month, cost) VALUES($1::winter_year_month, 100);")
1293 .bind(WinterYearMonth {
1294 year: 2021,
1295 month: MonthId(1),
1296 })
1297 .execute(&mut conn)
1298 .await;
1299
1300 let result = result.unwrap();
1301 assert_eq!(result.rows_affected(), 1);
1302
1303 let result = sqlx::query("DELETE FROM heating_bills;")
1304 .execute(&mut conn)
1305 .await;
1306
1307 let result = result.unwrap();
1308 assert_eq!(result.rows_affected(), 1);
1309
1310 Ok(())
1311 }
1312
1313 #[sqlx_macros::test]
1314 async fn it_resolves_custom_type_in_array() -> anyhow::Result<()> {
1315 // Only supported in Postgres 11+
1316 let mut conn = new::<Postgres>().await?;
1317 if matches!(conn.server_version_num(), Some(version) if version < 110000) {
1318 return Ok(());
1319 }
1320
1321 // language=PostgreSQL
1322 conn.execute(
1323 r#"
1324 DROP TABLE IF EXISTS pets;
1325 DROP TYPE IF EXISTS pet_name_and_race;
1326
1327 CREATE TYPE pet_name_and_race AS (
1328 name TEXT,
1329 race TEXT
1330 );
1331 CREATE TABLE pets (
1332 owner TEXT NOT NULL,
1333 name TEXT NOT NULL,
1334 race TEXT NOT NULL,
1335 PRIMARY KEY (owner, name)
1336 );
1337 INSERT INTO pets(owner, name, race)
1338 VALUES
1339 ('Alice', 'Foo', 'cat');
1340 INSERT INTO pets(owner, name, race)
1341 VALUES
1342 ('Alice', 'Bar', 'dog');
1343 "#,
1344 )
1345 .await?;
1346
1347 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1348 struct PetNameAndRace {
1349 name: String,
1350 race: String,
1351 }
1352
1353 impl sqlx::Type<Postgres> for PetNameAndRace {
1354 fn type_info() -> sqlx::postgres::PgTypeInfo {
1355 sqlx::postgres::PgTypeInfo::with_name("pet_name_and_race")
1356 }
1357 }
1358
1359 impl<'r> sqlx::Decode<'r, Postgres> for PetNameAndRace {
1360 fn decode(
1361 value: sqlx::postgres::PgValueRef<'r>,
1362 ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
1363 let mut decoder = sqlx::postgres::types::PgRecordDecoder::new(value)?;
1364 let name = decoder.try_decode::<String>()?;
1365 let race = decoder.try_decode::<String>()?;
1366 Ok(Self { name, race })
1367 }
1368 }
1369
1370 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1371 struct PetNameAndRaceArray(Vec<PetNameAndRace>);
1372
1373 impl sqlx::Type<Postgres> for PetNameAndRaceArray {
1374 fn type_info() -> sqlx::postgres::PgTypeInfo {
1375 // Array type name is the name of the element type prefixed with `_`
1376 sqlx::postgres::PgTypeInfo::with_name("_pet_name_and_race")
1377 }
1378 }
1379
1380 impl<'r> sqlx::Decode<'r, Postgres> for PetNameAndRaceArray {
1381 fn decode(
1382 value: sqlx::postgres::PgValueRef<'r>,
1383 ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
1384 Ok(Self(Vec::<PetNameAndRace>::decode(value)?))
1385 }
1386 }
1387
1388 let mut conn = new::<Postgres>().await?;
1389
1390 let row = sqlx::query("select owner, array_agg(row(name, race)::pet_name_and_race) as pets from pets group by owner")
1391 .fetch_one(&mut conn)
1392 .await?;
1393
1394 let pets: PetNameAndRaceArray = row.get("pets");
1395
1396 assert_eq!(pets.0.len(), 2);
1397 Ok(())
1398 }
1399
1400 #[sqlx_macros::test]
1401 async fn it_resolves_custom_types_in_anonymous_records() -> anyhow::Result<()> {
1402 use sqlx_core::error::Error;
1403 // This request involves nested records and array types.
1404
1405 // Only supported in Postgres 11+
1406 let mut conn = new::<Postgres>().await?;
1407 if matches!(conn.server_version_num(), Some(version) if version < 110000) {
1408 return Ok(());
1409 }
1410
1411 // language=PostgreSQL
1412 conn.execute(
1413 r#"
1414 DROP TABLE IF EXISTS repo_users;
1415 DROP TABLE IF EXISTS repositories;
1416 DROP TABLE IF EXISTS repo_memberships;
1417 DROP TYPE IF EXISTS repo_member;
1418
1419 CREATE TABLE repo_users (
1420 user_id INT4 NOT NULL,
1421 username TEXT NOT NULL,
1422 PRIMARY KEY (user_id)
1423 );
1424 CREATE TABLE repositories (
1425 repo_id INT4 NOT NULL,
1426 repo_name TEXT NOT NULL,
1427 PRIMARY KEY (repo_id)
1428 );
1429 CREATE TABLE repo_memberships (
1430 repo_id INT4 NOT NULL,
1431 user_id INT4 NOT NULL,
1432 permission TEXT NOT NULL,
1433 PRIMARY KEY (repo_id, user_id)
1434 );
1435 CREATE TYPE repo_member AS (
1436 user_id INT4,
1437 permission TEXT
1438 );
1439 INSERT INTO repo_users(user_id, username)
1440 VALUES
1441 (101, 'alice'),
1442 (102, 'bob'),
1443 (103, 'charlie');
1444 INSERT INTO repositories(repo_id, repo_name)
1445 VALUES
1446 (201, 'rust'),
1447 (202, 'sqlx'),
1448 (203, 'hello-world');
1449 INSERT INTO repo_memberships(repo_id, user_id, permission)
1450 VALUES
1451 (201, 101, 'admin'),
1452 (201, 102, 'write'),
1453 (201, 103, 'read'),
1454 (202, 102, 'admin');
1455 "#,
1456 )
1457 .await?;
1458
1459 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1460 struct RepoMember {
1461 user_id: i32,
1462 permission: String,
1463 }
1464
1465 impl sqlx::Type<Postgres> for RepoMember {
1466 fn type_info() -> sqlx::postgres::PgTypeInfo {
1467 sqlx::postgres::PgTypeInfo::with_name("repo_member")
1468 }
1469 }
1470
1471 impl<'r> sqlx::Decode<'r, Postgres> for RepoMember {
1472 fn decode(
1473 value: sqlx::postgres::PgValueRef<'r>,
1474 ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
1475 let mut decoder = sqlx::postgres::types::PgRecordDecoder::new(value)?;
1476 let user_id = decoder.try_decode::<i32>()?;
1477 let permission = decoder.try_decode::<String>()?;
1478 Ok(Self {
1479 user_id,
1480 permission,
1481 })
1482 }
1483 }
1484
1485 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1486 struct RepoMemberArray(Vec<RepoMember>);
1487
1488 impl sqlx::Type<Postgres> for RepoMemberArray {
1489 fn type_info() -> sqlx::postgres::PgTypeInfo {
1490 // Array type name is the name of the element type prefixed with `_`
1491 sqlx::postgres::PgTypeInfo::with_name("_repo_member")
1492 }
1493 }
1494
1495 impl<'r> sqlx::Decode<'r, Postgres> for RepoMemberArray {
1496 fn decode(
1497 value: sqlx::postgres::PgValueRef<'r>,
1498 ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
1499 Ok(Self(Vec::<RepoMember>::decode(value)?))
1500 }
1501 }
1502
1503 let mut conn = new::<Postgres>().await?;
1504
1505 #[derive(Debug, sqlx::FromRow)]
1506 #[allow(dead_code)] // We don't actually read these fields.
1507 struct Row {
1508 count: i64,
1509 items: Vec<(i32, String, RepoMemberArray)>,
1510 }
1511 // language=PostgreSQL
1512 let row: Result<Row, Error> = sqlx::query_as::<_, Row>(
1513 r"
1514 WITH
1515 members_by_repo AS (
1516 SELECT repo_id,
1517 ARRAY_AGG(ROW (user_id, permission)::repo_member) AS members
1518 FROM repo_memberships
1519 GROUP BY repo_id
1520 ),
1521 repos AS (
1522 SELECT repo_id, repo_name, COALESCE(members, '{}') AS members
1523 FROM repositories
1524 LEFT OUTER JOIN members_by_repo USING (repo_id)
1525 ORDER BY repo_id
1526 ),
1527 repo_array AS (
1528 SELECT COALESCE(ARRAY_AGG(repos.*), '{}') AS items
1529 FROM repos
1530 ),
1531 repo_count AS (
1532 SELECT COUNT(*) AS count
1533 FROM repos
1534 )
1535 SELECT count, items
1536 FROM repo_count, repo_array
1537 ;
1538 ",
1539 )
1540 .fetch_one(&mut conn)
1541 .await;
1542
1543 // This test currently tests mitigations for `#1672` (use regular errors
1544 // instead of panics). Once we fully support custom types, it should be
1545 // updated accordingly.
1546 match row {
1547 Ok(_) => panic!("full support for custom types is not implemented yet"),
1548 Err(e) => assert!(e
1549 .to_string()
1550 .contains("custom types in records are not fully supported yet")),
1551 }
1552 Ok(())
1553 }
1554
1555 #[sqlx_macros::test]
1556 async fn custom_type_resolution_respects_search_path() -> anyhow::Result<()> {
1557 let mut conn = new::<Postgres>().await?;
1558
1559 conn.execute(
1560 r#"
1561 DROP TYPE IF EXISTS some_enum_type;
1562 DROP SCHEMA IF EXISTS another CASCADE;
1563
1564 CREATE SCHEMA another;
1565 CREATE TYPE some_enum_type AS ENUM ('a', 'b', 'c');
1566 CREATE TYPE another.some_enum_type AS ENUM ('d', 'e', 'f');
1567 "#,
1568 )
1569 .await?;
1570
1571 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1572 struct SomeEnumType(String);
1573
1574 impl sqlx::Type<Postgres> for SomeEnumType {
1575 fn type_info() -> sqlx::postgres::PgTypeInfo {
1576 sqlx::postgres::PgTypeInfo::with_name("some_enum_type")
1577 }
1578
1579 fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
1580 *ty == Self::type_info()
1581 }
1582 }
1583
1584 impl<'r> sqlx::Decode<'r, Postgres> for SomeEnumType {
1585 fn decode(
1586 value: sqlx::postgres::PgValueRef<'r>,
1587 ) -> Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
1588 Ok(Self(<String as sqlx::Decode<Postgres>>::decode(value)?))
1589 }
1590 }
1591
1592 impl<'q> sqlx::Encode<'q, Postgres> for SomeEnumType {
1593 fn encode_by_ref(
1594 &self,
1595 buf: &mut sqlx::postgres::PgArgumentBuffer,
1596 ) -> Result<sqlx::encode::IsNull, BoxDynError> {
1597 <String as sqlx::Encode<Postgres>>::encode_by_ref(&self.0, buf)
1598 }
1599 }
1600
1601 let mut conn = new::<Postgres>().await?;
1602
1603 sqlx::query("set search_path = 'another'")
1604 .execute(&mut conn)
1605 .await?;
1606
1607 let result = sqlx::query("SELECT 1 WHERE $1::some_enum_type = 'd'::some_enum_type;")
1608 .bind(SomeEnumType("d".into()))
1609 .fetch_all(&mut conn)
1610 .await;
1611
1612 let result = result.unwrap();
1613 assert_eq!(result.len(), 1);
1614
1615 Ok(())
1616 }
1617
1618 #[sqlx_macros::test]
1619 async fn test_pg_server_num() -> anyhow::Result<()> {
1620 let conn = new::<Postgres>().await?;
1621
1622 assert!(conn.server_version_num().is_some());
1623
1624 Ok(())
1625 }
1626
1627 #[sqlx_macros::test]
1628 async fn it_can_copy_in() -> anyhow::Result<()> {
1629 let mut conn = new::<Postgres>().await?;
1630 conn.execute(
1631 r#"
1632 CREATE TEMPORARY TABLE users (id INTEGER NOT NULL);
1633 "#,
1634 )
1635 .await?;
1636
1637 let mut copy = conn
1638 .copy_in_raw(
1639 r#"
1640 COPY users (id) FROM STDIN WITH (FORMAT CSV, HEADER);
1641 "#,
1642 )
1643 .await?;
1644
1645 copy.send("id\n1\n2\n".as_bytes()).await?;
1646 let rows = copy.finish().await?;
1647 assert_eq!(rows, 2);
1648
1649 // conn is safe for reuse
1650 let value = sqlx::query("select 1 + 1")
1651 .try_map(|row: PgRow| row.try_get::<i32, _>(0))
1652 .fetch_one(&mut conn)
1653 .await?;
1654
1655 assert_eq!(2i32, value);
1656
1657 Ok(())
1658 }
1659
1660 #[sqlx_macros::test]
1661 async fn it_can_abort_copy_in() -> anyhow::Result<()> {
1662 let mut conn = new::<Postgres>().await?;
1663 conn.execute(
1664 r#"
1665 CREATE TEMPORARY TABLE users (id INTEGER NOT NULL);
1666 "#,
1667 )
1668 .await?;
1669
1670 let copy = conn
1671 .copy_in_raw(
1672 r#"
1673 COPY users (id) FROM STDIN WITH (FORMAT CSV, HEADER);
1674 "#,
1675 )
1676 .await?;
1677
1678 copy.abort("this is only a test").await?;
1679
1680 // conn is safe for reuse
1681 let value = sqlx::query("select 1 + 1")
1682 .try_map(|row: PgRow| row.try_get::<i32, _>(0))
1683 .fetch_one(&mut conn)
1684 .await?;
1685
1686 assert_eq!(2i32, value);
1687
1688 Ok(())
1689 }
1690
1691 #[sqlx_macros::test]
1692 async fn it_can_copy_out() -> anyhow::Result<()> {
1693 let mut conn = new::<Postgres>().await?;
1694
1695 {
1696 let mut copy = conn
1697 .copy_out_raw(
1698 "
1699 COPY (SELECT generate_series(1, 2) AS id) TO STDOUT WITH (FORMAT CSV, HEADER);
1700 ",
1701 )
1702 .await?;
1703
1704 assert_eq!(copy.next().await.unwrap().unwrap(), "id\n");
1705 assert_eq!(copy.next().await.unwrap().unwrap(), "1\n");
1706 assert_eq!(copy.next().await.unwrap().unwrap(), "2\n");
1707 if copy.next().await.is_some() {
1708 anyhow::bail!("Unexpected data from COPY");
1709 }
1710 }
1711
1712 // conn is safe for reuse
1713 let value = sqlx::query("select 1 + 1")
1714 .try_map(|row: PgRow| row.try_get::<i32, _>(0))
1715 .fetch_one(&mut conn)
1716 .await?;
1717
1718 assert_eq!(2i32, value);
1719
1720 Ok(())
1721 }
1722
1723 #[sqlx_macros::test]
1724 async fn it_encodes_custom_array_issue_1504() -> anyhow::Result<()> {
1725 use sqlx::encode::IsNull;
1726 use sqlx::postgres::{PgArgumentBuffer, PgTypeInfo};
1727 use sqlx::{Decode, Encode, Type, ValueRef};
1728
1729 #[derive(Debug, PartialEq)]
1730 enum Value {
1731 String(String),
1732 Number(i32),
1733 Array(Vec<Value>),
1734 }
1735
1736 impl<'r> Decode<'r, Postgres> for Value {
1737 fn decode(
1738 value: sqlx::postgres::PgValueRef<'r>,
1739 ) -> std::result::Result<Self, Box<dyn std::error::Error + 'static + Send + Sync>> {
1740 let typ = value.type_info().into_owned();
1741
1742 if typ == PgTypeInfo::with_name("text") {
1743 let s = <String as Decode<'_, Postgres>>::decode(value)?;
1744
1745 Ok(Self::String(s))
1746 } else if typ == PgTypeInfo::with_name("int4") {
1747 let n = <i32 as Decode<'_, Postgres>>::decode(value)?;
1748
1749 Ok(Self::Number(n))
1750 } else if typ == PgTypeInfo::with_name("_text") {
1751 let arr = Vec::<String>::decode(value)?;
1752 let v = arr.into_iter().map(|s| Value::String(s)).collect();
1753
1754 Ok(Self::Array(v))
1755 } else if typ == PgTypeInfo::with_name("_int4") {
1756 let arr = Vec::<i32>::decode(value)?;
1757 let v = arr.into_iter().map(|n| Value::Number(n)).collect();
1758
1759 Ok(Self::Array(v))
1760 } else {
1761 Err("unknown type".into())
1762 }
1763 }
1764 }
1765
1766 impl Encode<'_, Postgres> for Value {
1767 fn produces(&self) -> Option<PgTypeInfo> {
1768 match self {
1769 Self::Array(a) => {
1770 if a.len() < 1 {
1771 return Some(PgTypeInfo::with_name("_text"));
1772 }
1773
1774 match a[0] {
1775 Self::String(_) => Some(PgTypeInfo::with_name("_text")),
1776 Self::Number(_) => Some(PgTypeInfo::with_name("_int4")),
1777 Self::Array(_) => None,
1778 }
1779 }
1780 Self::String(_) => Some(PgTypeInfo::with_name("text")),
1781 Self::Number(_) => Some(PgTypeInfo::with_name("int4")),
1782 }
1783 }
1784
1785 fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
1786 match self {
1787 Value::String(s) => <String as Encode<'_, Postgres>>::encode_by_ref(s, buf),
1788 Value::Number(n) => <i32 as Encode<'_, Postgres>>::encode_by_ref(n, buf),
1789 Value::Array(arr) => arr.encode(buf),
1790 }
1791 }
1792 }
1793
1794 impl Type<Postgres> for Value {
1795 fn type_info() -> PgTypeInfo {
1796 PgTypeInfo::with_name("unknown")
1797 }
1798
1799 fn compatible(ty: &PgTypeInfo) -> bool {
1800 [
1801 PgTypeInfo::with_name("text"),
1802 PgTypeInfo::with_name("_text"),
1803 PgTypeInfo::with_name("int4"),
1804 PgTypeInfo::with_name("_int4"),
1805 ]
1806 .contains(ty)
1807 }
1808 }
1809
1810 let mut conn = new::<Postgres>().await?;
1811
1812 let (row,): (Value,) = sqlx::query_as("SELECT $1::text[] as Dummy")
1813 .bind(Value::Array(vec![
1814 Value::String("Test 0".to_string()),
1815 Value::String("Test 1".to_string()),
1816 ]))
1817 .fetch_one(&mut conn)
1818 .await?;
1819
1820 assert_eq!(
1821 row,
1822 Value::Array(vec![
1823 Value::String("Test 0".to_string()),
1824 Value::String("Test 1".to_string()),
1825 ])
1826 );
1827
1828 let (row,): (Value,) = sqlx::query_as("SELECT $1::int4[] as Dummy")
1829 .bind(Value::Array(vec![
1830 Value::Number(3),
1831 Value::Number(2),
1832 Value::Number(1),
1833 ]))
1834 .fetch_one(&mut conn)
1835 .await?;
1836
1837 assert_eq!(
1838 row,
1839 Value::Array(vec![Value::Number(3), Value::Number(2), Value::Number(1)])
1840 );
1841
1842 Ok(())
1843 }
1844
1845 #[sqlx_macros::test]
1846 async fn test_issue_1254() -> anyhow::Result<()> {
1847 #[derive(sqlx::Type)]
1848 #[sqlx(type_name = "pair")]
1849 struct Pair {
1850 one: i32,
1851 two: i32,
1852 }
1853
1854 // array for custom type is not supported, use wrapper
1855 #[derive(sqlx::Type)]
1856 #[sqlx(type_name = "_pair")]
1857 struct Pairs(Vec<Pair>);
1858
1859 let mut conn = new::<Postgres>().await?;
1860 conn.execute(
1861 "
1862 DROP TABLE IF EXISTS issue_1254;
1863 DROP TYPE IF EXISTS pair;
1864
1865 CREATE TYPE pair AS (one INT4, two INT4);
1866 CREATE TABLE issue_1254 (id INT4 PRIMARY KEY, pairs PAIR[]);
1867 ",
1868 )
1869 .await?;
1870
1871 let result = sqlx::query("INSERT INTO issue_1254 VALUES($1, $2)")
1872 .bind(0)
1873 .bind(Pairs(vec![Pair { one: 94, two: 87 }]))
1874 .execute(&mut conn)
1875 .await?;
1876 assert_eq!(result.rows_affected(), 1);
1877
1878 Ok(())
1879 }
1880
1881 #[sqlx_macros::test]
1882 async fn test_advisory_locks() -> anyhow::Result<()> {
1883 let pool = PgPoolOptions::new()
1884 .max_connections(2)
1885 .connect(&dotenvy::var("DATABASE_URL")?)
1886 .await?;
1887
1888 let lock1 = Arc::new(PgAdvisoryLock::new("sqlx-postgres-tests-1"));
1889 let lock2 = Arc::new(PgAdvisoryLock::new("sqlx-postgres-tests-2"));
1890
1891 let conn1 = pool.acquire().await?;
1892 let mut conn1_lock1 = lock1.acquire(conn1).await?;
1893
1894 // try acquiring a recursive lock through a mutable reference then dropping
1895 drop(lock1.acquire(&mut conn1_lock1).await?);
1896
1897 let conn2 = pool.acquire().await?;
1898 // leak so we can take it across the task boundary
1899 let conn2_lock2 = lock2.acquire(conn2).await?.leak();
1900
1901 sqlx_core::rt::spawn({
1902 let lock1 = lock1.clone();
1903 let lock2 = lock2.clone();
1904
1905 async move {
1906 let conn2_lock2 = lock1.try_acquire(conn2_lock2).await?.right_or_else(|_| {
1907 panic!(
1908 "acquired lock but wasn't supposed to! Key: {:?}",
1909 lock1.key()
1910 )
1911 });
1912
1913 let (conn2, released) = lock2.force_release(conn2_lock2).await?;
1914 assert!(released);
1915
1916 // acquire both locks but let the pool release them
1917 let conn2_lock1 = lock1.acquire(conn2).await?;
1918 let _conn2_lock1and2 = lock2.acquire(conn2_lock1).await?;
1919
1920 anyhow::Ok(())
1921 }
1922 });
1923
1924 // acquire lock2 on conn1, we leak the lock1 guard so we can manually release it before lock2
1925 let conn1_lock1and2 = lock2.acquire(conn1_lock1.leak()).await?;
1926
1927 // release lock1 while holding lock2
1928 let (conn1_lock2, released) = lock1.force_release(conn1_lock1and2).await?;
1929 assert!(released);
1930
1931 let conn1 = conn1_lock2.release_now().await?;
1932
1933 // acquire both locks to be sure they were released
1934 {
1935 let conn1_lock1 = lock1.acquire(conn1).await?;
1936 let _conn1_lock1and2 = lock2.acquire(conn1_lock1).await?;
1937 }
1938
1939 pool.close().await;
1940
1941 Ok(())
1942 }
1943
1944 #[sqlx_macros::test]
1945 async fn test_postgres_bytea_hex_deserialization_errors() -> anyhow::Result<()> {
1946 let mut conn = new::<Postgres>().await?;
1947 conn.execute("SET bytea_output = 'escape';").await?;
1948 for value in ["", "DEADBEEF"] {
1949 let query = format!("SELECT '\\x{value}'::bytea");
1950 let res: sqlx::Result<Vec<u8>> = conn.fetch_one(query.as_str()).await?.try_get(0usize);
1951 // Deserialization only supports hex format so this should error and definitely not panic.
1952 res.unwrap_err();
1953 }
1954 Ok(())
1955 }
1956
1957 #[sqlx_macros::test]
1958 async fn test_shrink_buffers() -> anyhow::Result<()> {
1959 // We don't really have a good way to test that `.shrink_buffers()` functions as expected
1960 // without exposing a lot of internals, but we can at least be sure it doesn't
1961 // materially affect the operation of the connection.
1962
1963 let mut conn = new::<Postgres>().await?;
1964
1965 // The connection buffer is only 8 KiB by default so this should definitely force it to grow.
1966 let data = vec![0u8; 32 * 1024];
1967
1968 let ret: Vec<u8> = sqlx::query_scalar("SELECT $1::bytea")
1969 .bind(&data)
1970 .fetch_one(&mut conn)
1971 .await?;
1972
1973 assert_eq!(ret, data);
1974
1975 conn.shrink_buffers();
1976
1977 let ret: i64 = sqlx::query_scalar("SELECT $1::int8")
1978 .bind(&12345678i64)
1979 .fetch_one(&mut conn)
1980 .await?;
1981
1982 assert_eq!(ret, 12345678i64);
1983
1984 Ok(())
1985 }
1986
1987 #[sqlx_macros::test]
1988 async fn test_error_handling_with_deferred_constraints() -> anyhow::Result<()> {
1989 let mut conn = new::<Postgres>().await?;
1990
1991 sqlx::query("CREATE TABLE IF NOT EXISTS deferred_constraint ( id INTEGER PRIMARY KEY )")
1992 .execute(&mut conn)
1993 .await?;
1994
1995 sqlx::query("CREATE TABLE IF NOT EXISTS deferred_constraint_fk ( fk INTEGER CONSTRAINT deferred_fk REFERENCES deferred_constraint(id) DEFERRABLE INITIALLY DEFERRED )")
1996 .execute(&mut conn)
1997 .await?;
1998
1999 let result: sqlx::Result<i32> =
2000 sqlx::query_scalar("INSERT INTO deferred_constraint_fk VALUES (1) RETURNING fk")
2001 .fetch_one(&mut conn)
2002 .await;
2003
2004 let err = result.unwrap_err();
2005 let db_err = err.as_database_error().unwrap();
2006 assert_eq!(db_err.constraint(), Some("deferred_fk"));
2007
2008 Ok(())
2009 }
2010
2011 #[sqlx_macros::test]
2012 #[cfg(feature = "bigdecimal")]
2013 async fn test_issue_3052() {
2014 use sqlx::types::BigDecimal;
2015
2016 // https://github.com/launchbadge/sqlx/issues/3052
2017 // Previously, attempting to bind a `BigDecimal` would panic if the value was out of range.
2018 // Now, we rewrite it to a sentinel value so that Postgres will return a range error.
2019 let too_small: BigDecimal = "1E-65536".parse().unwrap();
2020 let too_large: BigDecimal = "1E262144".parse().unwrap();
2021
2022 let mut conn = new::<Postgres>().await.unwrap();
2023
2024 let too_small_error = sqlx::query_scalar::<_, BigDecimal>("SELECT $1::numeric")
2025 .bind(&too_small)
2026 .fetch_one(&mut conn)
2027 .await
2028 .expect_err("Too small number should have failed");
2029 assert!(
2030 matches!(&too_small_error, sqlx::Error::Encode(_)),
2031 "expected encode error, got {too_small_error:?}"
2032 );
2033
2034 let too_large_error = sqlx::query_scalar::<_, BigDecimal>("SELECT $1::numeric")
2035 .bind(&too_large)
2036 .fetch_one(&mut conn)
2037 .await
2038 .expect_err("Too large number should have failed");
2039
2040 assert!(
2041 matches!(&too_large_error, sqlx::Error::Encode(_)),
2042 "expected encode error, got {too_large_error:?}",
2043 );
2044 }