drizzle-core 0.2.0

A type-safe SQL query builder for Rust
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Shared `FromDrizzleRow` machinery for SQLite-flavored driver rows.
//!
//! `rusqlite::Row`, `libsql::Row`, and `turso::Row` all expose a single
//! per-cell fetch that returns a tagged union of integer / real / text /
//! blob / null. The leaf `FromDrizzleRow` impls for each driver were
//! near-clones of the same match-on-variant pattern, differing only in how
//! the fetch is spelled.
//!
//! This module captures that pattern as the [`SqliteValueRow`] trait. Each
//! driver supplies one tiny adapter that normalizes its native cell into a
//! [`SqliteCell`]; the leaf [`FromDrizzleRow`] impls for every Rust target
//! type (`i64`, `f64`, `String`, `Vec<u8>`, `bool`, `uuid::Uuid`, chrono /
//! serde types, `Option<T>`) live here once as blanket impls keyed on
//! `R: SqliteValueRow`.
//!
//! ## NULL probes
//!
//! `Option<T>::from_row_at` only needs to know whether a cell is NULL — it
//! shouldn't pay the cost of materialising a large `Text`/`Blob` value into
//! an owned [`SqliteCell`] just to throw it away. The trait therefore
//! exposes a dedicated [`SqliteValueRow::is_null_at`] method with a
//! `cell_at`-based default impl. Drivers that can probe NULL without
//! allocating (e.g. `rusqlite::Row::get_ref`) override it.

use crate::error::DrizzleError;
use crate::row::FromDrizzleRow;

/// SQLite-flavored cell value. The union of the four storage classes plus NULL,
/// matching what `libsql::Value` and `turso::Value` already expose.
#[derive(Debug, Clone)]
pub enum SqliteCell {
    Null,
    Integer(i64),
    Real(f64),
    Text(String),
    Blob(Vec<u8>),
}

impl SqliteCell {
    #[inline]
    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }
}

/// Implemented by SQLite-flavored row types whose cells live in a tagged
/// union (`rusqlite::ValueRef`, `libsql::Value`, `turso::Value`). Drivers
/// normalize one cell into a [`SqliteCell`]; the shared blanket impls below
/// take care of every target type.
pub trait SqliteValueRow {
    /// Fetch the column at `offset` and normalize it into a [`SqliteCell`].
    /// Errors should reflect driver-side I/O / range failures — `Ok(Null)`
    /// is the standard "NULL was here" outcome, not an error.
    fn cell_at(&self, offset: usize) -> Result<SqliteCell, DrizzleError>;

    /// Return `true` if the column at `offset` is NULL.
    ///
    /// The default implementation materialises the cell and inspects its
    /// tag. Drivers that can probe NULL without allocating (e.g.
    /// `rusqlite::Row::get_ref`) should override this — the `Option<T>`
    /// blanket calls `is_null_at` on every fetch, so avoiding the
    /// materialisation matters for large `Text` / `Blob` columns.
    #[inline]
    fn is_null_at(&self, offset: usize) -> Result<bool, DrizzleError> {
        Ok(self.cell_at(offset)?.is_null())
    }
}

// =============================================================================
// Integer types
// =============================================================================

/// Produce the IEEE 754 `f64` representation of an `i64`, matching `i as f64`
/// semantics without using a precision-losing `as` cast.
///
/// Splits `i` into a sign-extended high `i32` half and an unsigned low `u32`
/// half, both converted via the exact [`From`] trait, then recombines with a
/// `2^32` multiply. The result is identical to `i as f64` for all `i64`
/// inputs (inexact beyond `|i| > 2^53` in the same way the direct cast is).
#[inline]
fn i64_to_f64(i: i64) -> f64 {
    let high = i32::try_from(i >> 32).expect("sign-extended high word fits in i32");
    let low = u32::try_from(i & 0xFFFF_FFFF).expect("masked low word fits in u32");
    f64::from(high) * 4_294_967_296.0_f64 + f64::from(low)
}

