Debian Codegraph @

tests/sqlite/types.rs

raw symbols SCIP
1 extern crate time_ as time;
2
3 use sqlx::sqlite::{Sqlite, SqliteRow};
4 use sqlx_core::executor::Executor;
5 use sqlx_core::row::Row;
6 use sqlx_core::types::Text;
7 use sqlx_test::new;
8 use sqlx_test::test_type;
9 use std::net::SocketAddr;
10
11 test_type!(null<Option<i32>>(Sqlite,
12 "NULL" == None::<i32>
13 ));
14
15 test_type!(bool(Sqlite, "FALSE" == false, "TRUE" == true));
16
17 test_type!(i32(Sqlite, "94101" == 94101_i32));
18
19 test_type!(i64(Sqlite, "9358295312" == 9358295312_i64));
20
21 // NOTE: This behavior can be surprising. Floating-point parameters are widening to double which can
22 // result in strange rounding.
23 test_type!(f32(Sqlite, "3.1410000324249268" == 3.141f32 as f64 as f32));
24
25 test_type!(f64(Sqlite, "939399419.1225182" == 939399419.1225182_f64));
26
27 test_type!(str<String>(Sqlite,
28 "'this is foo'" == "this is foo",
29 "cast(x'7468697320006973206E756C2D636F6E7461696E696E67' as text)" == "this \0is nul-containing",
30 "''" == ""
31 ));
32
33 test_type!(bytes<Vec<u8>>(Sqlite,
34 "X'DEADBEEF'"
35 == vec![0xDE_u8, 0xAD, 0xBE, 0xEF],
36 "X''"
37 == Vec::<u8>::new(),
38 "X'0000000052'"
39 == vec![0_u8, 0, 0, 0, 0x52]
40 ));
41
42 #[cfg(feature = "json")]
43 mod json_tests {
44 use super::*;
45 use serde_json::{json, Value as JsonValue};
46 use sqlx::types::Json;
47 use sqlx_test::test_type;
48
49 test_type!(json<JsonValue>(
50 Sqlite,
51 "'\"Hello, World\"'" == json!("Hello, World"),
52 "'\"😎\"'" == json!("😎"),
53 "'\"🙋‍♀️\"'" == json!("🙋‍♀️"),
54 "'[\"Hello\",\"World!\"]'" == json!(["Hello", "World!"])
55 ));
56
57 #[derive(serde::Deserialize, serde::Serialize, Debug, PartialEq)]
58 struct Friend {
59 name: String,
60 age: u32,
61 }
62
63 test_type!(json_struct<Json<Friend>>(
64 Sqlite,
65 "\'{\"name\":\"Joe\",\"age\":33}\'" == Json(Friend { name: "Joe".to_string(), age: 33 })
66 ));
67
68 // NOTE: This is testing recursive (and transparent) usage of the `Json` wrapper. You don't
69 // need to wrap the Vec in Json<_> to make the example work.
70
71 #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
72 struct Customer {
73 json_column: Json<Vec<i64>>,
74 }
75
76 test_type!(json_struct_json_column<Json<Customer>>(
77 Sqlite,
78 "\'{\"json_column\":[1,2]}\'" == Json(Customer { json_column: Json(vec![1, 2]) })
79 ));
80
81 #[sqlx_macros::test]
82 async fn it_json_extracts() -> anyhow::Result<()> {
83 let mut conn = new::<Sqlite>().await?;
84
85 let value = sqlx::query("select JSON_EXTRACT(JSON('{ \"number\": 42 }'), '$.number') = ?1")
86 .bind(42_i32)
87 .try_map(|row: SqliteRow| row.try_get::<bool, _>(0))
88 .fetch_one(&mut conn)
89 .await?;
90
91 assert_eq!(true, value);
92
93 Ok(())
94 }
95 }
96
97 #[cfg(feature = "chrono")]
98 mod chrono {
99 use super::*;
100 use sqlx::types::chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc};
101
102 test_type!(chrono_naive_date_time<NaiveDateTime>(Sqlite, "SELECT datetime({0}) is datetime(?), {0}, ?",
103 "'2019-01-02 05:10:20'" == NaiveDate::from_ymd_opt(2019, 1, 2).unwrap().and_hms_opt(5, 10, 20).unwrap()
104 ));
105
106 test_type!(chrono_date_time_utc<DateTime::<Utc>>(Sqlite, "SELECT datetime({0}) is datetime(?), {0}, ?",
107 "'1996-12-20T00:39:57+00:00'" == Utc.with_ymd_and_hms(1996, 12, 20, 0, 39, 57).unwrap()
108 ));
109
110 test_type!(chrono_date_time_fixed_offset<DateTime::<FixedOffset>>(Sqlite, "SELECT datetime({0}) is datetime(?), {0}, ?",
111 "'2016-11-08T03:50:23-05:00'" == DateTime::<Utc>::from(FixedOffset::west_opt(5 * 3600).unwrap().with_ymd_and_hms(2016, 11, 08, 3, 50, 23).unwrap())
112 ));
113 }
114
115 #[cfg(feature = "time")]
116 mod time_tests {
117 use super::*;
118 use sqlx::types::time::{Date, OffsetDateTime, PrimitiveDateTime, Time};
119 use time::macros::{date, datetime, time};
120
121 test_type!(time_offset_date_time<OffsetDateTime>(
122 Sqlite,
123 "SELECT datetime({0}) is datetime(?), {0}, ?",
124 "'2015-11-19 01:01:39+01:00'" == datetime!(2015 - 11 - 19 1:01:39 +1),
125 "'2014-10-18 00:00:38.697+00:00'" == datetime!(2014 - 10 - 18 00:00:38.697 +0),
126 "'2013-09-17 23:59-01:00'" == datetime!(2013 - 9 - 17 23:59 -1),
127 "'2016-03-07T22:36:55.135+03:30'" == datetime!(2016 - 3 - 7 22:36:55.135 +3:30),
128 "'2017-04-11T14:35+02:00'" == datetime!(2017 - 4 - 11 14:35 +2),
129 ));
130
131 test_type!(time_primitive_date_time<PrimitiveDateTime>(
132 Sqlite,
133 "SELECT datetime({0}) is datetime(?), {0}, ?",
134 "'2019-01-02 05:10:20'" == datetime!(2019 - 1 - 2 5:10:20),
135 "'2018-12-01 04:09:19.543'" == datetime!(2018 - 12 - 1 4:09:19.543),
136 "'2017-11-30 03:08'" == datetime!(2017 - 11 - 30 3:08),
137 "'2016-10-29T02:07:17'" == datetime!(2016 - 10 - 29 2:07:17),
138 "'2015-09-28T01:06:16.432'" == datetime!(2015 - 9 - 28 1:06:16.432),
139 "'2014-08-27T00:05'" == datetime!(2014 - 8 - 27 0:05),
140 "'2013-07-26 23:04:14Z'" == datetime!(2013 - 7 - 26 23:04:14),
141 "'2012-06-25 22:03:13.321Z'" == datetime!(2012 - 6 - 25 22:03:13.321),
142 "'2011-05-24 21:02Z'" == datetime!(2011 - 5 - 24 21:02),
143 "'2010-04-23T20:01:11Z'" == datetime!(2010 - 4 - 23 20:01:11),
144 "'2009-03-22T19:00:10.21Z'" == datetime!(2009 - 3 - 22 19:00:10.21),
145 "'2008-02-21T18:59Z'" == datetime!(2008 - 2 - 21 18:59:00),
146 ));
147
148 test_type!(time_date<Date>(
149 Sqlite,
150 "SELECT date({0}) is date(?), {0}, ?",
151 "'2002-06-04'" == date!(2002 - 6 - 4),
152 ));
153
154 test_type!(time_time<Time>(
155 Sqlite,
156 "SELECT time({0}) is time(?), {0}, ?",
157 "'21:46:32'" == time!(21:46:32),
158 "'20:45:31.133'" == time!(20:45:31.133),
159 "'19:44'" == time!(19:44),
160 ));
161 }
162
163 #[cfg(feature = "bstr")]
164 mod bstr {
165 use super::*;
166 use sqlx::types::bstr::BString;
167
168 test_type!(bstring<BString>(Sqlite,
169 "cast('abc123' as blob)" == BString::from(&b"abc123"[..]),
170 "x'0001020304'" == BString::from(&b"\x00\x01\x02\x03\x04"[..])
171 ));
172 }
173
174 #[cfg(feature = "git2")]
175 mod git2 {
176 use super::*;
177 use sqlx::types::git2::Oid;
178
179 test_type!(oid<Oid>(
180 Sqlite,
181 "x'0000000000000000000000000000000000000000'" == Oid::zero(),
182 "x'000102030405060708090a0b0c0d0e0f10111213'"
183 == Oid::from_str("000102030405060708090a0b0c0d0e0f10111213").unwrap()
184 ));
185 }
186
187 #[cfg(feature = "uuid")]
188 test_type!(uuid<sqlx::types::Uuid>(Sqlite,
189 "x'b731678f636f4135bc6f19440c13bd19'"
190 == sqlx::types::Uuid::parse_str("b731678f-636f-4135-bc6f-19440c13bd19").unwrap(),
191 "x'00000000000000000000000000000000'"
192 == sqlx::types::Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap()
193 ));
194
195 #[cfg(feature = "uuid")]
196 test_type!(uuid_hyphenated<sqlx::types::uuid::fmt::Hyphenated>(Sqlite,
197 "'b731678f-636f-4135-bc6f-19440c13bd19'"
198 == sqlx::types::Uuid::parse_str("b731678f-636f-4135-bc6f-19440c13bd19").unwrap().hyphenated(),
199 "'00000000-0000-0000-0000-000000000000'"
200 == sqlx::types::Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap().hyphenated()
201 ));
202
203 #[cfg(feature = "uuid")]
204 test_type!(uuid_simple<sqlx::types::uuid::fmt::Simple>(Sqlite,
205 "'b731678f636f4135bc6f19440c13bd19'"
206 == sqlx::types::Uuid::parse_str("b731678f636f4135bc6f19440c13bd19").unwrap().simple(),
207 "'00000000000000000000000000000000'"
208 == sqlx::types::Uuid::parse_str("00000000000000000000000000000000").unwrap().simple()
209 ));
210
211 #[sqlx_macros::test]
212 async fn test_text_adapter() -> anyhow::Result<()> {
213 #[derive(sqlx::FromRow, Debug, PartialEq, Eq)]
214 struct Login {
215 user_id: i32,
216 socket_addr: Text<SocketAddr>,
217 #[cfg(feature = "time")]
218 login_at: time::OffsetDateTime,
219 }
220
221 let mut conn = new::<Sqlite>().await?;
222
223 conn.execute(
224 r#"
225 CREATE TEMPORARY TABLE user_login (
226 user_id INT PRIMARY KEY,
227 socket_addr TEXT NOT NULL,
228 login_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
229 );
230 "#,
231 )
232 .await?;
233
234 let user_id = 1234;
235 let socket_addr: SocketAddr = "198.51.100.47:31790".parse().unwrap();
236
237 sqlx::query("INSERT INTO user_login (user_id, socket_addr) VALUES (?, ?)")
238 .bind(user_id)
239 .bind(Text(socket_addr))
240 .execute(&mut conn)
241 .await?;
242
243 let last_login: Login =
244 sqlx::query_as("SELECT * FROM user_login ORDER BY login_at DESC LIMIT 1")
245 .fetch_one(&mut conn)
246 .await?;
247
248 assert_eq!(last_login.user_id, user_id);
249 assert_eq!(*last_login.socket_addr, socket_addr);
250
251 Ok(())
252 }