1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! Types and traits related to serializing values for the database
use Error;
use fmt;
use ;
use result;
use crateBackend;
use crateRawBytesBindCollector;
use crateBindCollector;
pub use crateWriteTuple;
/// A specialized result type representing the result of serializing
/// a value for the database.
pub type Result = Result;
/// Tiny enum to make the return type of `ToSql` more descriptive
/// Wraps a buffer to be written by `ToSql` with additional backend specific
/// utilities.
/// Serializes a single value to be sent to the database.
///
/// The output is sent as a bind parameter, and the data must be written in the
/// expected format for the given backend.
///
/// When possible, implementations of this trait should prefer using an existing
/// implementation, rather than writing to `out` directly. (For example, if you
/// are implementing this for an enum, which is represented as an integer in the
/// database, you should use `i32::to_sql(x, out)` instead of writing to `out`
/// yourself.)
///
/// Any types which implement this trait should also
/// [`#[derive(AsExpression)]`](derive@crate::expression::AsExpression).
///
/// ### Backend specific details
///
/// - For PostgreSQL, the bytes will be sent using the binary protocol, not text.
/// - For SQLite, all implementations should be written in terms of an existing
/// `ToSql` implementation.
/// - For MySQL, the expected bytes will depend on the return value of
/// `type_metadata` for the given SQL type. See [`MysqlType`] for details.
/// - For third party backends, consult that backend's documentation.
///
/// [`MysqlType`]: ../mysql/enum.MysqlType.html
///
/// ### Examples
///
/// Most implementations of this trait will be defined in terms of an existing
/// implementation.
///
/// ```rust
/// # use diesel::backend::Backend;
/// # use diesel::expression::AsExpression;
/// # use diesel::sql_types::*;
/// # use diesel::serialize::{self, ToSql, Output};
/// # use std::io::Write;
/// #
/// #[repr(i32)]
/// #[derive(Debug, Clone, Copy, AsExpression)]
/// #[diesel(sql_type = Integer)]
/// pub enum MyEnum {
/// A = 1,
/// B = 2,
/// }
///
/// impl<DB> ToSql<Integer, DB> for MyEnum
/// where
/// DB: Backend,
/// i32: ToSql<Integer, DB>,
/// {
/// fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
/// match self {
/// MyEnum::A => 1.to_sql(out),
/// MyEnum::B => 2.to_sql(out),
/// }
/// }
/// }
/// ```
///
/// Example of creating a custom type mapping based on a MySQL [enum type](https://dev.mysql.com/doc/refman/8.0/en/enum.html)
///
/// This is designed to reuse the SQL type definition generated by diesel-cli
///
/// ```rust
/// # use diesel::backend::Backend;
/// # use diesel::expression::AsExpression;
/// # use diesel::sql_types::*;
/// # use diesel::serialize::{self, ToSql, Output, IsNull};
/// # use std::io::Write;
/// #
/// pub mod sql_types {
/// #[derive(diesel::sql_types::SqlType)]
/// #[diesel(mysql_type(name = "Enum"))]
/// pub struct PostEnum; //<- generated by diesel cli
/// }
/// #[derive(Debug, AsExpression, PartialEq, Clone)]
/// #[diesel(sql_type = sql_types::PostEnum)]
/// pub enum Post {
/// FirstValue,
/// SecondValue,
/// }
///
/// # #[cfg(feature = "mysql")]
/// impl ToSql<sql_types::PostEnum, diesel::mysql::Mysql> for Post {
/// fn to_sql<'b>(
/// &'b self,
/// out: &mut Output<'b, '_, diesel::mysql::Mysql>,
/// ) -> serialize::Result {
/// match *self {
/// // these string values need to match the labels used in your
/// // enum definition in SQL. So this expects that you defined the
/// /// relevant enum type as`ENUM('one', 'two')` in your `CREATE TABLE` statement
/// Post::FirstValue => out.write_all(b"one")?,
/// Post::SecondValue => out.write_all(b"two")?,
/// }
/// Ok(IsNull::No)
/// }
/// }
/// ```
///
/// Using temporary values as part of the `ToSql` implementation requires additional
/// work.
///
/// Backends using [`RawBytesBindCollector`] as [`BindCollector`] copy the serialized values as part
/// of `Write` implementation. This includes the `Mysql` and the `Pg` backend provided by diesel.
/// This means existing `ToSql` implementations can be used even with
/// temporary values. For these it is required to call
/// [`Output::reborrow`] to shorten the lifetime of the `Output` type correspondingly.
///
/// ```
/// # use diesel::backend::Backend;
/// # use diesel::expression::AsExpression;
/// # use diesel::sql_types::*;
/// # use diesel::serialize::{self, ToSql, Output};
/// # use std::io::Write;
/// #
/// #[repr(i32)]
/// #[derive(Debug, Clone, Copy, AsExpression)]
/// #[diesel(sql_type = Integer)]
/// pub enum MyEnum {
/// A = 1,
/// B = 2,
/// }
///
/// # #[cfg(feature = "postgres")]
/// impl ToSql<Integer, diesel::pg::Pg> for MyEnum
/// where
/// i32: ToSql<Integer, diesel::pg::Pg>,
/// {
/// fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> serialize::Result {
/// let v = *self as i32;
/// <i32 as ToSql<Integer, diesel::pg::Pg>>::to_sql(&v, &mut out.reborrow())
/// }
/// }
/// ````
///
/// For any other backend the [`Output::set_value`] method provides a way to
/// set the output value directly. Checkout the documentation of the corresponding
/// `BindCollector::Buffer` type for provided `From<T>` implementations for a list
/// of accepted types. For the `Sqlite` backend see `SqliteBindValue`.
///
/// ```
/// # use diesel::backend::Backend;
/// # use diesel::expression::AsExpression;
/// # use diesel::sql_types::*;
/// # use diesel::serialize::{self, ToSql, Output, IsNull};
/// # use std::io::Write;
/// #
/// #[repr(i32)]
/// #[derive(Debug, Clone, Copy, AsExpression)]
/// #[diesel(sql_type = Integer)]
/// pub enum MyEnum {
/// A = 1,
/// B = 2,
/// }
///
/// # #[cfg(feature = "sqlite")]
/// impl ToSql<Integer, diesel::sqlite::Sqlite> for MyEnum
/// where
/// i32: ToSql<Integer, diesel::sqlite::Sqlite>,
/// {
/// fn to_sql<'b>(
/// &'b self,
/// out: &mut Output<'b, '_, diesel::sqlite::Sqlite>,
/// ) -> serialize::Result {
/// out.set_value(*self as i32);
/// Ok(IsNull::No)
/// }
/// }
/// ````