spin-sdk 7.0.0

The Spin Rust SDK makes it easy to build Spin components in 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
474
475
476
use crate::wit_bindgen;

#[doc(hidden)]
/// Module containing wit bindgen generated code.
///
/// This is only meant for internal consumption.
pub mod wit {
    #![allow(missing_docs)]
    use crate::wit_bindgen;

    wit_bindgen::generate!({
        runtime_path: "crate::wit_bindgen::rt",
        world: "spin-sdk-sqlite",
        path: "wit",
        generate_all,
    });

    pub use spin::sqlite::sqlite;
}

#[doc(inline)]
pub use wit::sqlite::{Error, Value};

/// An open connection to a SQLite database.
///
/// [Connection::execute()] returns a tuple of `(columns, rows_stream, finish_future)`
/// where rows are consumed from a stream and the finish future is awaited to check
/// for errors.
///
/// # Examples
///
/// Open the default database, query rows, and iterate over the stream.
///
/// ```no_run
/// # async fn run() -> anyhow::Result<()> {
/// use spin_sdk::sqlite::{Connection, Value};
///
/// let min_age = 0;
/// let db = Connection::open_default().await?;
///
/// let mut query_result = db.execute(
///     "SELECT * FROM users WHERE age >= ?",
///     [Value::Integer(min_age)],
/// ).await?;
///
/// let name_idx = query_result.columns().iter().position(|c| c == "name").unwrap();
///
/// while let Some(row) = query_result.next().await {
///     let name: &str = row.get(name_idx).unwrap();
///     println!("Found user {name}");
/// }
///
/// query_result.result().await?;
/// # Ok(())
/// # }
/// ```
///
/// Perform an aggregate (scalar) operation over a named database.
///
/// ```no_run
/// # async fn run() -> anyhow::Result<()> {
/// use spin_sdk::sqlite::Connection;
///
/// let db = Connection::open("customer-data").await?;
/// let mut query_result = db.execute("SELECT COUNT(*) FROM users", []).await?;
///
/// if let Some(row) = query_result.next().await {
///     let count: i64 = row.get(0).unwrap();
///     println!("Total users: {count}");
/// }
///
/// query_result.result().await?;
/// # Ok(())
/// # }
/// ```
///
/// Delete rows from a database. The row stream will be empty, but the finish
/// future must still be awaited.
///
/// ```no_run
/// # async fn run() -> anyhow::Result<()> {
/// use spin_sdk::sqlite::{Connection, Value};
///
/// let min_age = 18;
/// let db = Connection::open("customer-data").await?;
/// let query_result = db.execute(
///     "DELETE FROM users WHERE age < ?",
///     [Value::Integer(min_age)],
/// ).await?;
///
/// query_result.result().await?;
/// # Ok(())
/// # }
/// ```
pub struct Connection(wit::sqlite::Connection);

impl Connection {
    /// Open a connection to the default database
    pub async fn open_default() -> Result<Self, Error> {
        Self::open("default").await
    }

    /// Open a connection to a named database instance.
    ///
    /// If `database` is "default", the default instance is opened.
    ///
    /// `error::no-such-database` will be raised if the `name` is not recognized.
    pub async fn open(database: impl AsRef<str>) -> Result<Self, Error> {
        wit::sqlite::Connection::open_async(database.as_ref().to_string())
            .await
            .map(Connection)
    }

    /// Execute a statement returning back data if there is any
    pub async fn execute(
        &self,
        statement: impl AsRef<str>,
        parameters: impl IntoIterator<Item = Value>,
    ) -> Result<QueryResult, Error> {
        let (columns, rows, result) = self
            .0
            .execute_async(
                statement.as_ref().to_string(),
                parameters.into_iter().collect(),
            )
            .await?;
        Ok(QueryResult {
            columns,
            rows,
            result,
        })
    }

    /// The SQLite rowid of the most recent successful INSERT on the connection, or 0 if
    /// there has not yet been an INSERT on the connection.
    pub async fn last_insert_rowid(&self) -> i64 {
        self.0.last_insert_rowid_async().await
    }

    /// The number of rows modified, inserted or deleted by the most recently completed
    /// INSERT, UPDATE or DELETE statement on the connection.
    pub async fn changes(&self) -> u64 {
        self.0.changes_async().await
    }
}

/// The result of a [`Connection::execute`] operation.
pub struct QueryResult {
    columns: Vec<String>,
    rows: wit_bindgen::StreamReader<RowResult>,
    result: wit_bindgen::FutureReader<Result<(), Error>>,
}

impl QueryResult {
    /// The columns in the query result.
    pub fn columns(&self) -> &[String] {
        &self.columns
    }

