@@ -12,7 +12,7 @@ Read the [Notes and FAQ](#notes-and-faq)
12
12
use worker :: * ;
13
13
14
14
#[event(fetch)]
15
- pub async fn main (req : Request , env : Env , _ctx : worker :: Context ) -> Result <Response > {
15
+ pub async fn main (mut req : Request , env : Env , _ctx : worker :: Context ) -> Result <Response > {
16
16
console_log! (
17
17
" {} {}, located at: {:?}, within: {}" ,
18
18
req . method (). to_string (),
@@ -221,11 +221,10 @@ For more information about how to configure these bindings, see:
221
221
### Define a Durable Object in Rust
222
222
223
223
To define a Durable Object using the ` worker ` crate you need to implement the ` DurableObject ` trait
224
- on your own struct. Additionally, the ` #[durable_object] ` attribute macro must be applied to _ both_
225
- your struct definition and the trait ` impl ` block for it.
224
+ on your own struct. Additionally, the ` #[durable_object] ` attribute macro must be applied to the struct definition.
226
225
227
226
``` rust
228
- use worker :: * ;
227
+ use worker :: {durable_object, State , Env , Result , Request , Response } ;
229
228
230
229
#[durable_object]
231
230
pub struct Chatroom {
@@ -235,7 +234,6 @@ pub struct Chatroom {
235
234
env : Env , // access `Env` across requests, use inside `fetch`
236
235
}
237
236
238
- #[durable_object]
239
237
impl DurableObject for Chatroom {
240
238
fn new (state : State , env : Env ) -> Self {
241
239
Self {
@@ -246,7 +244,7 @@ impl DurableObject for Chatroom {
246
244
}
247
245
}
248
246
249
- async fn fetch (& mut self , _req : Request ) -> Result <Response > {
247
+ async fn fetch (& self , _req : Request ) -> Result <Response > {
250
248
// do some work when a worker makes a request to this DO
251
249
Response :: ok (& format! (" {} active users." , self . users. len ()))
252
250
}
@@ -271,6 +269,66 @@ tag = "v1" # Should be unique for each entry
271
269
new_classes = [" Chatroom" ] # Array of new classes
272
270
```
273
271
272
+ ### SQLite Storage in Durable Objects
273
+
274
+ Durable Objects can use SQLite for persistent storage, providing a relational database interface. To enable SQLite storage, you need to use ` new_sqlite_classes ` in your migration and access the SQL storage through ` state.storage().sql() ` .
275
+
276
+ ``` rust
277
+ use worker :: {durable_object, State , Env , Result , Request , Response , SqlStorage };
278
+
279
+ #[durable_object]
280
+ pub struct SqlCounter {
281
+ sql : SqlStorage ,
282
+ }
283
+
284
+ impl DurableObject for SqlCounter {
285
+ fn new (state : State , _env : Env ) -> Self {
286
+ let sql = state . storage (). sql ();
287
+ // Create table if it does not exist
288
+ sql . exec (" CREATE TABLE IF NOT EXISTS counter(value INTEGER);" , None )
289
+ . expect (" create table" );
290
+ Self { sql }
291
+ }
292
+
293
+ async fn fetch (& self , _req : Request ) -> Result <Response > {
294
+ #[derive(serde:: Deserialize )]
295
+ struct Row {
296
+ value : i32 ,
297
+ }
298
+
299
+ // Read current value
300
+ let rows : Vec <Row > = self
301
+ . sql
302
+ . exec (" SELECT value FROM counter LIMIT 1;" , None )?
303
+ . to_array ()? ;
304
+ let current = rows . get (0 ). map (| r | r . value). unwrap_or (0 );
305
+ let next = current + 1 ;
306
+
307
+ // Update counter
308
+ self . sql. exec (" DELETE FROM counter;" , None )? ;
309
+ self . sql
310
+ . exec (" INSERT INTO counter(value) VALUES (?);" , vec! [next . into ()])? ;
311
+
312
+ Response :: ok (format! (" SQL counter is now {}" , next ))
313
+ }
314
+ }
315
+ ```
316
+
317
+ Configure your ` wrangler.toml ` to enable SQLite storage:
318
+
319
+ ``` toml
320
+ # ...
321
+
322
+ [durable_objects ]
323
+ bindings = [
324
+ { name = " SQL_COUNTER" , class_name = " SqlCounter" }
325
+ ]
326
+
327
+ [[migrations ]]
328
+ tag = " v1" # Should be unique for each entry
329
+ new_sqlite_classes = [" SqlCounter" ] # Use new_sqlite_classes for SQLite-enabled objects
330
+ ```
331
+
274
332
- For more information about migrating your Durable Object as it changes, see the docs here:
275
333
https://developers.cloudflare.com/workers/learning/using-durable-objects#durable-object-migrations-in-wranglertoml
276
334
0 commit comments