Debian Codegraph @

tests/postgres/macros.rs

raw symbols SCIP
1 use sqlx::{Connection, PgConnection, Postgres, Transaction};
2 use sqlx_postgres::types::PgHstore;
3 use sqlx_test::new;
4
5 use futures::TryStreamExt;
6
7 #[sqlx_macros::test]
8 async fn test_query() -> anyhow::Result<()> {
9 let mut conn = new::<Postgres>().await?;
10
11 let account = sqlx::query!(
12 "SELECT * from (VALUES (1, 'Herp Derpinson')) accounts(id, name) where id = $1",
13 1i32
14 )
15 .fetch_one(&mut conn)
16 .await?;
17
18 assert_eq!(account.id, Some(1));
19 assert_eq!(account.name.as_deref(), Some("Herp Derpinson"));
20
21 Ok(())
22 }
23
24 #[sqlx_macros::test]
25 async fn test_non_null() -> anyhow::Result<()> {
26 let mut conn = new::<Postgres>().await?;
27 let mut tx = conn.begin().await?;
28
29 let _ = sqlx::query!("INSERT INTO tweet (text) VALUES ('Hello')")
30 .execute(&mut *tx)
31 .await?;
32
33 let row = sqlx::query!("SELECT id, text, owner_id FROM tweet LIMIT 1")
34 .fetch_one(&mut *tx)
35 .await?;
36
37 assert!(row.id > 0);
38 assert_eq!(row.text, "Hello");
39 assert_eq!(row.owner_id, None);
40
41 // let the transaction rollback so we don't actually insert the tweet
42
43 Ok(())
44 }
45
46 #[sqlx_macros::test]
47 async fn test_no_result() -> anyhow::Result<()> {
48 let mut conn = new::<Postgres>().await?;
49 let mut tx = conn.begin().await?;
50
51 let _ = sqlx::query!("DELETE FROM tweet").execute(&mut *tx).await?;
52
53 // let the transaction rollback so we don't actually delete the tweets
54
55 Ok(())
56 }
57
58 #[sqlx_macros::test]
59 async fn test_text_var_char_char_n() -> anyhow::Result<()> {
60 let mut conn = new::<Postgres>().await?;
61
62 // TEXT
63 // we cannot infer nullability from an expression
64 let rec = sqlx::query!("SELECT 'Hello'::text as greeting")
65 .fetch_one(&mut conn)
66 .await?;
67
68 assert_eq!(rec.greeting.as_deref(), Some("Hello"));
69
70 // VARCHAR(N)
71
72 let rec = sqlx::query!("SELECT 'Hello'::varchar(5) as greeting")
73 .fetch_one(&mut conn)
74 .await?;
75
76 assert_eq!(rec.greeting.as_deref(), Some("Hello"));
77
78 // CHAR(N)
79
80 let rec = sqlx::query!("SELECT 'Hello'::char(5) as greeting")
81 .fetch_one(&mut conn)
82 .await?;
83
84 assert_eq!(rec.greeting.as_deref(), Some("Hello"));
85
86 Ok(())
87 }
88
89 #[sqlx_macros::test]
90 async fn test_void() -> anyhow::Result<()> {
91 let mut conn = new::<Postgres>().await?;
92
93 let _ = sqlx::query!(r#"select pg_notify('chan', 'message')"#)
94 .execute(&mut conn)
95 .await?;
96
97 Ok(())
98 }
99
100 #[sqlx_macros::test]
101 async fn test_call_procedure() -> anyhow::Result<()> {
102 let mut conn = new::<Postgres>().await?;
103
104 let row = sqlx::query!(r#"CALL forty_two(null)"#)
105 .fetch_one(&mut conn)
106 .await?;
107
108 assert_eq!(row.forty_two, Some(42));
109
110 Ok(())
111 }
112
113 #[sqlx_macros::test]
114 async fn test_query_file() -> anyhow::Result<()> {
115 let mut conn = new::<Postgres>().await?;
116
117 // keep trailing comma as a test
118 let account = sqlx::query_file!("tests/postgres/test-query.sql")
119 .fetch_one(&mut conn)
120 .await?;
121
122 assert_eq!(account.id, 1);
123 assert_eq!(account.name, Option::<String>::None);
124
125 Ok(())
126 }
127
128 #[derive(Debug)]
129 struct Account {
130 id: i32,
131 name: Option<String>,
132 }
133
134 #[sqlx_macros::test]
135 async fn test_query_as() -> anyhow::Result<()> {
136 let mut conn = new::<Postgres>().await?;
137
138 let name: Option<&str> = None;
139 let account = sqlx::query_as!(
140 Account,
141 r#"SELECT id "id!", name from (VALUES (1, $1)) accounts(id, name)"#,
142 name
143 )
144 .fetch_one(&mut conn)
145 .await?;
146
147 assert_eq!(1, account.id);
148 assert_eq!(None, account.name);
149
150 println!("{account:?}");
151
152 Ok(())
153 }
154
155 #[derive(Debug)]
156 struct RawAccount {
157 r#type: i32,
158 name: Option<String>,
159 }
160
161 #[sqlx_macros::test]
162 async fn test_query_as_raw() -> anyhow::Result<()> {
163 let mut conn = new::<Postgres>().await?;
164
165 let account = sqlx::query_as!(
166 RawAccount,
167 r#"SELECT type "type!", name from (VALUES (1, null)) accounts(type, name)"#
168 )
169 .fetch_one(&mut conn)
170 .await?;
171
172 assert_eq!(None, account.name);
173 assert_eq!(1, account.r#type);
174
175 println!("{account:?}");
176
177 Ok(())
178 }
179
180 #[sqlx_macros::test]
181 async fn test_query_file_as() -> anyhow::Result<()> {
182 let mut conn = new::<Postgres>().await?;
183
184 let account = sqlx::query_file_as!(Account, "tests/postgres/test-query.sql")
185 .fetch_one(&mut conn)
186 .await?;
187
188 println!("{account:?}");
189
190 Ok(())
191 }
192
193 #[sqlx_macros::test]
194 async fn test_query_scalar() -> anyhow::Result<()> {
195 let mut conn = new::<Postgres>().await?;
196
197 let id = sqlx::query_scalar!("select 1").fetch_one(&mut conn).await?;
198 // nullability inference can't handle expressions
199 assert_eq!(id, Some(1i32));
200
201 // invalid column names are ignored
202 let id = sqlx::query_scalar!(r#"select 1 as "&foo""#)
203 .fetch_one(&mut conn)
204 .await?;
205 assert_eq!(id, Some(1i32));
206
207 let id = sqlx::query_scalar!(r#"select 1 as "foo!""#)
208 .fetch_one(&mut conn)
209 .await?;
210 assert_eq!(id, 1i32);
211
212 let id = sqlx::query_scalar!(r#"select 1 as "foo?""#)
213 .fetch_one(&mut conn)
214 .await?;
215
216 assert_eq!(id, Some(1i32));
217
218 let id = sqlx::query_scalar!(r#"select 1 as "foo: MyInt4""#)
219 .fetch_one(&mut conn)
220 .await?;
221
222 assert_eq!(id, Some(MyInt4(1i32)));
223
224 let id = sqlx::query_scalar!(r#"select 1 as "foo?: MyInt4""#)
225 .fetch_one(&mut conn)
226 .await?;
227
228 assert_eq!(id, Some(MyInt4(1i32)));
229
230 let id = sqlx::query_scalar!(r#"select 1 as "foo!: MyInt4""#)
231 .fetch_one(&mut conn)
232 .await?;
233
234 assert_eq!(id, MyInt4(1i32));
235
236 let id: MyInt4 = sqlx::query_scalar!(r#"select 1 as "foo: _""#)
237 .fetch_one(&mut conn)
238 .await?
239 // don't hint that it should be `Option<MyInt4>`
240 .unwrap();
241
242 assert_eq!(id, MyInt4(1i32));
243
244 let id: MyInt4 = sqlx::query_scalar!(r#"select 1 as "foo?: _""#)
245 .fetch_one(&mut conn)
246 .await?
247 // don't hint that it should be `Option<MyInt4>`
248 .unwrap();
249
250 assert_eq!(id, MyInt4(1i32));
251
252 let id: MyInt4 = sqlx::query_scalar!(r#"select 1 as "foo!: _""#)
253 .fetch_one(&mut conn)
254 .await?;
255
256 assert_eq!(id, MyInt4(1i32));
257
258 Ok(())
259 }
260
261 #[sqlx_macros::test]
262 async fn query_by_string() -> anyhow::Result<()> {
263 let mut conn = new::<Postgres>().await?;
264
265 let string = "Hello, world!".to_string();
266 let ref tuple = ("Hello, world!".to_string(),);
267
268 let result = sqlx::query!(
269 "SELECT * from (VALUES('Hello, world!')) strings(string)\
270 where string in ($1, $2, $3, $4, $5, $6, $7)",
271 string, // make sure we don't actually take ownership here
272 &string[..],
273 Some(&string),
274 Some(&string[..]),
275 Option::<String>::None,
276 string.clone(),
277 tuple.0 // make sure we're not trying to move out of a field expression
278 )
279 .fetch_one(&mut conn)
280 .await?;
281
282 assert_eq!(result.string, Some(string));
283
284 Ok(())
285 }
286
287 #[sqlx_macros::test]
288 #[cfg(feature = "bigdecimal")]
289 async fn query_by_bigdecimal() -> anyhow::Result<()> {
290 use sqlx::types::BigDecimal;
291 let mut conn = new::<Postgres>().await?;
292
293 // this tests querying by a non-`Copy` type that doesn't have special reborrow semantics
294
295 let decimal = "1234".parse::<BigDecimal>()?;
296 let ref tuple = ("51245.121232".parse::<BigDecimal>()?,);
297
298 let result = sqlx::query!(
299 "SELECT * from (VALUES(1234.0)) decimals(decimal)\
300 where decimal in ($1, $2, $3, $4, $5, $6, $7)",
301 decimal, // make sure we don't actually take ownership here
302 &decimal, // allow query-by-reference
303 Some(&decimal),
304 Some(&decimal),
305 Option::<BigDecimal>::None,
306 decimal.clone(),
307 tuple.0 // make sure we're not trying to move out of a field expression
308 )
309 .fetch_one(&mut conn)
310 .await?;
311
312 assert_eq!(result.decimal, Some(decimal));
313
314 Ok(())
315 }
316
317 #[sqlx_macros::test]
318 async fn test_nullable_err() -> anyhow::Result<()> {
319 #[allow(dead_code)]
320 #[derive(Debug)]
321 struct Account {
322 id: i32,
323 name: String,
324 }
325
326 let mut conn = new::<Postgres>().await?;
327
328 let err = sqlx::query_as!(
329 Account,
330 r#"SELECT id "id!", name "name!" from (VALUES (1, null::text)) accounts(id, name)"#
331 )
332 .fetch_one(&mut conn)
333 .await
334 .unwrap_err();
335
336 if let sqlx::Error::ColumnDecode { source, .. } = &err {
337 if let Some(sqlx::error::UnexpectedNullError) = source.downcast_ref() {
338 return Ok(());
339 }
340 }
341
342 panic!("expected `UnexpectedNullError`, got {err}")
343 }
344
345 #[sqlx_macros::test]
346 async fn test_many_args() -> anyhow::Result<()> {
347 let mut conn = new::<Postgres>().await?;
348
349 // previous implementation would only have supported 10 bind parameters
350 // (this is really gross to test in MySQL)
351 let rows = sqlx::query!(
352 "SELECT * from unnest(array[$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12]::int[]) ids(id);",
353 0i32, 1i32, 2i32, 3i32, 4i32, 5i32, 6i32, 7i32, 8i32, 9i32, 10i32, 11i32
354 )
355 .fetch_all(&mut conn)
356 .await?;
357
358 for (i, row) in rows.iter().enumerate() {
359 assert_eq!(Some(i as i32), row.id);
360 }
361
362 Ok(())
363 }
364
365 #[sqlx_macros::test]
366 async fn test_array_from_slice() -> anyhow::Result<()> {
367 let mut conn = new::<Postgres>().await?;
368
369 let list: &[i32] = &[1, 2, 3, 4i32];
370
371 let result = sqlx::query!("SELECT $1::int[] as my_array", list)
372 .fetch_one(&mut conn)
373 .await?;
374
375 assert_eq!(result.my_array, Some(vec![1, 2, 3, 4]));
376
377 println!("result ID: {:?}", result.my_array);
378
379 let account = sqlx::query!("SELECT ARRAY[4,3,2,1] as my_array")
380 .fetch_one(&mut conn)
381 .await?;
382
383 assert_eq!(account.my_array, Some(vec![4, 3, 2, 1]));
384
385 println!("account ID: {:?}", account.my_array);
386
387 Ok(())
388 }
389
390 #[sqlx_macros::test]
391 async fn fetch_is_usable_issue_224() -> anyhow::Result<()> {
392 // ensures that the stream returned by `query::Map::fetch()` is usable with `TryStreamExt`
393 let mut conn = new::<Postgres>().await?;
394
395 let mut stream =
396 sqlx::query!("select * from generate_series(1, 3) as series(num);").fetch(&mut conn);
397
398 // `num` is generated by a function so we can't assume it's non-null
399 assert_eq!(stream.try_next().await?.unwrap().num, Some(1));
400 assert_eq!(stream.try_next().await?.unwrap().num, Some(2));
401 assert_eq!(stream.try_next().await?.unwrap().num, Some(3));
402 assert!(stream.try_next().await?.is_none());
403
404 Ok(())
405 }
406
407 #[sqlx_macros::test]
408 async fn test_column_override_not_null() -> anyhow::Result<()> {
409 let mut conn = new::<Postgres>().await?;
410
411 let record = sqlx::query!(r#"select 1 as "id!""#)
412 .fetch_one(&mut conn)
413 .await?;
414
415 assert_eq!(record.id, 1);
416
417 Ok(())
418 }
419
420 #[sqlx_macros::test]
421 async fn test_column_override_nullable() -> anyhow::Result<()> {
422 let mut conn = new::<Postgres>().await?;
423
424 // workaround for https://github.com/launchbadge/sqlx/issues/367
425 // declare a `NOT NULL` column from a left-joined table to be nullable
426 let record = sqlx::query!(
427 r#"select text as "text?" from (values (1)) foo(id) left join tweet on false"#
428 )
429 .fetch_one(&mut conn)
430 .await?;
431
432 assert_eq!(record.text, None);
433
434 Ok(())
435 }
436
437 async fn with_test_row<'a>(
438 conn: &'a mut PgConnection,
439 ) -> anyhow::Result<Transaction<'a, Postgres>> {
440 let mut transaction = conn.begin().await?;
441 sqlx::query!("INSERT INTO tweet(id, text, owner_id) VALUES (1, '#sqlx is pretty cool!', 1)")
442 .execute(&mut *transaction)
443 .await?;
444 Ok(transaction)
445 }
446
447 #[derive(PartialEq, Eq, Debug, sqlx::Type)]
448 #[sqlx(transparent)]
449 struct MyInt(i64);
450
451 #[derive(PartialEq, Eq, Debug, sqlx::Type)]
452 #[sqlx(transparent)]
453 struct MyInt4(i32);
454
455 struct Record {
456 id: MyInt,
457 }
458
459 struct OptionalRecord {
460 id: Option<MyInt>,
461 }
462
463 #[sqlx_macros::test]
464 async fn test_column_override_wildcard() -> anyhow::Result<()> {
465 let mut conn = new::<Postgres>().await?;
466 let mut conn = with_test_row(&mut conn).await?;
467
468 let record = sqlx::query_as!(Record, r#"select id as "id: _" from tweet"#)
469 .fetch_one(&mut *conn)
470 .await?;
471
472 assert_eq!(record.id, MyInt(1));
473
474 let record = sqlx::query_as!(OptionalRecord, r#"select owner_id as "id: _" from tweet"#)
475 .fetch_one(&mut *conn)
476 .await?;
477
478 assert_eq!(record.id, Some(MyInt(1)));
479
480 Ok(())
481 }
482
483 #[sqlx_macros::test]
484 async fn test_column_override_wildcard_not_null() -> anyhow::Result<()> {
485 let mut conn = new::<Postgres>().await?;
486 let mut conn = with_test_row(&mut conn).await?;
487
488 let record = sqlx::query_as!(Record, r#"select owner_id as "id!: _" from tweet"#)
489 .fetch_one(&mut *conn)
490 .await?;
491
492 assert_eq!(record.id, MyInt(1));
493
494 Ok(())
495 }
496
497 #[sqlx_macros::test]
498 async fn test_column_override_wildcard_nullable() -> anyhow::Result<()> {
499 let mut conn = new::<Postgres>().await?;
500 let mut conn = with_test_row(&mut conn).await?;
501
502 let record = sqlx::query_as!(OptionalRecord, r#"select id as "id?: _" from tweet"#)
503 .fetch_one(&mut *conn)
504 .await?;
505
506 assert_eq!(record.id, Some(MyInt(1)));
507
508 Ok(())
509 }
510
511 #[sqlx_macros::test]
512 async fn test_column_override_exact() -> anyhow::Result<()> {
513 let mut conn = new::<Postgres>().await?;
514 let mut conn = with_test_row(&mut conn).await?;
515
516 let record = sqlx::query!(r#"select id as "id: MyInt" from tweet"#)
517 .fetch_one(&mut *conn)
518 .await?;
519
520 assert_eq!(record.id, MyInt(1));
521
522 let record = sqlx::query!(r#"select owner_id as "id: MyInt" from tweet"#)
523 .fetch_one(&mut *conn)
524 .await?;
525
526 assert_eq!(record.id, Some(MyInt(1)));
527
528 Ok(())
529 }
530
531 #[sqlx_macros::test]
532 async fn test_column_override_exact_not_null() -> anyhow::Result<()> {
533 let mut conn = new::<Postgres>().await?;
534 let mut conn = with_test_row(&mut conn).await?;
535
536 let record = sqlx::query!(r#"select owner_id as "id!: MyInt" from tweet"#)
537 .fetch_one(&mut *conn)
538 .await?;
539
540 assert_eq!(record.id, MyInt(1));
541
542 Ok(())
543 }
544
545 #[sqlx_macros::test]
546 async fn test_column_override_exact_nullable() -> anyhow::Result<()> {
547 let mut conn = new::<Postgres>().await?;
548 let mut conn = with_test_row(&mut conn).await?;
549
550 let record = sqlx::query!(r#"select id as "id?: MyInt" from tweet"#)
551 .fetch_one(&mut *conn)
552 .await?;
553
554 assert_eq!(record.id, Some(MyInt(1)));
555
556 Ok(())
557 }
558
559 #[sqlx_macros::test]
560 async fn test_bind_arg_override_exact() -> anyhow::Result<()> {
561 let mut conn = new::<Postgres>().await?;
562
563 let my_int = MyInt4(1);
564
565 // this query should require a bind parameter override as we would otherwise expect the bind
566 // to be the same type
567 let record = sqlx::query!(
568 "select * from (select 1::int4) records(id) where id = $1",
569 my_int as MyInt4
570 )
571 .fetch_one(&mut conn)
572 .await?;
573
574 assert_eq!(record.id, Some(1i32));
575
576 // test that we're actually emitting the typecast by requiring the bound type to be the same
577 let record = sqlx::query!("select $1::int8 as id", 1i32 as i64)
578 .fetch_one(&mut conn)
579 .await?;
580
581 assert_eq!(record.id, Some(1i64));
582
583 // test the override with `Option`
584 let my_opt_int = Some(MyInt4(1));
585
586 let record = sqlx::query!(
587 "select * from (select 1::int4) records(id) where id = $1",
588 my_opt_int as Option<MyInt4>
589 )
590 .fetch_one(&mut conn)
591 .await?;
592
593 assert_eq!(record.id, Some(1i32));
594
595 Ok(())
596 }
597
598 #[sqlx_macros::test]
599 async fn test_bind_arg_override_wildcard() -> anyhow::Result<()> {
600 let mut conn = new::<Postgres>().await?;
601
602 let my_int = MyInt4(1);
603
604 let record = sqlx::query!(
605 "select * from (select 1::int4) records(id) where id = $1",
606 my_int as _
607 )
608 .fetch_one(&mut conn)
609 .await?;
610
611 assert_eq!(record.id, Some(1i32));
612
613 Ok(())
614 }
615
616 #[sqlx_macros::test]
617 async fn test_to_from_citext() -> anyhow::Result<()> {
618 // Ensure that the macros consider `CITEXT` to be compatible with `String` and friends
619
620 let mut conn = new::<Postgres>().await?;
621
622 let mut tx = conn.begin().await?;
623
624 let foo_in = "Hello, world!";
625
626 sqlx::query!("insert into test_citext(foo) values ($1)", foo_in)
627 .execute(&mut *tx)
628 .await?;
629
630 let foo_out: String = sqlx::query_scalar!("select foo from test_citext")
631 .fetch_one(&mut *tx)
632 .await?;
633
634 assert_eq!(foo_in, foo_out);
635
636 tx.rollback().await?;
637
638 Ok(())
639 }
640
641 #[sqlx_macros::test]
642 async fn pghstore_tests() -> anyhow::Result<()> {
643 let mut conn = new::<Postgres>().await?;
644
645 let mut store = PgHstore::default();
646 let stores = vec![store.clone(), store.clone()];
647
648 store.insert("key".into(), Some("value".to_string()));
649 sqlx::query!(" insert into mytable(f) values ($1)", store)
650 .execute(&mut conn)
651 .await?;
652
653 sqlx::query!(
654 " insert into mytable(f) select * from unnest($1::hstore[])",
655 &stores
656 )
657 .execute(&mut conn)
658 .await?;
659
660 Ok(())
661 }