    /// Gets the next row in the result set.
    ///
    /// If this is `None`, there are no more rows available. You _must_
    /// await [`QueryResult::result()`] to determine if all rows
    /// were read successfully.
    pub async fn next(&mut self) -> Option<RowResult> {
        self.rows.next().await
    }

    /// Whether the query completed successfully or with an error.
    pub async fn result(self) -> Result<(), Error> {
        self.result.await
    }

    /// Collect all rows in the result set.
    ///
    /// This is provided for when the result set is small enough to fit in
    /// memory and you do not require streaming behaviour.
    pub async fn collect(self) -> Result<Vec<RowResult>, Error> {
        let rows = self.rows.collect().await;
        self.result.await?;
        Ok(rows)
    }

    /// Extracts the underlying Wasm Component Model results of the query.
    #[allow(clippy::type_complexity, reason = "that's what the inner bits are")]
    pub fn into_inner(
        self,
    ) -> (
        Vec<String>,
        wit_bindgen::StreamReader<RowResult>,
        wit_bindgen::FutureReader<Result<(), Error>>,
    ) {
        (self.columns, self.rows, self.result)
    }
}

/// A single row from a SQLite query result.
///
/// `RowResult` provides index-based access to column values via [`RowResult::get()`].
///
/// # Examples
///
/// Consume rows from the async streaming API:
///
/// ```no_run
/// # async fn run() -> anyhow::Result<()> {
/// use spin_sdk::sqlite::{Connection, Value};
///
/// let db = Connection::open_default().await?;
/// let mut query_result = db.execute(
///     "SELECT name, age FROM users WHERE age >= ?",
///     [Value::Integer(0)],
/// ).await?;
///
/// let name_idx = query_result.columns().iter().position(|c| c == "name").unwrap();
///
/// while let Some(row) = query_result.next().await {
///     let name: &str = row.get(name_idx).unwrap();
///     println!("Found user {name}");
/// }
///
/// query_result.result().await?;
/// # Ok(())
/// # }
/// ```
#[doc(inline)]
pub use wit::sqlite::RowResult;

impl RowResult {
    /// Get a value by its column name. The value is converted to the target type.
    ///
    /// * SQLite integers are convertible to Rust integer types (i8, u8, i16, etc. including usize and isize) and bool.
    /// * SQLite strings are convertible to Rust &str or &[u8] (encoded as UTF-8).
    /// * SQLite reals are convertible to Rust f64.
    /// * SQLite blobs are convertible to Rust &[u8] or &str (interpreted as UTF-8).
    ///
    /// To look up by name, you can use `QueryResult::rows()` or obtain the invoice from `QueryResult::columns`.
    /// If you do not know the type of a value, access the underlying [Value] enum directly
    /// via the [RowResult::values] field
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn run() -> anyhow::Result<()> {
    /// use spin_sdk::sqlite::{Connection, Value};
    ///
    /// let db = Connection::open_default().await?;
    /// let mut query_result = db.execute(
    ///     "SELECT name, age FROM users WHERE id = ?",
    ///     [Value::Integer(0)],
    /// ).await?;
    ///
    /// if let Some(row) = query_result.next().await {
    ///     let name: &str = row.get(0).unwrap();
    ///     let age: u16 = row.get(1).unwrap();
    ///     println!("{name} is {age} years old");
    /// }
    ///
    /// query_result.result().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn get<'a, T: TryFrom<&'a Value>>(&'a self, index: usize) -> Option<T> {
        self.values.get(index).and_then(|c| c.try_into().ok())
    }
}

impl<'a> TryFrom<&'a Value> for bool {
    type Error = ();

    fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
        match value {
            Value::Integer(i) => Ok(*i != 0),
            _ => Err(()),
        }
    }
}

macro_rules! int_from_value {
    ($($t:ty),*) => {
        $(impl<'a> TryFrom<&'a Value> for $t {
            type Error = ();

            fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
                match value {
                    Value::Integer(i) => (*i).try_into().map_err(|_| ()),
                    _ => Err(()),
                }
            }
        })*
    };
}

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

impl<'a> TryFrom<&'a Value> for f64 {
    type Error = ();

    fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
        match value {
            Value::Real(f) => Ok(*f),
            _ => Err(()),
        }
    }
}

impl<'a> TryFrom<&'a Value> for &'a str {
    type Error = ();

    fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
        match value {
            Value::Text(s) => Ok(s.as_str()),
            Value::Blob(b) => std::str::from_utf8(b).map_err(|_| ()),
            _ => Err(()),
        }
    }
}

