Skip to main content

rok_db_core/
cursor.rs

1use std::fmt;
2use std::str::FromStr;
3
4use crate::{Error, Value};
5
6/// An opaque position in a keyset-paginated result, returned by
7/// [`Select::cursor_paginate`](crate::Select::cursor_paginate).
8///
9/// A cursor holds the ordering values of the last row of a page. It
10/// round-trips through a compact, URL-safe string (`to_string()` /
11/// `parse()`), so it can be handed to API clients as a "next page" token.
12/// Treat the string as opaque: its format may change between minor versions.
13#[derive(Debug, Clone, PartialEq)]
14pub struct Cursor {
15    pub(crate) values: Vec<Value>,
16}
17
18impl Cursor {
19    /// A cursor positioned after a row with these ordering values (one per
20    /// `ORDER BY` column, in order, including the primary key tiebreaker).
21    pub fn new(values: impl IntoIterator<Item = Value>) -> Self {
22        Self {
23            values: values.into_iter().collect(),
24        }
25    }
26
27    /// The ordering values this cursor points after.
28    pub fn values(&self) -> &[Value] {
29        &self.values
30    }
31}
32
33/// One page of a keyset-paginated query.
34#[derive(Debug, Clone, PartialEq)]
35pub struct CursorPage<T> {
36    /// Records on this page.
37    pub items: Vec<T>,
38    /// Cursor for the following page, or `None` on the last page.
39    pub next: Option<Cursor>,
40}
41
42impl<T> CursorPage<T> {
43    /// `true` if a later page exists.
44    pub fn has_next(&self) -> bool {
45        self.next.is_some()
46    }
47
48    /// Transform every record, keeping the cursor.
49    pub fn map<U>(self, f: impl FnMut(T) -> U) -> CursorPage<U> {
50        CursorPage {
51            items: self.items.into_iter().map(f).collect(),
52            next: self.next,
53        }
54    }
55}
56
57impl<T> IntoIterator for CursorPage<T> {
58    type Item = T;
59    type IntoIter = std::vec::IntoIter<T>;
60
61    fn into_iter(self) -> Self::IntoIter {
62        self.items.into_iter()
63    }
64}
65
66// ----- encoding --------------------------------------------------------------
67//
68// `tag` + `~` (NULL) or `tag` + hex(payload), joined with `.`; every character
69// is URL-safe.
70
71fn hex(bytes: &[u8]) -> String {
72    bytes.iter().map(|b| format!("{b:02x}")).collect()
73}
74
75fn unhex(s: &str) -> Result<Vec<u8>, Error> {
76    if s.len() % 2 != 0 {
77        return Err(Error::InvalidCursor("odd hex length".into()));
78    }
79    (0..s.len())
80        .step_by(2)
81        .map(|i| {
82            u8::from_str_radix(&s[i..i + 2], 16)
83                .map_err(|_| Error::InvalidCursor("bad hex digit".into()))
84        })
85        .collect()
86}
87
88fn text(bytes: Vec<u8>) -> Result<String, Error> {
89    String::from_utf8(bytes).map_err(|_| Error::InvalidCursor("invalid utf-8".into()))
90}
91
92fn parse<T: FromStr>(bytes: Vec<u8>) -> Result<T, Error> {
93    text(bytes)?
94        .parse()
95        .map_err(|_| Error::InvalidCursor("malformed value".into()))
96}
97
98fn encode(value: &Value) -> String {
99    fn part<T>(tag: char, v: &Option<T>, f: impl FnOnce(&T) -> Vec<u8>) -> String {
100        match v {
101            Some(v) => format!("{tag}{}", hex(&f(v))),
102            None => format!("{tag}~"),
103        }
104    }
105    let s = |v: &dyn ToString| v.to_string().into_bytes();
106    match value {
107        Value::Bool(v) => part('b', v, |v| s(v)),
108        Value::I16(v) => part('h', v, |v| s(v)),
109        Value::I32(v) => part('i', v, |v| s(v)),
110        Value::I64(v) => part('l', v, |v| s(v)),
111        Value::F32(v) => part('f', v, |v| s(&v.to_bits())),
112        Value::F64(v) => part('d', v, |v| s(&v.to_bits())),
113        Value::String(v) => part('s', v, |v| v.as_bytes().to_vec()),
114        Value::Bytes(v) => part('y', v, |v| v.clone()),
115        #[cfg(feature = "uuid")]
116        Value::Uuid(v) => part('u', v, |v| s(v)),
117        #[cfg(feature = "chrono")]
118        Value::DateTime(v) => part('t', v, |v| v.to_rfc3339().into_bytes()),
119        #[cfg(feature = "chrono")]
120        Value::NaiveDateTime(v) => part('n', v, |v| s(v)),
121        #[cfg(feature = "chrono")]
122        Value::NaiveDate(v) => part('D', v, |v| s(v)),
123        #[cfg(feature = "chrono")]
124        Value::NaiveTime(v) => part('T', v, |v| s(v)),
125        #[cfg(feature = "json")]
126        Value::Json(v) => part('j', v, |v| s(v)),
127        // Custom types can't be decoded generically; `x` makes the cursor
128        // fail to parse with a clear error instead of misbehaving.
129        Value::Custom(v) => format!("x{}", hex(format!("{v:?}").as_bytes())),
130    }
131}
132
133fn decode(part: &str) -> Result<Value, Error> {
134    let mut chars = part.chars();
135    let tag = chars
136        .next()
137        .ok_or_else(|| Error::InvalidCursor("empty value".into()))?;
138    let rest = chars.as_str();
139    let payload = if rest == "~" {
140        None
141    } else {
142        Some(unhex(rest)?)
143    };
144    macro_rules! val {
145        ($variant:ident, |$b:ident| $conv:expr) => {
146            Value::$variant(match payload {
147                Some($b) => Some($conv),
148                None => None,
149            })
150        };
151    }
152    Ok(match tag {
153        'b' => val!(Bool, |b| parse(b)?),
154        'h' => val!(I16, |b| parse(b)?),
155        'i' => val!(I32, |b| parse(b)?),
156        'l' => val!(I64, |b| parse(b)?),
157        'f' => val!(F32, |b| f32::from_bits(parse(b)?)),
158        'd' => val!(F64, |b| f64::from_bits(parse(b)?)),
159        's' => val!(String, |b| text(b)?),
160        'y' => val!(Bytes, |b| b),
161        #[cfg(feature = "uuid")]
162        'u' => val!(Uuid, |b| parse(b)?),
163        #[cfg(feature = "chrono")]
164        't' => val!(DateTime, |b| {
165            sqlx::types::chrono::DateTime::parse_from_rfc3339(&text(b)?)
166                .map_err(|_| Error::InvalidCursor("malformed timestamp".into()))?
167                .with_timezone(&sqlx::types::chrono::Utc)
168        }),
169        #[cfg(feature = "chrono")]
170        'n' => val!(NaiveDateTime, |b| parse(b)?),
171        #[cfg(feature = "chrono")]
172        'D' => val!(NaiveDate, |b| parse(b)?),
173        #[cfg(feature = "chrono")]
174        'T' => val!(NaiveTime, |b| parse(b)?),
175        #[cfg(feature = "json")]
176        'j' => val!(Json, |b| serde_json::from_slice(&b)
177            .map_err(|_| Error::InvalidCursor("malformed json".into()))?),
178        'x' => {
179            return Err(Error::InvalidCursor(
180                "custom column types can't be used as keyset pagination columns".into(),
181            ));
182        }
183        other => return Err(Error::InvalidCursor(format!("unknown type tag `{other}`"))),
184    })
185}
186
187impl fmt::Display for Cursor {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        let parts: Vec<String> = self.values.iter().map(encode).collect();
190        f.write_str(&parts.join("."))
191    }
192}
193
194impl FromStr for Cursor {
195    type Err = Error;
196
197    fn from_str(s: &str) -> Result<Self, Error> {
198        if s.is_empty() {
199            return Err(Error::InvalidCursor("empty cursor".into()));
200        }
201        Ok(Self {
202            values: s.split('.').map(decode).collect::<Result<_, _>>()?,
203        })
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn round_trips() {
213        let cursor = Cursor::new([
214            Value::from(42_i64),
215            Value::from("a.b~c/é"),
216            Value::from(None::<i32>),
217            Value::from(-1.5_f64),
218            Value::from(true),
219            Value::from(vec![0_u8, 255]),
220        ]);
221        let encoded = cursor.to_string();
222        assert!(
223            encoded
224                .chars()
225                .all(|c| c.is_ascii_alphanumeric() || ".~".contains(c)),
226            "{encoded}"
227        );
228        assert_eq!(encoded.parse::<Cursor>().unwrap(), cursor);
229    }
230
231    #[test]
232    fn rejects_garbage() {
233        for bad in ["", "x12", "lzz", "l1", "s~.q"] {
234            assert!(bad.parse::<Cursor>().is_err(), "{bad}");
235        }
236    }
237}