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
fn ty<R, T>(range: &R) -> crate::pq::Type
where
    R: std::ops::RangeBounds<T>,
    T: crate::ToSql,
{
    use crate::pq::types::*;
    use std::ops::Bound::*;

    let start = match range.start_bound() {
        Included(start) | Excluded(start) => start,
        Unbounded => panic!("Unsupported unbounded range"),
    };

    match start.ty() {
        ANY => ANY_RANGE,
        INT4 => INT4_RANGE,
        INT8 => INT8_RANGE,
        NUMERIC => NUM_RANGE,
        TIMESTAMP => TS_RANGE,
        TIMESTAMPTZ => TSTZ_RANGE,
        DATE => DATE_RANGE,
        _ => UNKNOWN,
    }
}

fn to_sql<R, T>(range: &R) -> crate::Result<Option<Vec<u8>>>
where
    R: std::ops::RangeBounds<T>,
    T: crate::ToSql,
{
    use std::ops::Bound::*;

    let (start_char, start) = match range.start_bound() {
        Included(start) => (b'[', start),
        Excluded(start) => (b'(', start),
        Unbounded => panic!("Unsupported unbounded range"),
    };

    let mut start = start.to_sql()?.unwrap();
    start.pop(); // removes \0

    let (end_char, end) = match range.end_bound() {
        Included(end) => (b']', end),
        Excluded(end) => (b')', end),
        Unbounded => panic!("Unsupported unbounded range"),
    };

    let mut end = end.to_sql()?.unwrap();
    end.pop(); // removes \0

    let mut vec = Vec::new();
    vec.push(start_char);
    vec.append(&mut start);
    vec.push(b',');
    vec.append(&mut end);
    vec.push(end_char);
    vec.push(b'\0');

    Ok(Some(vec))
}

impl<T: crate::ToSql> crate::ToSql for std::ops::Range<T> {
    fn ty(&self) -> crate::pq::Type {
        ty(self)
    }

    fn to_sql(&self) -> crate::Result<Option<Vec<u8>>> {
        to_sql(self)
    }
}

impl<T: crate::FromSql> crate::FromSql for std::ops::Range<T> {
    fn from_text(
        ty: &crate::pq::Type,
        raw: Option<&str>,
    ) -> crate::Result<Self> {
        let regex =
            regex::Regex::new(r"[\[\(](?P<start>.?*),(?P<end>.?*)[\]\)]")
                .unwrap();

        let matches = regex.captures(crate::not_null(raw)?).unwrap();

        // tstzrange are quoted
        let start =
            matches.name("start").map(|x| x.as_str().trim_matches('\"'));
        let end = matches.name("end").map(|x| x.as_str().trim_matches('\"'));

        Ok(std::ops::Range {
            start: T::from_text(ty, start)?,
            end: T::from_text(ty, end)?,
        })
    }

    /*
     * https://github.com/postgres/postgres/blob/REL_12_0/src/backend/utils/adt/rangetypes.c#L246
     */
    fn from_binary(
        ty: &crate::pq::Type,
        raw: Option<&[u8]>,
    ) -> crate::Result<Self> {
        use byteorder::ReadBytesExt;

        let mut buf = crate::from_sql::not_null(raw)?;
        let _flag = buf.read_u8()?;

        let start_bound_len = buf.read_i32::<byteorder::BigEndian>()?;
        let mut start = Vec::new();
        for _ in 0..start_bound_len {
            let b = buf.read_u8()?;

            start.push(b);
        }

        let end_bound_len = buf.read_i32::<byteorder::BigEndian>()?;
        let mut end = Vec::new();
        for _ in 0..end_bound_len {
            let b = buf.read_u8()?;

            end.push(b);
        }

        Ok(std::ops::Range {
            start: T::from_binary(ty, Some(&start))?,
            end: T::from_binary(ty, Some(&end))?,
        })
    }
}

impl<T: crate::ToSql> crate::ToSql for std::ops::RangeInclusive<T> {
    fn ty(&self) -> crate::pq::Type {
        ty(self)
    }

    fn to_sql(&self) -> crate::Result<Option<Vec<u8>>> {
        to_sql(self)
    }
}

#[cfg(test)]
mod test {
    crate::sql_test!(int4range, std::ops::Range<i32>, [(
        "'[0, 10)'",
        0_i32..10
    )]);

    crate::sql_test!(int8range, std::ops::Range<i64>, [(
        "'[0, 10)'",
        0_i64..10
    )]);

    #[cfg(feature = "numeric")]
    crate::sql_test!(numrange, std::ops::Range<bigdecimal::BigDecimal>, [(
        "'[3900, 20000)'",
        bigdecimal::BigDecimal::from(3_900)
            ..bigdecimal::BigDecimal::from(20_000)
    )]);

    #[cfg(feature = "date")]
    crate::sql_test!(daterange, std::ops::Range<chrono::NaiveDate>, [(
        "'[1970-01-01, 2010-01-01)'",
        chrono::NaiveDate::from_ymd(1970, 01, 01)
            ..chrono::NaiveDate::from_ymd(2010, 01, 01)
    )]);

    #[cfg(feature = "date")]
    crate::sql_test!(tsrange, std::ops::Range<chrono::NaiveDateTime>, [(
        "'[1970-01-01 00:00:00, 2010-01-01 00:00:00)'",
        chrono::NaiveDate::from_ymd(1970, 01, 01).and_hms(0, 0, 0)
            ..chrono::NaiveDate::from_ymd(2010, 01, 01).and_hms(0, 0, 0)
    )]);

    #[cfg(feature = "date")]
    crate::sql_test!(
        tstzrange,
        std::ops::Range<chrono::DateTime<chrono::offset::Utc>>,
        [(
            "'[1970-01-01 00:00:00+00, 2010-01-01 00:00:00+00)'",
            chrono::DateTime::<chrono::offset::Utc>::from_utc(
                chrono::NaiveDate::from_ymd(1970, 01, 01).and_hms(0, 0, 0),
                chrono::offset::Utc
            )
                ..chrono::DateTime::<chrono::offset::Utc>::from_utc(
                    chrono::NaiveDate::from_ymd(2010, 01, 01).and_hms(0, 0, 0),
                    chrono::offset::Utc
                )
        )]
    );
}