Skip to content

Commit f758917

Browse files
OriolMunozmehcode
authored andcommitted
FromRow derivation docs
1 parent 92cddc7 commit f758917

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

sqlx-core/src/from_row.rs

+52
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,58 @@ use crate::row::Row;
1919
/// }
2020
/// ```
2121
///
22+
/// Several attributes can be specified to customize how each column in a row is read:
23+
///
24+
/// ### rename
25+
///
26+
/// When the name of a field in Rust does not match the name of its corresponding column,
27+
/// you can use the `rename` attribute to specify the name that the field has in the row.
28+
/// For example:
29+
///
30+
/// ```rust,ignore
31+
/// #[derive(sqlx::FromRow)]
32+
/// struct User {
33+
/// id: i32,
34+
/// name: String,
35+
/// #[sqlx(rename = "description")]
36+
/// about_me: String
37+
/// }
38+
/// ```
39+
///
40+
/// Given a query such as:
41+
///
42+
/// ```sql
43+
/// SELECT id, name, description FROM users;
44+
/// ```
45+
///
46+
/// will read the content of the column `description` into the field `about_me`.
47+
///
48+
/// ### default
49+
///
50+
/// When your struct contains a field that is not present in your query,
51+
/// if the field type has an implementation for [`Default`],
52+
/// you can use the `default` attribute to assign the default value to said field.
53+
/// For example:
54+
///
55+
/// ```rust,ignore
56+
/// #[derive(sqlx::FromRow)]
57+
/// struct User {
58+
/// id: i32,
59+
/// name: String,
60+
/// #[sqlx(default)]
61+
/// location: Option<String>
62+
/// }
63+
/// ```
64+
///
65+
/// Given a query such as:
66+
///
67+
/// ```sql
68+
/// SELECT id, name FROM users;
69+
/// ```
70+
///
71+
/// will set the value of the field `location` to the default value of `Option<String>,
72+
/// which is `None`.
73+
///
2274
/// [`query_as`]: crate::query_as
2375
/// [`Row::try_get`]: crate::row::Row::try_get
2476
pub trait FromRow<'r, R: Row>: Sized {

0 commit comments

Comments
 (0)