diesel/sql_types/
mod.rs

1//! Types which represent a SQL data type.
2//!
3//! The structs in this module are *only* used as markers to represent a SQL type.
4//! They should never be used in your structs.
5//! If you'd like to know the rust types which can be used for a given SQL type,
6//! see the documentation for that SQL type.
7//! Additional types may be provided by other crates.
8//!
9//! To see which SQL type can be used with a given Rust type,
10//! see the "Implementors" section of [`FromSql`].
11//!
12//! [`FromSql`]: ../deserialize/trait.FromSql.html
13//!
14//! Any backend specific types are re-exported through this module
15
16mod fold;
17pub mod ops;
18mod ord;
19
20pub use self::fold::Foldable;
21pub use self::ord::SqlOrd;
22
23/// The boolean SQL type.
24///
25/// On backends without a native boolean type,
26/// this is emulated with the smallest supported integer.
27///
28/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
29///
30/// - [`bool`][bool]
31///
32/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
33///
34/// - [`bool`][bool]
35///
36/// [bool]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
37#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
38#[cfg_attr(feature = "postgres", postgres(oid = "16", array_oid = "1000"))]
39#[cfg_attr(feature = "sqlite", sqlite_type = "Integer")]
40#[cfg_attr(feature = "mysql", mysql_type = "Tiny")]
41pub struct Bool;
42
43/// The tiny integer SQL type.
44///
45/// This is only available on MySQL.
46/// Keep in mind that `infer_schema!` will see `TINYINT(1)` as `Bool`,
47/// not `TinyInt`.
48///
49/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
50///
51/// - [`i8`][i8]
52///
53/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
54///
55/// - [`i8`][i8]
56///
57/// [i8]: https://doc.rust-lang.org/nightly/std/primitive.i8.html
58#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
59#[cfg_attr(feature = "mysql", mysql_type = "Tiny")]
60pub struct TinyInt;
61#[doc(hidden)]
62pub type Tinyint = TinyInt;
63
64/// The small integer SQL type.
65///
66/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
67///
68/// - [`i16`][i16]
69///
70/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
71///
72/// - [`i16`][i16]
73///
74/// [i16]: https://doc.rust-lang.org/nightly/std/primitive.i16.html
75#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
76#[cfg_attr(feature = "postgres", postgres(oid = "21", array_oid = "1005"))]
77#[cfg_attr(feature = "sqlite", sqlite_type = "SmallInt")]
78#[cfg_attr(feature = "mysql", mysql_type = "Short")]
79pub struct SmallInt;
80#[doc(hidden)]
81pub type Int2 = SmallInt;
82#[doc(hidden)]
83pub type Smallint = SmallInt;
84
85/// The integer SQL type.
86///
87/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
88///
89/// - [`i32`][i32]
90///
91/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
92///
93/// - [`i32`][i32]
94///
95/// [i32]: https://doc.rust-lang.org/nightly/std/primitive.i32.html
96#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
97#[cfg_attr(feature = "postgres", postgres(oid = "23", array_oid = "1007"))]
98#[cfg_attr(feature = "sqlite", sqlite_type = "Integer")]
99#[cfg_attr(feature = "mysql", mysql_type = "Long")]
100pub struct Integer;
101#[doc(hidden)]
102pub type Int4 = Integer;
103
104/// The big integer SQL type.
105///
106/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
107///
108/// - [`i64`][i64]
109///
110/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
111///
112/// - [`i64`][i64]
113///
114/// [i64]: https://doc.rust-lang.org/nightly/std/primitive.i64.html
115#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
116#[cfg_attr(feature = "postgres", postgres(oid = "20", array_oid = "1016"))]
117#[cfg_attr(feature = "sqlite", sqlite_type = "Long")]
118#[cfg_attr(feature = "mysql", mysql_type = "LongLong")]
119pub struct BigInt;
120#[doc(hidden)]
121pub type Int8 = BigInt;
122#[doc(hidden)]
123pub type Bigint = BigInt;
124
125/// The float SQL type.
126///
127/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
128///
129/// - [`f32`][f32]
130///
131/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
132///
133/// - [`f32`][f32]
134///
135/// [f32]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
136#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
137#[cfg_attr(feature = "postgres", postgres(oid = "700", array_oid = "1021"))]
138#[cfg_attr(feature = "sqlite", sqlite_type = "Float")]
139#[cfg_attr(feature = "mysql", mysql_type = "Float")]
140pub struct Float;
141#[doc(hidden)]
142pub type Float4 = Float;
143
144/// The double precision float SQL type.
145///
146/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
147///
148/// - [`f64`][f64]
149///
150/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
151///
152/// - [`f64`][f64]
153///
154/// [f64]: https://doc.rust-lang.org/nightly/std/primitive.f64.html
155#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
156#[cfg_attr(feature = "postgres", postgres(oid = "701", array_oid = "1022"))]
157#[cfg_attr(feature = "sqlite", sqlite_type = "Double")]
158#[cfg_attr(feature = "mysql", mysql_type = "Double")]
159pub struct Double;
160#[doc(hidden)]
161pub type Float8 = Double;
162
163/// The arbitrary precision numeric SQL type.
164///
165/// This type is only supported on PostgreSQL and MySQL.
166/// On SQLite, [`Double`](struct.Double.html) should be used instead.
167///
168/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
169///
170/// - [`bigdecimal::BigDecimal`] with `feature = ["numeric"]`
171///
172/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
173///
174/// - [`bigdecimal::BigDecimal`] with `feature = ["numeric"]`
175///
176/// [`bigdecimal::BigDecimal`]: /bigdecimal/struct.BigDecimal.html
177#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
178#[cfg_attr(feature = "postgres", postgres(oid = "1700", array_oid = "1231"))]
179#[cfg_attr(feature = "mysql", mysql_type = "String")]
180#[cfg_attr(feature = "sqlite", sqlite_type = "Double")]
181pub struct Numeric;
182
183/// Alias for `Numeric`
184pub type Decimal = Numeric;
185
186/// The text SQL type.
187///
188/// On all backends strings must be valid UTF-8.
189/// On PostgreSQL strings must not include nul bytes.
190///
191/// Schema inference will treat all variants of `TEXT` as this type (e.g.
192/// `VARCHAR`, `MEDIUMTEXT`, etc).
193///
194/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
195///
196/// - [`String`][String]
197/// - [`&str`][str]
198///
199/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
200///
201/// - [`String`][String]
202///
203/// [String]: https://doc.rust-lang.org/nightly/std/string/struct.String.html
204/// [str]: https://doc.rust-lang.org/nightly/std/primitive.str.html
205#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
206#[cfg_attr(feature = "postgres", postgres(oid = "25", array_oid = "1009"))]
207#[cfg_attr(feature = "sqlite", sqlite_type = "Text")]
208#[cfg_attr(feature = "mysql", mysql_type = "String")]
209pub struct Text;
210
211/// The SQL `VARCHAR` type
212///
213/// This type is generally interchangeable with `TEXT`, so Diesel has this as an
214/// alias rather than a separate type (Diesel does not currently support
215/// implicit coercions).
216///
217/// One notable exception to this is with arrays on PG. `TEXT[]` cannot be
218/// coerced to `VARCHAR[]`.  It is recommended that you always use `TEXT[]` if
219/// you need a string array on PG.
220pub type VarChar = Text;
221#[doc(hidden)]
222pub type Varchar = VarChar;
223#[doc(hidden)]
224pub type Char = Text;
225#[doc(hidden)]
226pub type Tinytext = Text;
227#[doc(hidden)]
228pub type Mediumtext = Text;
229#[doc(hidden)]
230pub type Longtext = Text;
231
232/// The binary SQL type.
233///
234/// Schema inference will treat all variants of `BLOB` as this type (e.g.
235/// `VARBINARY`, `MEDIUMBLOB`, etc).
236///
237/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
238///
239/// - [`Vec<u8>`][Vec]
240/// - [`&[u8]`][slice]
241///
242/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
243///
244/// - [`Vec<u8>`][Vec]
245///
246/// [Vec]: https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html
247/// [slice]: https://doc.rust-lang.org/nightly/std/primitive.slice.html
248#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
249#[cfg_attr(feature = "postgres", postgres(oid = "17", array_oid = "1001"))]
250#[cfg_attr(feature = "sqlite", sqlite_type = "Binary")]
251#[cfg_attr(feature = "mysql", mysql_type = "Blob")]
252pub struct Binary;
253
254#[doc(hidden)]
255pub type Tinyblob = Binary;
256#[doc(hidden)]
257pub type Blob = Binary;
258#[doc(hidden)]
259pub type Mediumblob = Binary;
260#[doc(hidden)]
261pub type Longblob = Binary;
262#[doc(hidden)]
263pub type Varbinary = Binary;
264#[doc(hidden)]
265pub type Bit = Binary;
266
267/// The date SQL type.
268///
269/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
270///
271/// - [`chrono::NaiveDate`][NaiveDate] with `feature = "chrono"`
272///
273/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
274///
275/// - [`chrono::NaiveDate`][NaiveDate] with `feature = "chrono"`
276///
277/// [NaiveDate]: /chrono/naive/date/struct.NaiveDate.html
278#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
279#[cfg_attr(feature = "postgres", postgres(oid = "1082", array_oid = "1182"))]
280#[cfg_attr(feature = "sqlite", sqlite_type = "Text")]
281#[cfg_attr(feature = "mysql", mysql_type = "Date")]
282pub struct Date;
283
284/// The interval SQL type.
285///
286/// This type is currently only implemented for PostgreSQL.
287///
288/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
289///
290/// - [`PgInterval`] which can be constructed using [`IntervalDsl`]
291///
292/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
293///
294/// - [`PgInterval`] which can be constructed using [`IntervalDsl`]
295///
296/// [`PgInterval`]: ../pg/data_types/struct.PgInterval.html
297/// [`IntervalDsl`]: ../pg/expression/extensions/trait.IntervalDsl.html
298#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
299#[cfg_attr(feature = "postgres", postgres(oid = "1186", array_oid = "1187"))]
300pub struct Interval;
301
302/// The time SQL type.
303///
304/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
305///
306/// - [`chrono::NaiveTime`][NaiveTime] with `feature = "chrono"`
307///
308/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
309///
310/// - [`chrono::NaiveTime`][NaiveTime] with `feature = "chrono"`
311///
312/// [NaiveTime]: /chrono/naive/time/struct.NaiveTime.html
313#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
314#[cfg_attr(feature = "postgres", postgres(oid = "1083", array_oid = "1183"))]
315#[cfg_attr(feature = "sqlite", sqlite_type = "Text")]
316#[cfg_attr(feature = "mysql", mysql_type = "Time")]
317pub struct Time;
318
319/// The timestamp SQL type.
320///
321/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
322///
323/// - [`std::time::SystemTime`][SystemTime] (PG only)
324/// - [`chrono::NaiveDateTime`][NaiveDateTime] with `feature = "chrono"`
325/// - [`time::Timespec`][Timespec] with `feature = "deprecated-time"` (PG only)
326///
327/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
328///
329/// - [`std::time::SystemTime`][SystemTime] (PG only)
330/// - [`chrono::NaiveDateTime`][NaiveDateTime] with `feature = "chrono"`
331/// - [`time::Timespec`][Timespec] with `feature = "deprecated-time"` (PG only)
332///
333/// [SystemTime]: https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html
334/// [NaiveDateTime]: /chrono/naive/datetime/struct.NaiveDateTime.html
335/// [Timespec]: /time/struct.Timespec.html
336#[derive(Debug, Clone, Copy, Default, QueryId, SqlType)]
337#[cfg_attr(feature = "postgres", postgres(oid = "1114", array_oid = "1115"))]
338#[cfg_attr(feature = "sqlite", sqlite_type = "Text")]
339#[cfg_attr(feature = "mysql", mysql_type = "Timestamp")]
340pub struct Timestamp;
341
342/// The nullable SQL type.
343///
344/// This wraps another SQL type to indicate that it can be null.
345/// By default all values are assumed to be `NOT NULL`.
346///
347/// ### [`ToSql`](../serialize/trait.ToSql.html) impls
348///
349/// - Any `T` which implements `ToSql<ST>`
350/// - `Option<T>` for any `T` which implements `ToSql<ST>`
351///
352/// ### [`FromSql`](../deserialize/trait.FromSql.html) impls
353///
354/// - `Option<T>` for any `T` which implements `FromSql<ST>`
355#[derive(Debug, Clone, Copy, Default)]
356pub struct Nullable<ST: NotNull>(ST);
357
358#[cfg(feature = "postgres")]
359pub use pg::types::sql_types::*;
360
361#[cfg(feature = "mysql")]
362pub use mysql::types::*;
363
364/// Indicates that a SQL type exists for a backend.
365///
366/// # Deriving
367///
368/// This trait can be automatically derived by `#[derive(SqlType)]`.
369/// This derive will also implement [`NotNull`] and [`SingleValue`].
370/// When deriving this trait,
371/// you need to specify how the type is represented on various backends.
372/// You don't need to specify every backend,
373/// only the ones supported by your type.
374///
375/// For PostgreSQL, add `#[postgres(oid = "some_oid", array_oid = "some_oid")]`
376/// or `#[postgres(type_name = "pg_type_name")]` if the OID is not stable.
377/// For MySQL, specify which variant of [`MysqlType`] should be used
378/// by adding `#[mysql_type = "Variant"]`.
379/// For SQLite, specify which variant of [`SqliteType`] should be used
380/// by adding `#[sqlite_type = "Variant"]`.
381///
382/// [`NotNull`]: trait.NotNull.html
383/// [`SingleValue`]: trait.SingleValue.html
384/// [`MysqlType`]: ../mysql/enum.MysqlType.html
385/// [`SqliteType`]: ../sqlite/enum.SqliteType.html
386///
387/// # Example
388///
389/// ```rust
390/// # #[macro_use]
391/// # extern crate diesel;
392/// #[derive(SqlType)]
393/// #[postgres(oid = "23", array_oid = "1007")]
394/// #[sqlite_type = "Integer"]
395/// #[mysql_type = "Long"]
396/// pub struct Integer;
397/// # fn main() {}
398/// ```
399pub trait HasSqlType<ST>: TypeMetadata {
400    /// Fetch the metadata for the given type
401    ///
402    /// This method may use `lookup` to do dynamic runtime lookup. Implementors
403    /// of this method should not do dynamic lookup unless absolutely necessary
404    fn metadata(lookup: &Self::MetadataLookup) -> Self::TypeMetadata;
405
406    #[doc(hidden)]
407    #[cfg(feature = "with-deprecated")]
408    #[deprecated(
409        since = "1.4.0",
410        note = "This method is no longer used, and has been deprecated without replacement"
411    )]
412    fn row_metadata(out: &mut Vec<Self::TypeMetadata>, lookup: &Self::MetadataLookup) {
413        out.push(Self::metadata(lookup))
414    }
415
416    #[doc(hidden)]
417    #[cfg(feature = "mysql")]
418    fn is_signed() -> IsSigned {
419        IsSigned::Signed
420    }
421
422    #[doc(hidden)]
423    #[cfg(feature = "mysql")]
424    fn mysql_metadata(lookup: &Self::MetadataLookup) -> (Self::TypeMetadata, IsSigned) {
425        (Self::metadata(lookup), Self::is_signed())
426    }
427
428    #[doc(hidden)]
429    #[cfg(feature = "mysql")]
430    fn mysql_row_metadata(
431        out: &mut Vec<(Self::TypeMetadata, IsSigned)>,
432        lookup: &Self::MetadataLookup,
433    ) {
434        out.push(Self::mysql_metadata(lookup))
435    }
436}
437
438#[doc(hidden)]
439#[cfg(feature = "mysql")]
440#[derive(Debug, Clone, Copy)]
441pub enum IsSigned {
442    Signed,
443    Unsigned,
444}
445
446/// Information about how a backend stores metadata about given SQL types
447pub trait TypeMetadata {
448    /// The actual type used to represent metadata.
449    ///
450    /// On PostgreSQL, this is the type's OID.
451    /// On MySQL and SQLite, this is an enum representing all storage classes
452    /// they support.
453    type TypeMetadata;
454    /// The type used for runtime lookup of metadata.
455    ///
456    /// For most backends, which don't support user defined types, this will
457    /// be `()`.
458    type MetadataLookup;
459}
460
461/// A marker trait indicating that a SQL type is not null.
462///
463/// All SQL types must implement this trait.
464///
465/// # Deriving
466///
467/// This trait is automatically implemented by `#[derive(SqlType)]`
468pub trait NotNull {}
469
470/// Converts a type which may or may not be nullable into its nullable
471/// representation.
472pub trait IntoNullable {
473    /// The nullable representation of this type.
474    ///
475    /// For all types except `Nullable`, this will be `Nullable<Self>`.
476    type Nullable;
477}
478
479impl<T: NotNull> IntoNullable for T {
480    type Nullable = Nullable<T>;
481}
482
483impl<T: NotNull> IntoNullable for Nullable<T> {
484    type Nullable = Nullable<T>;
485}
486
487/// A marker trait indicating that a SQL type represents a single value, as
488/// opposed to a list of values.
489///
490/// This trait should generally be implemented for all SQL types with the
491/// exception of Rust tuples. If a column could have this as its type, this
492/// trait should be implemented.
493///
494/// # Deriving
495///
496/// This trait is automatically implemented by `#[derive(SqlType)]`
497pub trait SingleValue {}
498
499impl<T: NotNull + SingleValue> SingleValue for Nullable<T> {}