Debian Codegraph @

third_party/rust/arraystring/src/integration.rs

raw
1 //! Integrates `ArrayString` with other crates' traits
2
3 use crate::prelude::*;
4
5 #[cfg(all(feature = "diesel-traits", feature = "std"))]
6 use std::io::Write;
7
8 #[cfg(feature = "diesel-traits")]
9 use diesel::{expression::*, prelude::*, query_builder::*, row::Row, sql_types::*};
10
11 #[cfg(feature = "diesel-traits")]
12 use diesel::backend::Backend;
13
14 #[cfg(feature = "diesel-traits")]
15 use diesel::deserialize::{self, FromSql, FromSqlRow, Queryable};
16
17 #[cfg(all(feature = "diesel-traits", feature = "std"))]
18 use diesel::serialize::{self, Output, ToSql};
19
20 #[cfg(feature = "serde-traits")]
21 use serde::{de::Deserializer, ser::Serializer, Deserialize, Serialize};
22
23 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "serde-traits")))]
24 #[cfg(feature = "serde-traits")]
25 impl<SIZE> Serialize for ArrayString<SIZE>
26 where
27 SIZE: Capacity,
28 {
29 #[inline]
30 fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
31 Serialize::serialize(self.as_str(), ser)
32 }
33 }
34
35 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "serde-traits")))]
36 #[cfg(feature = "serde-traits")]
37 impl<'a, SIZE> Deserialize<'a> for ArrayString<SIZE>
38 where
39 SIZE: Capacity,
40 {
41 #[inline]
42 fn deserialize<D: Deserializer<'a>>(des: D) -> Result<Self, D::Error> {
43 <&str>::deserialize(des).map(Self::from_str_truncate)
44 }
45 }
46
47 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
48 #[cfg(feature = "diesel-traits")]
49 impl<SIZE: Capacity> Expression for ArrayString<SIZE> {
50 type SqlType = VarChar;
51 }
52
53 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
54 #[cfg(feature = "diesel-traits")]
55 impl<SIZE: Capacity, QS> SelectableExpression<QS> for ArrayString<SIZE> {}
56 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
57 #[cfg(feature = "diesel-traits")]
58 impl<SIZE: Capacity, QS> AppearsOnTable<QS> for ArrayString<SIZE> {}
59 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
60 #[cfg(feature = "diesel-traits")]
61 impl<SIZE: Capacity> NonAggregate for ArrayString<SIZE> {}
62
63 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
64 #[cfg(feature = "diesel-traits")]
65 impl<SIZE, DB> QueryFragment<DB> for ArrayString<SIZE>
66 where
67 SIZE: Capacity,
68 DB: Backend + HasSqlType<VarChar>,
69 {
70 #[inline]
71 fn walk_ast(&self, mut pass: AstPass<DB>) -> QueryResult<()> {
72 pass.push_bind_param::<Varchar, _>(&self.as_str())?;
73 Ok(())
74 }
75 }
76
77 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
78 #[cfg(feature = "diesel-traits")]
79 impl<SIZE, ST, DB> FromSql<ST, DB> for ArrayString<SIZE>
80 where
81 SIZE: Capacity,
82 DB: Backend,
83 *const str: FromSql<ST, DB>,
84 {
85 #[inline]
86 fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
87 let ptr: *const str = FromSql::<ST, DB>::from_sql(bytes)?;
88 // We know that the pointer impl will never return null
89 Ok(Self::from_str_truncate(unsafe { &*ptr }))
90 }
91 }
92
93 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
94 #[cfg(feature = "diesel-traits")]
95 impl<SIZE, ST, DB> FromSqlRow<ST, DB> for ArrayString<SIZE>
96 where
97 SIZE: Capacity,
98 DB: Backend,
99 *const str: FromSql<ST, DB>,
100 {
101 const FIELDS_NEEDED: usize = 1;
102
103 #[inline]
104 fn build_from_row<T: Row<DB>>(row: &mut T) -> deserialize::Result<Self> {
105 FromSql::<ST, DB>::from_sql(row.take())
106 }
107 }
108
109 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
110 #[cfg(feature = "diesel-traits")]
111 impl<SIZE, ST, DB> Queryable<ST, DB> for ArrayString<SIZE>
112 where
113 SIZE: Capacity,
114 DB: Backend,
115 *const str: FromSql<ST, DB>,
116 {
117 type Row = Self;
118
119 #[inline]
120 fn build(row: Self::Row) -> Self {
121 row
122 }
123 }
124
125 #[cfg_attr(
126 docs_rs_workaround,
127 doc(cfg(all(feature = "diesel-traits", feature = "std")))
128 )]
129 #[cfg(all(feature = "diesel-traits", feature = "std"))]
130 impl<SIZE, DB> ToSql<VarChar, DB> for ArrayString<SIZE>
131 where
132 SIZE: Capacity,
133 DB: Backend,
134 {
135 #[inline]
136 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
137 ToSql::<VarChar, DB>::to_sql(self.as_str(), out)
138 }
139 }
140
141 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
142 #[cfg(feature = "diesel-traits")]
143 impl Expression for CacheString {
144 type SqlType = VarChar;
145 }
146
147 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
148 #[cfg(feature = "diesel-traits")]
149 impl<QS> SelectableExpression<QS> for CacheString {}
150 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
151 #[cfg(feature = "diesel-traits")]
152 impl<QS> AppearsOnTable<QS> for CacheString {}
153 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
154 #[cfg(feature = "diesel-traits")]
155 impl NonAggregate for CacheString {}
156
157 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
158 #[cfg(feature = "diesel-traits")]
159 impl<DB> QueryFragment<DB> for CacheString
160 where
161 DB: Backend + HasSqlType<VarChar>,
162 {
163 #[inline]
164 fn walk_ast(&self, pass: AstPass<DB>) -> QueryResult<()> {
165 self.0.walk_ast(pass)
166 }
167 }
168
169 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
170 #[cfg(feature = "diesel-traits")]
171 impl<ST, DB> FromSql<ST, DB> for CacheString
172 where
173 DB: Backend,
174 *const str: FromSql<ST, DB>,
175 {
176 #[inline]
177 fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
178 Ok(CacheString(FromSql::from_sql(bytes)?))
179 }
180 }
181
182 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
183 #[cfg(feature = "diesel-traits")]
184 impl<ST, DB> FromSqlRow<ST, DB> for CacheString
185 where
186 DB: Backend,
187 *const str: FromSql<ST, DB>,
188 {
189 const FIELDS_NEEDED: usize = 1;
190
191 #[inline]
192 fn build_from_row<T: Row<DB>>(row: &mut T) -> deserialize::Result<Self> {
193 Ok(CacheString(FromSqlRow::build_from_row(row)?))
194 }
195 }
196
197 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "diesel-traits")))]
198 #[cfg(feature = "diesel-traits")]
199 impl<ST, DB> Queryable<ST, DB> for CacheString
200 where
201 DB: Backend,
202 *const str: FromSql<ST, DB>,
203 {
204 type Row = Self;
205
206 #[inline]
207 fn build(row: Self::Row) -> Self {
208 row
209 }
210 }
211
212 #[cfg_attr(
213 docs_rs_workaround,
214 doc(cfg(all(feature = "diesel-traits", feature = "std")))
215 )]
216 #[cfg(all(feature = "diesel-traits", feature = "std"))]
217 impl<DB> ToSql<VarChar, DB> for CacheString
218 where
219 DB: Backend,
220 {
221 #[inline]
222 fn to_sql<W: Write>(&self, out: &mut Output<W, DB>) -> serialize::Result {
223 ToSql::to_sql(&self.0, out)
224 }
225 }
226
227 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "serde-traits")))]
228 #[cfg(feature = "serde-traits")]
229 impl Serialize for CacheString {
230 #[inline]
231 fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
232 self.0.serialize(ser)
233 }
234 }
235
236 #[cfg_attr(docs_rs_workaround, doc(cfg(feature = "serde-traits")))]
237 #[cfg(feature = "serde-traits")]
238 impl<'a> Deserialize<'a> for CacheString {
239 #[inline]
240 fn deserialize<D: Deserializer<'a>>(des: D) -> Result<Self, D::Error> {
241 Ok(CacheString(Deserialize::deserialize(des)?))
242 }
243 }
244
245 #[cfg(test)]
246 mod tests {
247 #![allow(proc_macro_derive_resolution_fallback)]
248 #![allow(unused_import_braces)]
249
250 use super::*;
251 use crate::ArrayString;
252
253 #[cfg(feature = "serde-traits")]
254 #[derive(Serialize, Deserialize, PartialEq, Debug)]
255 struct DeriveSerde(pub ArrayString<typenum::U8>);
256
257 #[cfg(feature = "serde-traits")]
258 #[derive(Serialize, Deserialize, PartialEq, Debug)]
259 struct Derive2Serde(pub CacheString);
260
261 #[test]
262 #[cfg(feature = "serde-traits")]
263 fn serde_derive_json() {
264 let string =
265 serde_json::to_string(&DeriveSerde(ArrayString::try_from_str("abcdefg").unwrap()))
266 .unwrap();
267 let s: DeriveSerde = serde_json::from_str(&string).unwrap();
268 assert_eq!(
269 s,
270 DeriveSerde(ArrayString::try_from_str("abcdefg").unwrap())
271 );
272 }
273
274 #[test]
275 #[cfg(feature = "serde-traits")]
276 fn serde_derive2_json() {
277 let string = serde_json::to_string(&Derive2Serde(CacheString(
278 ArrayString::try_from_str("abcdefg").unwrap(),
279 )))
280 .unwrap();
281 let s: DeriveSerde = serde_json::from_str(&string).unwrap();
282 assert_eq!(
283 s,
284 DeriveSerde(ArrayString::try_from_str("abcdefg").unwrap())
285 );
286 }
287
288 #[test]
289 #[cfg(feature = "serde-traits")]
290 fn serde_json() {
291 let string =
292 serde_json::to_string(&ArrayString::<typenum::U8>::try_from_str("abcdefg").unwrap())
293 .unwrap();
294 let s: ArrayString<typenum::U8> = serde_json::from_str(&string).unwrap();
295 assert_eq!(
296 s,
297 ArrayString::<typenum::U8>::try_from_str("abcdefg").unwrap()
298 );
299 }
300
301 #[cfg(all(feature = "diesel-traits", feature = "std"))]
302 use diesel::{debug_query, insert_into, mysql, pg, sqlite, update};
303
304 #[cfg(all(feature = "diesel-traits", feature = "std"))]
305 #[macro_use]
306 table! {
307 derives (name) {
308 name -> VarChar,
309 }
310 }
311
312 #[cfg(all(feature = "diesel-traits", feature = "std"))]
313 #[derive(Queryable, Insertable, Clone, Debug)]
314 #[table_name = "derives"]
315 struct DeriveDiesel {
316 pub name: ArrayString<typenum::U32>,
317 }
318
319 #[cfg(all(feature = "diesel-traits", feature = "std"))]
320 #[derive(Queryable, Insertable, Clone, Debug)]
321 #[table_name = "derives"]
322 struct Derive2Diesel {
323 pub name: CacheString,
324 }
325
326 #[cfg(all(feature = "diesel-traits", feature = "std"))]
327 #[derive(Queryable, Insertable, Clone, Debug)]
328 #[table_name = "derives"]
329 struct Derive3Diesel<'a> {
330 pub name: &'a str,
331 }
332
333 #[cfg(all(feature = "diesel-traits", feature = "std"))]
334 #[test]
335 fn diesel_derive_query_compare_insert() {
336 let array = DeriveDiesel {
337 name: ArrayString::try_from_str("Name1").unwrap(),
338 };
339 let cache = Derive2Diesel {
340 name: CacheString(ArrayString::try_from_str("Name1").unwrap()),
341 };
342 let string = Derive3Diesel { name: "Name1" };
343
344 let insert_array = insert_into(derives::table).values(&array);
345 let insert_cache = insert_into(derives::table).values(&cache);
346 let insert_string = insert_into(derives::table).values(&string);
347 assert_eq!(
348 debug_query::<pg::Pg, _>(&insert_array).to_string(),
349 debug_query::<pg::Pg, _>(&insert_string).to_string()
350 );
351 assert_eq!(
352 debug_query::<pg::Pg, _>(&insert_cache).to_string(),
353 debug_query::<pg::Pg, _>(&insert_string).to_string()
354 );
355 assert_eq!(
356 debug_query::<mysql::Mysql, _>(&insert_array).to_string(),
357 debug_query::<mysql::Mysql, _>(&insert_string).to_string()
358 );
359 assert_eq!(
360 debug_query::<mysql::Mysql, _>(&insert_cache).to_string(),
361 debug_query::<mysql::Mysql, _>(&insert_string).to_string()
362 );
363 assert_eq!(
364 debug_query::<sqlite::Sqlite, _>(&insert_array).to_string(),
365 debug_query::<sqlite::Sqlite, _>(&insert_string).to_string()
366 );
367 assert_eq!(
368 debug_query::<sqlite::Sqlite, _>(&insert_cache).to_string(),
369 debug_query::<sqlite::Sqlite, _>(&insert_string).to_string()
370 );
371 }
372
373 #[test]
374 fn diesel_derive_query_compare_update() {
375 let array = DeriveDiesel {
376 name: ArrayString::try_from_str("Name1").unwrap(),
377 };
378 let cache = Derive2Diesel {
379 name: CacheString(ArrayString::try_from_str("Name1").unwrap()),
380 };
381 let string = Derive3Diesel { name: "Name1" };
382 let update_array = update(derives::table).set(derives::name.eq(&array.name));
383 let update_cache = update(derives::table).set(derives::name.eq(&cache.name));
384 let update_string = update(derives::table).set(derives::name.eq(&string.name));
385 assert_eq!(
386 debug_query::<pg::Pg, _>(&update_array).to_string(),
387 debug_query::<pg::Pg, _>(&update_string).to_string()
388 );
389 assert_eq!(
390 debug_query::<pg::Pg, _>(&update_cache).to_string(),
391 debug_query::<pg::Pg, _>(&update_string).to_string()
392 );
393 assert_eq!(
394 debug_query::<mysql::Mysql, _>(&update_array).to_string(),
395 debug_query::<mysql::Mysql, _>(&update_string).to_string()
396 );
397 assert_eq!(
398 debug_query::<mysql::Mysql, _>(&update_cache).to_string(),
399 debug_query::<mysql::Mysql, _>(&update_string).to_string()
400 );
401 assert_eq!(
402 debug_query::<sqlite::Sqlite, _>(&update_array).to_string(),
403 debug_query::<sqlite::Sqlite, _>(&update_string).to_string()
404 );
405 assert_eq!(
406 debug_query::<sqlite::Sqlite, _>(&update_cache).to_string(),
407 debug_query::<sqlite::Sqlite, _>(&update_string).to_string()
408 );
409 }
410
411 #[test]
412 #[ignore]
413 #[cfg(feature = "std")]
414 fn diesel_select_query_compiles() {
415 let conn = pg::PgConnection::establish("").unwrap();
416 let select_array: Vec<DeriveDiesel> = derives::table
417 .select(derives::all_columns)
418 .load(&conn)
419 .unwrap();
420 let select_cache: Vec<Derive2Diesel> = derives::table
421 .select(derives::all_columns)
422 .load(&conn)
423 .unwrap();
424 assert_eq!(
425 select_cache
426 .into_iter()
427 .map(|d| d.name.to_string())
428 .collect::<Vec<_>>(),
429 select_array
430 .into_iter()
431 .map(|d| d.name.to_string())
432 .collect::<Vec<_>>()
433 );
434 let _: std::time::SystemTime = derives::table.select(dsl::now).first(&conn).unwrap();
435 let _: std::time::SystemTime = derives::table.select(dsl::now).first(&conn).unwrap();
436
437 let conn = mysql::MysqlConnection::establish("").unwrap();
438 let select_array: Vec<DeriveDiesel> = derives::table
439 .select(derives::all_columns)
440 .load(&conn)
441 .unwrap();
442 let select_cache: Vec<Derive2Diesel> = derives::table
443 .select(derives::all_columns)
444 .load(&conn)
445 .unwrap();
446 assert_eq!(
447 select_array
448 .into_iter()
449 .map(|d| d.name.to_string())
450 .collect::<Vec<_>>(),
451 select_cache
452 .into_iter()
453 .map(|d| d.name.to_string())
454 .collect::<Vec<_>>()
455 );
456 }
457
458 #[cfg(all(feature = "diesel-traits", feature = "std"))]
459 #[test]
460 fn diesel_derive_query_sqlite() {
461 let conn = diesel::sqlite::SqliteConnection::establish(":memory:").unwrap();
462 let _ = diesel::sql_query("CREATE TABLE derives (name VARCHAR(32));")
463 .execute(&conn)
464 .unwrap();
465 let string = DeriveDiesel {
466 name: ArrayString::try_from_str("Name1").unwrap(),
467 };
468
469 let _ = insert_into(derives::table)
470 .values(&string)
471 .execute(&conn)
472 .unwrap();
473
474 let queried: DeriveDiesel = derives::table.first(&conn).unwrap();
475 assert_eq!(queried.name.as_str(), "Name1");
476 }
477
478 #[cfg(all(feature = "diesel-traits", feature = "std"))]
479 #[test]
480 fn diesel_derive2_query_sqlite() {
481 let conn = diesel::sqlite::SqliteConnection::establish(":memory:").unwrap();
482 let _ = diesel::sql_query("CREATE TABLE derives (name VARCHAR(32));")
483 .execute(&conn)
484 .unwrap();
485 let string = Derive2Diesel {
486 name: CacheString(ArrayString::try_from_str("Name1").unwrap()),
487 };
488
489 let _ = insert_into(derives::table)
490 .values(&string)
491 .execute(&conn)
492 .unwrap();
493
494 let queried: Derive2Diesel = derives::table.first(&conn).unwrap();
495 assert_eq!(queried.name.as_str(), "Name1");
496 }
497 }