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
/*!
Defines the [`FromSql`] trait and implements it for standard Rust types
and for [`NotNan`], so that they can be parsed from SQL syntax.
*/

use bstr::B;
use either::Either;
use nom::{
    branch::alt,
    bytes::streaming::{escaped_transform, is_not, tag},
    character::streaming::{char, digit1, one_of},
    combinator::{map, map_res, opt, recognize},
    error::context,
    number::streaming::recognize_float,
    sequence::{preceded, terminated, tuple},
};
use ordered_float::NotNan;

pub type IResult<'a, T> = nom::IResult<&'a [u8], T, crate::error::Error<'a>>;

/**
Trait for converting from the SQL syntax for a simple type
(anything other than a tuple) to a Rust type,
which can borrow from the string or not.
Used by [`schemas::FromSqlTuple`][crate::FromSqlTuple].
*/
pub trait FromSql<'a>: Sized {
    fn from_sql(s: &'a [u8]) -> IResult<'a, Self>;
}

/// Parses a [`bool`] from `1` or `0`.
impl<'a> FromSql<'a> for bool {
    fn from_sql(s: &'a [u8]) -> IResult<'a, Self> {
        context("1 or 0", map(one_of("01"), |b| b == '1'))(s)
    }
}

// This won't panic if the SQL file is valid and the parser is using
// the correct numeric types.
macro_rules! number_impl {
    (
        $( #[doc = $com:expr] )*
        $type_name:ty
        $implementation:block
    ) => {
        $( #[doc = $com] )*
        impl<'a> FromSql<'a> for $type_name {
            fn from_sql(s: &'a [u8]) -> IResult<'a, $type_name> {
                context(
                    concat!("number (", stringify!($type_name), ")"),
                    map_res($implementation, |num: &[u8]| {
                        let s = std::str::from_utf8(num).map_err(Either::Right)?;
                        s.parse().map_err(Either::Left)
                    }),
                )(s)
            }
        }
    };
    (
        $( #[doc = $com:expr] )*
        $type_name:ty
        $implementation:block
        $further_processing:block
    ) => {
        $( #[doc = $com] )*
        impl<'a> FromSql<'a> for $type_name {
            fn from_sql(s: &'a [u8]) -> IResult<'a, $type_name> {
                context(
                    concat!("number (", stringify!($type_name), ")"),
                    map($implementation, $further_processing),
                )(s)
            }
        }
    };
}

macro_rules! unsigned_int {
    ($t:ident) => {
        number_impl! { $t { recognize(digit1) } }
    };
}

unsigned_int!(u8);
unsigned_int!(u16);
unsigned_int!(u32);
unsigned_int!(u64);

macro_rules! signed_int {
    ($t:ident) => {
        number_impl! { $t { recognize(tuple((opt(char('-')), digit1))) } }
    };
}

signed_int!(i8);
signed_int!(i16);
signed_int!(i32);
signed_int!(i64);

macro_rules! float {
    ($t:ident) => {
        number_impl! {
            #[doc = concat!("Matches a float literal with [`recognize_float`] and parses it as a [`", stringify!($t), "`].")]
            $t { recognize_float }
        }

        number_impl! {
            // Link to `<$t as FromSql>::from_sql` when https://github.com/rust-lang/rust/issues/74563 is resolved.
            #[doc = concat!("Parses an [`", stringify!($t), "`] and wraps it with [`NotNan::unchecked_new`].")]
            ///
            /// # Safety
            /// This will never accidentally wrap a `NaN` because `nom`'s [`recognize_float`] doesn't include a representation of `NaN`.
            NotNan<$t> {
                <$t>::from_sql
            } {
                |float| unsafe { NotNan::unchecked_new(float) }
            }
        }
    };
}

float!(f32);
float!(f64);

/// Used for byte strings that have no escape sequences.
impl<'a> FromSql<'a> for &'a [u8] {
    fn from_sql(s: &'a [u8]) -> IResult<'a, Self> {
        context(
            "byte string with no escape sequences",
            preceded(
                tag("'"),
                terminated(
                    map(opt(is_not(B("'"))), |opt| opt.unwrap_or_else(|| B(""))),
                    tag("'"),
                ),
            ),
        )(s)
    }
}

/// Used for types represented as strings without escape sequences. For instance,
/// [`Timestamp`](crate::field_types::Timestamp)s matches the regex `^[0-9: -]+$`
/// and thus never has any escape sequences.
impl<'a> FromSql<'a> for &'a str {
    fn from_sql(s: &'a [u8]) -> IResult<'a, Self> {
        context(
            "string with no escape sequences",
            map_res(<&[u8]>::from_sql, |bytes| std::str::from_utf8(bytes)),
        )(s)
    }
}

/// Use this for string types that require unescaping and are guaranteed
/// to be valid UTF-8, like page titles.
impl<'a> FromSql<'a> for String {
    fn from_sql(s: &'a [u8]) -> IResult<'a, Self> {
        context(
            "string",
            map_res(<Vec<u8>>::from_sql, String::from_utf8),
        )(s)
    }
}

/// Used for "strings" that sometimes contain invalid UTF-8, like the
/// `cl_sortkey` field in the `categorylinks` table, which is truncated to 230
/// bits, sometimes in the middle of a UTF-8 sequence.
impl<'a> FromSql<'a> for Vec<u8> {
    fn from_sql(s: &'a [u8]) -> IResult<'a, Self> {
        context(
            "byte string",
            preceded(
                tag("'"),
                terminated(
                    map(
                        opt(escaped_transform(
                            is_not(B("\\\"'")),
                            '\\',
                            map(one_of(B(r#"0btnrZ\'""#)), |b| match b {
                                '0' => B("\0"),
                                'b' => b"\x08",
                                't' => b"\t",
                                'n' => b"\n",
                                'r' => b"\r",
                                'Z' => b"\x1A",
                                '\\' => b"\\",
                                '\'' => b"'",
                                '"' => b"\"",
                                _ => unreachable!(),
                            }),
                        )),
                        |opt| opt.unwrap_or_else(Vec::new),
                    ),
                    tag("'"),
                ),
            ),
        )(s)
    }
}

impl<'a> FromSql<'a> for () {
    fn from_sql(s: &'a [u8]) -> IResult<'a, Self> {
        context("unit type", map(tag("NULL"), |_| ()))(s)
    }
}

impl<'a, T> FromSql<'a> for Option<T>
where
    T: FromSql<'a>,
{
    fn from_sql(s: &'a [u8]) -> IResult<'a, Self> {
        context(
            "optional type",
            alt((
                context("“NULL”", map(<()>::from_sql, |_| None)),
                map(T::from_sql, Some),
            )),
        )(s)
    }
}