impl<'a> TryFrom<&'a Value> for &'a [u8] {
    type Error = ();

    fn try_from(value: &'a Value) -> Result<Self, Self::Error> {
        match value {
            Value::Blob(b) => Ok(b.as_slice()),
            Value::Text(s) => Ok(s.as_bytes()),
            _ => Err(()),
        }
    }
}

impl Value {
    /// Creates a Text parameter.
    pub fn text(value: impl Into<String>) -> Self {
        Self::Text(value.into())
    }

    /// Creates an Integer parameter.
    pub fn integer(value: impl Into<i64>) -> Self {
        Self::Integer(value.into())
    }

    /// Creates a Real parameter.
    pub fn real(value: impl Into<f64>) -> Self {
        Self::Real(value.into())
    }

    /// Creates a Blob parameter.
    pub fn blob(value: impl Into<Vec<u8>>) -> Self {
        Self::Blob(value.into())
    }
}

impl From<&str> for Value {
    fn from(value: &str) -> Self {
        Self::Text(value.into())
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

macro_rules! value_from_int {
    ($($t:ty),*) => {
        $(impl From<$t> for Value {
            fn from(value: $t) -> Self {
                Self::integer(value)
            }
        })*
    };
}

value_from_int!(u8, u16, u32, i8, i16, i32, i64);

impl From<f32> for Value {
    fn from(value: f32) -> Self {
        Self::Real(value.into())
    }
}

impl From<f64> for Value {
    fn from(value: f64) -> Self {
        Self::Real(value)
    }
}

impl From<&[u8]> for Value {
    fn from(value: &[u8]) -> Self {
        Self::Blob(value.into())
    }
}

impl<const N: usize> From<[u8; N]> for Value {
    fn from(value: [u8; N]) -> Self {
        Self::Blob(value.into())
    }
}

impl<const N: usize> From<&[u8; N]> for Value {
    fn from(value: &[u8; N]) -> Self {
        Self::Blob(value.into())
    }
}

impl From<Vec<u8>> for Value {
    fn from(value: Vec<u8>) -> Self {
        Self::Blob(value)
    }
}

impl<T: Into<Value>> From<Option<T>> for Value {
    fn from(value: Option<T>) -> Self {
        match value {
            None => Value::Null,
            Some(value) => value.into(),
        }
    }
}

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Integer(l0), Self::Integer(r0)) => l0 == r0,
            (Self::Real(l0), Self::Real(r0)) => l0 == r0,
            (Self::Text(l0), Self::Text(r0)) => l0 == r0,
            (Self::Blob(l0), Self::Blob(r0)) => l0 == r0,
            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn value_conversions() {
        let expected_text = Value::Text("a".to_string());
        let expected_int = Value::Integer(123);
        let expected_real = Value::Real(1234.5); // the test wants equality and FP stuff is notoriously inexact: use a value for testing that won't incur off-by-0.00000001 errors
        let expected_real_int = Value::Real(123.0);
        let expected_blob = Value::Blob(vec![1, 2, 3]);

        assert_eq!(expected_text, Value::text("a"));
        assert_eq!(expected_text, "a".into());
        assert_eq!(expected_text, "a".to_string().into());

        assert_eq!(expected_int, Value::integer(123u8));
        assert_eq!(expected_int, Value::integer(123i16));
        assert_eq!(expected_int, Value::integer(123u32));
        assert_eq!(expected_int, Value::integer(123i64));
        assert_eq!(expected_int, 123u8.into());
        assert_eq!(expected_int, 123i16.into());
        assert_eq!(expected_int, 123u32.into());
        assert_eq!(expected_int, 123i64.into());

        assert_eq!(expected_real, Value::real(1234.5f32));
        assert_eq!(expected_real, Value::real(1234.5f64));
        assert_eq!(expected_real, 1234.5f32.into());
        assert_eq!(expected_real, 1234.5f64.into());
        // named function allows passing integer to Real case (where `into()` would give you the Integer case)
        assert_eq!(expected_real_int, Value::real(123u32));

        assert_eq!(expected_blob, Value::blob([1, 2, 3]));
        assert_eq!(expected_blob, Value::blob(vec![1, 2, 3]));
        assert_eq!(expected_blob, (&[1, 2, 3]).into());
        assert_eq!(expected_blob, ([1, 2, 3][..]).into());
        assert_eq!(expected_blob, [1, 2, 3].into());
        assert_eq!(expected_blob, (vec![1, 2, 3]).into());

        assert_eq!(Value::Null, None::<i16>.into());
        assert_eq!(expected_int, Some(123u32).into());
    }
}