macro_rules! sqlite_value_int_impl {
    ($($ty:ty),*) => { $(
        impl<R: SqliteValueRow> FromDrizzleRow<R> for $ty {
            const COLUMN_COUNT: usize = 1;
            fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
                match row.cell_at(offset)? {
                    SqliteCell::Integer(i) => i.try_into().map_err(
                        |e: core::num::TryFromIntError| {
                            DrizzleError::ConversionError(e.to_string().into())
                        },
                    ),
                    SqliteCell::Null => Err(DrizzleError::ConversionError(
                        "unexpected NULL for integer".into(),
                    )),
                    _ => Err(DrizzleError::ConversionError(
                        "expected integer value".into(),
                    )),
                }
            }
        }
    )* }
}

sqlite_value_int_impl!(i8, i16, i32, isize, u8, u16, u32, u64, usize);

// `i64` is the identity conversion — skip the `try_into` indirection so the
// fast path doesn't even mention `TryFromIntError`.
impl<R: SqliteValueRow> FromDrizzleRow<R> for i64 {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        match row.cell_at(offset)? {
            SqliteCell::Integer(i) => Ok(i),
            SqliteCell::Null => Err(DrizzleError::ConversionError(
                "unexpected NULL for integer".into(),
            )),
            _ => Err(DrizzleError::ConversionError(
                "expected integer value".into(),
            )),
        }
    }
}

// =============================================================================
// Float types
// =============================================================================

impl<R: SqliteValueRow> FromDrizzleRow<R> for f64 {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        match row.cell_at(offset)? {
            SqliteCell::Real(r) => Ok(r),
            // SQLite's NUMERIC affinity allows an integer to come back from a
            // column declared REAL; preserve the existing libsql behavior of
            // accepting that and round-tripping via the exact `i64_to_f64`
            // helper. (turso used a decimal-string parse for the same idea —
            // this is the more correct path.)
            SqliteCell::Integer(i) => Ok(i64_to_f64(i)),
            SqliteCell::Null => Err(DrizzleError::ConversionError(
                "unexpected NULL for float".into(),
            )),
            _ => Err(DrizzleError::ConversionError("expected real value".into())),
        }
    }
}

impl<R: SqliteValueRow> FromDrizzleRow<R> for f32 {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let v = f64::from_row_at(row, offset)?;
        // Decimal-string round-trip matches IEEE-754 round-to-nearest
        // semantics and avoids the lossy `as` cast.
        let f: Self = format!("{v}")
            .parse()
            .map_err(|e: core::num::ParseFloatError| {
                DrizzleError::ConversionError(e.to_string().into())
            })?;
        if v.is_finite() && !f.is_finite() {
            return Err(DrizzleError::ConversionError(
                format!("f64 value {v} overflows f32").into(),
            ));
        }
        Ok(f)
    }
}

// =============================================================================
// Bool, String, Vec<u8>
// =============================================================================

impl<R: SqliteValueRow> FromDrizzleRow<R> for bool {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        match row.cell_at(offset)? {
            SqliteCell::Integer(i) => Ok(i != 0),
            SqliteCell::Null => Err(DrizzleError::ConversionError(
                "unexpected NULL for bool".into(),
            )),
            _ => Err(DrizzleError::ConversionError(
                "expected integer for bool".into(),
            )),
        }
    }
}

impl<R: SqliteValueRow> FromDrizzleRow<R> for String {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        match row.cell_at(offset)? {
            SqliteCell::Text(s) => Ok(s),
            SqliteCell::Null => Err(DrizzleError::ConversionError(
                "unexpected NULL for string".into(),
            )),
            _ => Err(DrizzleError::ConversionError("expected text value".into())),
        }
    }
}

