sqlx_core/from_row.rs
1use crate::{error::Error, row::Row};
2
3/// A record that can be built from a row returned by the database.
4///
5/// In order to use [`query_as`](crate::query_as) the output type must implement `FromRow`.
6///
7/// ## Derivable
8///
9/// This trait can be derived by SQLx for any struct. The generated implementation
10/// will consist of a sequence of calls to [`Row::try_get`] using the name from each
11/// struct field.
12///
13/// ```rust,ignore
14/// #[derive(sqlx::FromRow)]
15/// struct User {
16/// id: i32,
17/// name: String,
18/// }
19/// ```
20///
21/// ### Field attributes
22///
23/// Several attributes can be specified to customize how each column in a row is read:
24///
25/// #### `rename`
26///
27/// When the name of a field in Rust does not match the name of its corresponding column,
28/// you can use the `rename` attribute to specify the name that the field has in the row.
29/// For example:
30///
31/// ```rust,ignore
32/// #[derive(sqlx::FromRow)]
33/// struct User {
34/// id: i32,
35/// name: String,
36/// #[sqlx(rename = "description")]
37/// about_me: String
38/// }
39/// ```
40///
41/// Given a query such as:
42///
43/// ```sql
44/// SELECT id, name, description FROM users;
45/// ```
46///
47/// will read the content of the column `description` into the field `about_me`.
48///
49/// #### `rename_all`
50/// By default, field names are expected verbatim (with the exception of the raw identifier prefix `r#`, if present).
51/// Placed at the struct level, this attribute changes how the field name is mapped to its SQL column name:
52///
53/// ```rust,ignore
54/// #[derive(sqlx::FromRow)]
55/// #[sqlx(rename_all = "camelCase")]
56/// struct UserPost {
57/// id: i32,
58/// // remapped to "userId"
59/// user_id: i32,
60/// contents: String
61/// }
62/// ```
63///
64/// The supported values are `snake_case` (available if you have non-snake-case field names for some
65/// reason), `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`, `SCREAMING_SNAKE_CASE` and `kebab-case`.
66/// The styling of each option is intended to be an example of its behavior.
67///
68/// #### `default`
69///
70/// When your struct contains a field that is not present in your query,
71/// if the field type has an implementation for [`Default`],
72/// you can use the `default` attribute to assign the default value to said field.
73/// For example:
74///
75/// ```rust,ignore
76/// #[derive(sqlx::FromRow)]
77/// struct User {
78/// id: i32,
79/// name: String,
80/// #[sqlx(default)]
81/// location: Option<String>
82/// }
83/// ```
84///
85/// Given a query such as:
86///
87/// ```sql
88/// SELECT id, name FROM users;
89/// ```
90///
91/// will set the value of the field `location` to the default value of `Option<String>`,
92/// which is `None`.
93///
94/// Moreover, if the struct has an implementation for [`Default`], you can use the `default`
95/// attribute at the struct level rather than for each single field. If a field does not appear in the result,
96/// its value is taken from the `Default` implementation for the struct.
97/// For example:
98///
99/// ```rust, ignore
100/// #[derive(Default, sqlx::FromRow)]
101/// #[sqlx(default)]
102/// struct Options {
103/// option_a: Option<i32>,
104/// option_b: Option<String>,
105/// option_c: Option<bool>,
106/// }
107/// ```
108///
109/// For a derived `Default` implementation this effectively populates each missing field
110/// with `Default::default()`, but a manual `Default` implementation can provide
111/// different placeholder values, if applicable.
112///
113/// This is similar to how `#[serde(default)]` behaves.
114///
115/// #### `flatten`
116///
117/// If you want to handle a field that implements [`FromRow`],
118/// you can use the `flatten` attribute to specify that you want
119/// it to use [`FromRow`] for parsing rather than the usual method.
120/// For example:
121///
122/// ```rust,ignore
123/// #[derive(sqlx::FromRow)]
124/// struct Address {
125/// country: String,
126/// city: String,
127/// road: String,
128/// }
129///
130/// #[derive(sqlx::FromRow)]
131/// struct User {
132/// id: i32,
133/// name: String,
134/// #[sqlx(flatten)]
135/// address: Address,
136/// }
137/// ```
138/// Given a query such as:
139///
140/// ```sql
141/// SELECT id, name, country, city, road FROM users;
142/// ```
143///
144/// This field is compatible with the `default` attribute.
145///
146/// #### `skip`
147///
148/// This is a variant of the `default` attribute which instead always takes the value from
149/// the `Default` implementation for this field type ignoring any results in your query.
150/// This can be useful, if some field does not satifisfy the trait bounds (i.e.
151/// `sqlx::decode::Decode`, `sqlx::type::Type`), in particular in case of nested structures.
152/// For example:
153///
154/// ```rust,ignore
155/// #[derive(sqlx::FromRow)]
156/// struct Address {
157/// user_name: String,
158/// street: String,
159/// city: String,
160/// }
161///
162/// #[derive(sqlx::FromRow)]
163/// struct User {
164/// name: String,
165/// #[sqlx(skip)]
166/// addresses: Vec<Address>,
167/// }
168/// ```
169///
170/// Then when querying into `User`, only `name` needs to be set:
171///
172/// ```rust,ignore
173/// let user: User = sqlx::query_as("SELECT name FROM users")
174/// .fetch_one(&mut some_connection)
175/// .await?;
176///
177/// // `Default` for `Vec<Address>` is an empty vector.
178/// assert!(user.addresses.is_empty());
179/// ```
180///
181/// #### `try_from`
182///
183/// When your struct contains a field whose type is not matched with the database type,
184/// if the field type has an implementation [`TryFrom`] for the database type,
185/// you can use the `try_from` attribute to convert the database type to the field type.
186/// For example:
187///
188/// ```rust,ignore
189/// #[derive(sqlx::FromRow)]
190/// struct User {
191/// id: i32,
192/// name: String,
193/// #[sqlx(try_from = "i64")]
194/// bigIntInMySql: u64
195/// }
196/// ```
197///
198/// Given a query such as:
199///
200/// ```sql
201/// SELECT id, name, bigIntInMySql FROM users;
202/// ```
203///
204/// In MySql, `BigInt` type matches `i64`, but you can convert it to `u64` by `try_from`.
205///
206/// #### `json`
207///
208/// If your database supports a JSON type, you can leverage `#[sqlx(json)]`
209/// to automatically integrate JSON deserialization in your [`FromRow`] implementation using [`serde`](https://docs.rs/serde/latest/serde/).
210///
211/// ```rust,ignore
212/// #[derive(serde::Deserialize)]
213/// struct Data {
214/// field1: String,
215/// field2: u64
216/// }
217///
218/// #[derive(sqlx::FromRow)]
219/// struct User {
220/// id: i32,
221/// name: String,
222/// #[sqlx(json)]
223/// metadata: Data
224/// }
225/// ```
226///
227/// Given a query like the following:
228///
229/// ```sql
230/// SELECT
231/// 1 AS id,
232/// 'Name' AS name,
233/// JSON_OBJECT('field1', 'value1', 'field2', 42) AS metadata
234/// ```
235///
236/// The `metadata` field will be deserialized used its `serde::Deserialize` implementation:
237///
238/// ```rust,ignore
239/// User {
240/// id: 1,
241/// name: "Name",
242/// metadata: Data {
243/// field1: "value1",
244/// field2: 42
245/// }
246/// }
247/// ```
248///
249/// By default the `#[sqlx(json)]` attribute will assume that the underlying database row is
250/// _not_ NULL. This can cause issues when your field type is an `Option<T>` because this would be
251/// represented as the _not_ NULL (in terms of DB) JSON value of `null`.
252///
253/// If you wish to describe a database row which _is_ NULLable but _cannot_ contain the JSON value `null`,
254/// use the `#[sqlx(json(nullable))]` attrubute.
255///
256/// For example
257/// ```rust,ignore
258/// #[derive(serde::Deserialize)]
259/// struct Data {
260/// field1: String,
261/// field2: u64
262/// }
263///
264/// #[derive(sqlx::FromRow)]
265/// struct User {
266/// id: i32,
267/// name: String,
268/// #[sqlx(json(nullable))]
269/// metadata: Option<Data>
270/// }
271/// ```
272/// Would describe a database field which _is_ NULLable but if it exists it must be the JSON representation of `Data`
273/// and cannot be the JSON value `null`
274///
275/// ## Manual implementation
276///
277/// You can also implement the [`FromRow`] trait by hand. This can be useful if you
278/// have a struct with a field that needs manual decoding:
279///
280///
281/// ```rust,ignore
282/// use sqlx::{FromRow, sqlite::SqliteRow, sqlx::Row};
283/// struct MyCustomType {
284/// custom: String,
285/// }
286///
287/// struct Foo {
288/// bar: MyCustomType,
289/// }
290///
291/// impl FromRow<'_, SqliteRow> for Foo {
292/// fn from_row(row: &SqliteRow) -> sqlx::Result<Self> {
293/// Ok(Self {
294/// bar: MyCustomType {
295/// custom: row.try_get("custom")?
296/// }
297/// })
298/// }
299/// }
300/// ```
301pub trait FromRow<'r, R: Row>: Sized {
302 fn from_row(row: &'r R) -> Result<Self, Error>;
303}
304
305impl<'r, R> FromRow<'r, R> for ()
306where
307 R: Row,
308{
309 #[inline]
310 fn from_row(_: &'r R) -> Result<Self, Error> {
311 Ok(())
312 }
313}
314
315// implement FromRow for tuples of types that implement Decode
316// up to tuples of 16 values
317
318macro_rules! impl_from_row_for_tuple {
319 ($( ($idx:tt) -> $T:ident );+;) => {
320 impl<'r, R, $($T,)+> FromRow<'r, R> for ($($T,)+)
321 where
322 R: Row,
323 usize: crate::column::ColumnIndex<R>,
324 $($T: crate::decode::Decode<'r, R::Database> + crate::types::Type<R::Database>,)+
325 {
326 #[inline]
327 fn from_row(row: &'r R) -> Result<Self, Error> {
328 Ok(($(row.try_get($idx as usize)?,)+))
329 }
330 }
331 };
332}
333
334impl_from_row_for_tuple!(
335 (0) -> T1;
336);
337
338impl_from_row_for_tuple!(
339 (0) -> T1;
340 (1) -> T2;
341);
342
343impl_from_row_for_tuple!(
344 (0) -> T1;
345 (1) -> T2;
346 (2) -> T3;
347);
348
349impl_from_row_for_tuple!(
350 (0) -> T1;
351 (1) -> T2;
352 (2) -> T3;
353 (3) -> T4;
354);
355
356impl_from_row_for_tuple!(
357 (0) -> T1;
358 (1) -> T2;
359 (2) -> T3;
360 (3) -> T4;
361 (4) -> T5;
362);
363
364impl_from_row_for_tuple!(
365 (0) -> T1;
366 (1) -> T2;
367 (2) -> T3;
368 (3) -> T4;
369 (4) -> T5;
370 (5) -> T6;
371);
372
373impl_from_row_for_tuple!(
374 (0) -> T1;
375 (1) -> T2;
376 (2) -> T3;
377 (3) -> T4;
378 (4) -> T5;
379 (5) -> T6;
380 (6) -> T7;
381);
382
383impl_from_row_for_tuple!(
384 (0) -> T1;
385 (1) -> T2;
386 (2) -> T3;
387 (3) -> T4;
388 (4) -> T5;
389 (5) -> T6;
390 (6) -> T7;
391 (7) -> T8;
392);
393
394impl_from_row_for_tuple!(
395 (0) -> T1;
396 (1) -> T2;
397 (2) -> T3;
398 (3) -> T4;
399 (4) -> T5;
400 (5) -> T6;
401 (6) -> T7;
402 (7) -> T8;
403 (8) -> T9;
404);
405
406impl_from_row_for_tuple!(
407 (0) -> T1;
408 (1) -> T2;
409 (2) -> T3;
410 (3) -> T4;
411 (4) -> T5;
412 (5) -> T6;
413 (6) -> T7;
414 (7) -> T8;
415 (8) -> T9;
416 (9) -> T10;
417);
418
419impl_from_row_for_tuple!(
420 (0) -> T1;
421 (1) -> T2;
422 (2) -> T3;
423 (3) -> T4;
424 (4) -> T5;
425 (5) -> T6;
426 (6) -> T7;
427 (7) -> T8;
428 (8) -> T9;
429 (9) -> T10;
430 (10) -> T11;
431);
432
433impl_from_row_for_tuple!(
434 (0) -> T1;
435 (1) -> T2;
436 (2) -> T3;
437 (3) -> T4;
438 (4) -> T5;
439 (5) -> T6;
440 (6) -> T7;
441 (7) -> T8;
442 (8) -> T9;
443 (9) -> T10;
444 (10) -> T11;
445 (11) -> T12;
446);
447
448impl_from_row_for_tuple!(
449 (0) -> T1;
450 (1) -> T2;
451 (2) -> T3;
452 (3) -> T4;
453 (4) -> T5;
454 (5) -> T6;
455 (6) -> T7;
456 (7) -> T8;
457 (8) -> T9;
458 (9) -> T10;
459 (10) -> T11;
460 (11) -> T12;
461 (12) -> T13;
462);
463
464impl_from_row_for_tuple!(
465 (0) -> T1;
466 (1) -> T2;
467 (2) -> T3;
468 (3) -> T4;
469 (4) -> T5;
470 (5) -> T6;
471 (6) -> T7;
472 (7) -> T8;
473 (8) -> T9;
474 (9) -> T10;
475 (10) -> T11;
476 (11) -> T12;
477 (12) -> T13;
478 (13) -> T14;
479);
480
481impl_from_row_for_tuple!(
482 (0) -> T1;
483 (1) -> T2;
484 (2) -> T3;
485 (3) -> T4;
486 (4) -> T5;
487 (5) -> T6;
488 (6) -> T7;
489 (7) -> T8;
490 (8) -> T9;
491 (9) -> T10;
492 (10) -> T11;
493 (11) -> T12;
494 (12) -> T13;
495 (13) -> T14;
496 (14) -> T15;
497);
498
499impl_from_row_for_tuple!(
500 (0) -> T1;
501 (1) -> T2;
502 (2) -> T3;
503 (3) -> T4;
504 (4) -> T5;
505 (5) -> T6;
506 (6) -> T7;
507 (7) -> T8;
508 (8) -> T9;
509 (9) -> T10;
510 (10) -> T11;
511 (11) -> T12;
512 (12) -> T13;
513 (13) -> T14;
514 (14) -> T15;
515 (15) -> T16;
516);