sqll 0.13.3

Efficient interface to SQLite that doesn't get in your way
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use core::borrow::Borrow;
use core::cmp::Ordering;
use core::fmt::{self, Write};
use core::hash::{Hash, Hasher};
use core::str::Utf8Error;

/// A SQLite text value.
///
/// One of the types in a SQLite database is a text type, internally these can
/// have two opaque representations. UTF-8 and UTF-16 (of various endianesses).
/// This library only interacts with the UTF-8 portion of the library.
///
/// Rust strings demand that all text is valid and well-formed UTF-8. SQLite
/// despite calling what it returns as UTF-8 it doesn't validate that the data
/// it stores is well-formed. To put it in other terms, garbage in is garbage
/// out. For a more detailed overview see the [Invalid UTF Policy].
///
/// Since we want a thing wrapper on top of SQLite, that leaves us with having
/// to treat all text values as potentially malformed UTF-8, which is where this
/// wrapper type comes in. It provides some basic text-like functionality
/// similar to the [`bstr` crate] which makes your life a little easier. Such as
/// safely printing the value.
///
/// A type loaded as [`Text`] doesn't validate that the underlying bytes are
/// valid or well-formed UTF-8, but provide some access to the literal
/// underlying data and convenience method for performing the text validation
/// locally such as [`Text::to_str`].
///
/// For cases where you prefer to do this validation up front, we do provide
/// [`FromColumn`] implementations for string-like types where you can opt in to
/// eagerly perform the validation.
///
/// Reading the UTF policy carefully also leads you to the realization that all
/// SQLite APIs which might mix in user-provided text can produce malformed
/// UTF-8. Like [`Connection::error_message`]. Meaning even if we didn't want to
/// support lossless text values, we would still want to treat these values
/// carefully.
///
/// [`FromColumn`]: crate::FromColumn
/// [Invalid UTF Policy]: <https://www.sqlite.org/invalidutf.html>
/// [`Connection::error_message`]: crate::Connection::error_message
///
/// # Examples
///
/// ```
/// use sqll::{Code, Connection, Text};
///
/// let mut c = Connection::open_in_memory()?;
///
/// c.execute(r#"
///     CREATE TABLE example (data TEXT);
/// "#)?;
///
/// let mut insert = c.prepare("INSERT INTO example (data) VALUES (?)")?;
/// insert.execute(Text::new(b"invalid: \xF0\x90\x80\xF0\x90\x80"))?;
/// insert.execute(Text::new(b"valid: \xe2\x9d\xa4\xef\xb8\x8f"))?;
///
/// let mut stmt = c.prepare("SELECT data FROM example")?;
/// let e = stmt.next::<&str>().unwrap_err();
/// assert_eq!(e.code(), Code::MISMATCH);
///
/// stmt.reset()?;
///
/// let text = stmt.next::<&Text>()?.expect("expected value");
/// assert_eq!(text.as_bytes(), b"invalid: \xF0\x90\x80\xF0\x90\x80");
/// assert_eq!(text.to_string(), "invalid: ��");
///
/// let text = stmt.next::<&Text>()?.expect("expected value");
/// assert_eq!(text.as_bytes(), b"valid: \xe2\x9d\xa4\xef\xb8\x8f");
/// assert_eq!(text.to_str()?, "valid: ❤️");
/// # Ok::<_, Box<dyn core::error::Error>>(())
/// ```
#[repr(transparent)]
pub struct Text {
    bytes: [u8],
}

impl Text {
    /// Create a new `Text` from the given type coerced into a byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Text;
    ///
    /// let a = Text::new(b"hello");
    /// assert_eq!(a, "hello");
    /// ```
    pub fn new<T>(bytes: &T) -> &Self
    where
        T: ?Sized + AsRef<[u8]>,
    {
        Self::from_bytes(bytes.as_ref())
    }

    /// Create a new `Text` from the given byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Text;
    ///
    /// let t = Text::from_bytes(b"example");
    /// assert_eq!(t, "example");
    /// ```
    pub const fn from_bytes(bytes: &[u8]) -> &Self {
        // SAFETY: Text is #[repr(transparent)] over [u8].
        unsafe { &*(bytes as *const [u8] as *const Text) }
    }

    /// Get the underlying byte slice for this `Text`.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Text;
    ///
    /// let t = Text::new(b"example");
    /// assert_eq!(t.as_bytes(), b"example");
    /// ```
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Attempt to convert this `Text` into a UTF-8 string slice.
    ///
    /// Returns an error if the underlying bytes are not valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqll::Text;
    ///
    /// let t = Text::new(b"example");
    /// assert_eq!(t.to_str()?, "example");
    ///
    /// let invalid = Text::new(b"\xF0\x90\x80");
    /// assert!(invalid.to_str().is_err());
    /// # Ok::<_, core::str::Utf8Error>(())
    /// ```
    #[inline]
    pub fn to_str(&self) -> Result<&str, Utf8Error> {
        str::from_utf8(&self.bytes)
    }
}

/// Compare the text for equality with another `Text`. This performs a byte-wise
/// comparison.
///
/// # Examples
///
/// ```
/// use sqll::Text;
///
/// let t1 = Text::new(b"example");
/// let t2 = Text::new(b"example");
/// let t3 = Text::new(b"different");
///
/// assert_eq!(t1, t2);
/// assert_ne!(t1, t3);
/// ```
impl PartialEq for Text {
    #[inline]
    fn eq(&self, other: &Text) -> bool {
        self.bytes == other.bytes
    }
}