impl<R: SqliteValueRow> FromDrizzleRow<R> for Vec<u8> {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        match row.cell_at(offset)? {
            SqliteCell::Blob(b) => Ok(b),
            SqliteCell::Null => Err(DrizzleError::ConversionError(
                "unexpected NULL for blob".into(),
            )),
            _ => Err(DrizzleError::ConversionError("expected blob value".into())),
        }
    }
}

// =============================================================================
// Option<T>: NULL-aware wrapper
// =============================================================================

impl<R: SqliteValueRow, T> FromDrizzleRow<R> for Option<T>
where
    T: FromDrizzleRow<R>,
{
    const COLUMN_COUNT: usize = T::COLUMN_COUNT;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        if row.is_null_at(offset)? {
            Ok(None)
        } else {
            T::from_row_at(row, offset).map(Some)
        }
    }
}

// =============================================================================
// Feature-gated types
// =============================================================================

#[cfg(feature = "uuid")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for uuid::Uuid {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        match row.cell_at(offset)? {
            SqliteCell::Text(s) => Self::parse_str(&s).map_err(Into::into),
            SqliteCell::Blob(b) => Self::from_slice(&b)
                .map_err(|e| DrizzleError::ConversionError(e.to_string().into())),
            _ => Err(DrizzleError::ConversionError(
                "expected TEXT or BLOB for UUID".into(),
            )),
        }
    }
}

#[cfg(feature = "chrono")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for chrono::NaiveDate {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        s.parse()
            .map_err(|e: chrono::ParseError| DrizzleError::ConversionError(e.to_string().into()))
    }
}

#[cfg(feature = "chrono")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for chrono::NaiveTime {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        s.parse()
            .map_err(|e: chrono::ParseError| DrizzleError::ConversionError(e.to_string().into()))
    }
}

#[cfg(feature = "chrono")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for chrono::NaiveDateTime {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        s.parse()
            .map_err(|e: chrono::ParseError| DrizzleError::ConversionError(e.to_string().into()))
    }
}

#[cfg(feature = "chrono")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for chrono::DateTime<chrono::Utc> {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        // The SQLite conversion writes RFC 3339; text without an offset (as
        // SQLite's own `CURRENT_TIMESTAMP` writes) is UTC.
        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&s) {
            return Ok(dt.with_timezone(&chrono::Utc));
        }
        let ndt: chrono::NaiveDateTime = s
            .parse()
            .map_err(|e: chrono::ParseError| DrizzleError::ConversionError(e.to_string().into()))?;
        Ok(Self::from_naive_utc_and_offset(ndt, chrono::Utc))
    }
}

/// Parsers for the text `time` values are stored as.
///
/// Each accepts what the SQLite conversions write and the forms SQLite's own
/// date and time functions produce (`HH:MM:SS`, a space between date and time,
/// no offset for UTC).
#[cfg(feature = "time")]
mod time_text {
    use time::format_description::well_known::{Iso8601, Rfc3339};
    use time::macros::format_description;

    /// `HH:MM:SS[.fraction]`. Versions before 0.2.0 wrote ISO 8601's `T`
    /// prefix, which is accepted too.
    pub(crate) fn time(text: &str) -> Result<time::Time, time::error::Parse> {
        let text = text.strip_prefix('T').unwrap_or(text);
        time::Time::parse(
            text,
            format_description!("[hour]:[minute]:[second].[subsecond]"),
        )
        .or_else(|_| time::Time::parse(text, format_description!("[hour]:[minute]:[second]")))
    }

    /// ISO 8601, or SQLite's `YYYY-MM-DD HH:MM:SS[.fraction]`.
    pub(crate) fn primitive(text: &str) -> Result<time::PrimitiveDateTime, time::error::Parse> {
        time::PrimitiveDateTime::parse(text, &Iso8601::DATE_TIME)
            .or_else(|_| {
                time::PrimitiveDateTime::parse(
                    text,
                    format_description!(
                        "[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"
                    ),
                )
            })
            .or_else(|_| {
                time::PrimitiveDateTime::parse(
                    text,
                    format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"),
                )
            })
    }

    /// RFC 3339, or a date and time without an offset, which is UTC.
    pub(crate) fn offset(text: &str) -> Result<time::OffsetDateTime, time::error::Parse> {
        time::OffsetDateTime::parse(text, &Rfc3339).or_else(|error| {
            primitive(text)
                .map(time::PrimitiveDateTime::assume_utc)
                .map_err(|_| error)
        })
    }
}

#[cfg(feature = "time")]
fn time_parse_error(error: time::error::Parse) -> DrizzleError {
    DrizzleError::ConversionError(error.to_string().into())
}

#[cfg(feature = "time")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for time::Date {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        Self::parse(&s, &time::format_description::well_known::Iso8601::DATE)
            .map_err(time_parse_error)
    }
}

#[cfg(feature = "time")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for time::Time {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        time_text::time(&s).map_err(time_parse_error)
    }
}

#[cfg(feature = "time")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for time::PrimitiveDateTime {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        time_text::primitive(&s).map_err(time_parse_error)
    }
}

#[cfg(feature = "time")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for time::OffsetDateTime {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        time_text::offset(&s).map_err(time_parse_error)
    }
}

/// Parses SQLite text as a jiff value.
#[cfg(feature = "jiff")]
fn parse_jiff<T: core::str::FromStr<Err = jiff::Error>>(text: &str) -> Result<T, DrizzleError> {
    text.parse()
        .map_err(|e: jiff::Error| DrizzleError::ConversionError(e.to_string().into()))
}

#[cfg(feature = "jiff")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for jiff::civil::Date {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        parse_jiff(&String::from_row_at(row, offset)?)
    }
}

#[cfg(feature = "jiff")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for jiff::civil::Time {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        parse_jiff(&String::from_row_at(row, offset)?)
    }
}

#[cfg(feature = "jiff")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for jiff::civil::DateTime {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        parse_jiff(&String::from_row_at(row, offset)?)
    }
}

#[cfg(feature = "jiff")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for jiff::Timestamp {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        // RFC 3339 as the SQLite conversion writes it; text without an offset
        // (as SQLite's own `CURRENT_TIMESTAMP` writes) is UTC.
        s.parse().or_else(|_| {
            let civil: jiff::civil::DateTime = parse_jiff(&s)?;
            jiff::tz::Offset::UTC
                .to_timestamp(civil)
                .map_err(|e| DrizzleError::ConversionError(e.to_string().into()))
        })
    }
}

/// A JSON column read on its own (`select(t.meta)`) decodes through
/// [`Json`](crate::json::Json), so the payload type needs no impls.
#[cfg(feature = "serde")]
impl<R: SqliteValueRow, T: serde::de::DeserializeOwned> FromDrizzleRow<R> for crate::json::Json<T> {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        match row.cell_at(offset)? {
            SqliteCell::Text(text) => Self::from_json_str(&text),
            SqliteCell::Blob(bytes) => Self::from_json_slice(&bytes),
            SqliteCell::Integer(value) => Self::from_json_value(serde_json::Value::from(value)),
            SqliteCell::Real(value) => Self::from_json_value(
                serde_json::Number::from_f64(value)
                    .map(serde_json::Value::Number)
                    .ok_or_else(|| {
                        DrizzleError::ConversionError(
                            "cannot convert a non-finite REAL to JSON".into(),
                        )
                    })?,
            ),
            SqliteCell::Null => Err(DrizzleError::ConversionError(
                "unexpected NULL for a JSON column".into(),
            )),
        }
    }
}

#[cfg(feature = "serde")]
impl<R: SqliteValueRow> FromDrizzleRow<R> for serde_json::Value {
    const COLUMN_COUNT: usize = 1;
    fn from_row_at(row: &R, offset: usize) -> Result<Self, DrizzleError> {
        let s = String::from_row_at(row, offset)?;
        serde_json::from_str(&s).map_err(Into::into)
    }
}