/// Texts are equal if their bytes are equal.
///
/// # Examples
///
/// ```
/// use sqll::Text;
///
/// let t1 = Text::new(b"example");
/// let t2 = Text::new(b"example");
///
/// assert!(t1 == t2);
/// ```
impl Eq for Text {}

/// Texts are ordered by their byte sequences.
///
/// # Examples
///
/// ```
/// use sqll::Text;
///
/// let t1 = Text::new(b"apple");
/// let t2 = Text::new(b"banana");
///
/// assert!(t1 < t2);
/// ```
impl PartialOrd for Text {
    #[inline]
    fn partial_cmp(&self, other: &Text) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Compare for ordering.
///
/// # Examples
///
/// ```
/// use sqll::Text;
/// use std::collections::BTreeSet;
///
/// let a = Text::new("Apple");
/// let b = Text::new("Banana");
///
/// let mut set = BTreeSet::from([a, b]);
///
/// let c = Text::new("Banana");
/// assert!(set.contains(&c));
/// assert!(!set.insert(c));
/// ```
impl Ord for Text {
    #[inline]
    fn cmp(&self, other: &Text) -> Ordering {
        self.bytes.cmp(&other.bytes)
    }
}

/// Hash the text based on its byte sequence.
///
/// # Examples
///
/// ```
/// use sqll::Text;
/// use std::collections::hash_map::DefaultHasher;
/// use std::hash::{Hash, Hasher};
///
/// let t1 = Text::new(b"example");
/// let t2 = Text::new(b"example");
///
/// let mut hasher1 = DefaultHasher::new();
/// let mut hasher2 = DefaultHasher::new();
///
/// t1.hash(&mut hasher1);
/// t2.hash(&mut hasher2);
///
/// assert_eq!(hasher1.finish(), hasher2.finish());
/// ```
///
/// Inserting into a has set:
///
/// ```
/// use sqll::Text;
/// use std::collections::HashSet;
///
/// let a = Text::new("Apple");
/// let b = Text::new("Banana");
///
/// let mut set = HashSet::from([a, b]);
///
/// let c = Text::new("Banana");
/// assert!(set.contains(&c));
/// assert!(!set.insert(c));
/// ```
impl Hash for Text {
    #[inline]
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.bytes.hash(state);
    }
}

/// Allow borrowing the underlying byte slice.
///
/// # Examples
///
/// ```
/// use sqll::Text;
/// use core::borrow::Borrow;
///
/// let t = Text::new(b"example");
/// let b: &[u8] = t.borrow();
/// assert_eq!(b, b"example");
/// ```
impl Borrow<[u8]> for Text {
    #[inline]
    fn borrow(&self) -> &[u8] {
        &self.bytes
    }
}

/// Allow getting a reference to self.
///
/// # Examples
///
/// ```
/// use sqll::Text;
///
/// let t = Text::new(b"example");
/// let t_ref: &Text = t.as_ref();
/// assert_eq!(t_ref, t);
/// ```
impl AsRef<Text> for Text {
    #[inline]
    fn as_ref(&self) -> &Text {
        self
    }
}

/// Allow getting a a string as a [`Text`] reference.
///
/// # Examples
///
/// ```
/// use sqll::Text;
///
/// let t = "example";
/// let t_ref: &Text = t.as_ref();
/// assert_eq!(t_ref, t);
/// ```
impl AsRef<Text> for str {
    #[inline]
    fn as_ref(&self) -> &Text {
        Text::new(self)
    }
}

/// Allow getting a reference to the underlying byte slice.
///
/// # Examples
///
/// ```
/// use sqll::Text;
///
/// let t = Text::new(b"example");
/// let b: &[u8] = t.as_ref();
/// assert_eq!(b, b"example");
/// ```
impl AsRef<[u8]> for Text {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.bytes
    }
}

/// Compare the text for equality with a `str`.
///
/// This performs a byte-wise comparison.
///
/// # Examples
///
/// ```
/// use sqll::Text;
/// let t = Text::new(b"example");
///
/// assert_eq!(t, "example");
/// assert_ne!(t, "different");
/// ```
impl PartialEq<str> for Text {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        &self.bytes == other.as_bytes()
    }
}

/// The display implementation for `Text` will convert it into a UTF-8 string
/// lossily, replacing invalid sequences with the replacement character `�`.
///
/// # Examples
///
/// ```
/// use sqll::Text;
///
/// let text = Text::new(b"before\xF0\x90\x80after");
/// assert_eq!(text.to_string(), "before�after");
///
/// let text = Text::new(b"before\xF0\x90\x80\xF0\x90\x80");
/// assert_eq!(text.to_string(), "before��");
/// ```
impl fmt::Display for Text {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for chunk in self.bytes.utf8_chunks() {
            f.write_str(chunk.valid())?;

            if !chunk.invalid().is_empty() {
                f.write_char('\u{FFFD}')?;
            }
        }

        Ok(())
    }
}

/// The debug implementation for `Text` will output a string literal style
/// representation of the text, escaping invalid UTF-8 bytes as `\xNN` escapes.
///
/// # Examples
///
/// ```
/// use sqll::Text;
///
/// assert_eq! {
///     format!("{:?}", Text::new(b"Hello, \xF0\x90\x80World!")),
///     "\"Hello, \\xF0\\x90\\x80World!\"",
/// };
/// ```
impl fmt::Debug for Text {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"")?;

        for chunk in self.bytes.utf8_chunks() {
            for c in chunk.valid().chars() {
                for c in c.escape_debug() {
                    f.write_char(c)?;
                }
            }

            for b in chunk.invalid() {
                write!(f, "\\x{:02X}", b)?;
            }
        }

        write!(f, "\"")?;
        Ok(())
    }
}