drizzle 0.1.3

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
# Drizzle RS


A type-safe SQL query builder for Rust inspired by Drizzle ORM.

## Schema Setup


First, create a `schema.rs` file to define your database tables. All schema
items must be `pub` for proper destructuring:

```rust
use drizzle::prelude::*;
use uuid::Uuid;

#[derive(SQLiteSchema)]

pub struct Schema {
    pub users: Users,
    pub posts: Posts,
    pub user_email_idx: UserEmailIdx,
    pub user_email_username_idx: UserEmailUsernameIdx,
}

#[SQLiteTable(name = "users")]

pub struct Users {
    #[blob(primary, default_fn = Uuid::new_v4)]
    pub id: Uuid,
    #[text]
    pub name: String,
    #[text]
    pub email: Option<String>,
    #[integer]
    pub age: u64,
}

#[SQLiteTable(name = "posts")]

pub struct Posts {
    #[blob(primary, default_fn = Uuid::new_v4)]
    pub id: Uuid,
    #[blob(references = Users::id)]
    pub user_id: Uuid,
    #[text]
    pub context: Option<String>,
}

// Index definitions
#[SQLiteIndex(unique)]

pub struct UserEmailUsernameIdx(Users::email, Users::name);

#[SQLiteIndex]

pub struct UserEmailIdx(Users::email);
```

### UUID Storage Options


Choose between binary (BLOB) or string (TEXT) storage:

```rust
// Binary storage (16 bytes) - more efficient
#[blob(primary, default_fn = Uuid::new_v4)]

pub id: Uuid,

// String storage (36 characters) - human readable
#[text(primary, default_fn = || Uuid::new_v4)]

pub id: Uuid,
```

### Indexes


Indexes are defined as separate structs and included in your schema. They
reference table columns using the `Table::column` syntax:

```rust
use drizzle::prelude::*;

// Unique compound index on email and name
#[SQLiteIndex(unique)]

pub struct UserEmailUsernameIdx(Users::email, Users::name);

// Simple index on email column
#[SQLiteIndex]

pub struct UserEmailIdx(Users::email);
```

The indexes are automatically created when you call `db.create()` and must be
included as fields in your schema struct.

## Basic Usage


In your `main.rs`, use the schema without feature flags:

```rust
mod schema;

use drizzle::prelude::*;
use drizzle::rusqlite::Drizzle;
use rusqlite::Connection;
use uuid::Uuid;

use crate::schema::{InsertPosts, InsertUsers, Posts, Schema, SelectPosts, SelectUsers, Users};

fn main() -> drizzle::Result<()> {
    let conn = Connection::open_in_memory()?;
    let (mut db, Schema { users, posts, .. }) = Drizzle::new(conn, Schema::new());

    // Create tables (only on fresh database)
    db.create()?;

    let id = Uuid::new_v4();

    // Insert data
    db.insert(users)
        .values([InsertUsers::new("Alex Smith", 26).with_id(id)])
        .execute()?;

    db.insert(posts)
        .values([InsertPosts::new(id).with_context("just testing")])
        .execute()?;

    // Query data
    let user_rows: Vec<SelectUsers> = db.select(()).from(users).all()?;
    let post_rows: Vec<SelectPosts> = db.select(()).from(posts).all()?;

    println!("Users: {:?}", user_rows);
    println!("Posts: {:?}", post_rows);

    // JOIN queries with custom result struct
    #[derive(FromRow, Default, Debug)]
    struct JoinedResult {
        #[column(Users::id)]
        id: Uuid,
        #[column(Posts::id)]
        post_id: Uuid,
        name: String,
        age: u64,
    }

    let row: JoinedResult = db
        .select(JoinedResult::default())
        .from(users)
        .left_join(posts, eq(users.id, posts.user_id))
        .get()?;

    Ok(())
}
```

## Insert Models


```rust
// Always use new() as it forces you at compile time to input required fields
InsertUsers::new("John Doe", 25)
    .with_email("john@example.com") // Optional fields or fields with defaults via .with_*
```

> [!WARNING]\
> Avoid using `InsertUsers::default()`, as it will fail at runtime if required
> fields are not provided.

The `.values()` method automatically batches inserts of the same type:

```rust
// Same insert model type - will batch
db.insert(users)
    .values([
        InsertUsers::new("Alice", 30),
        InsertUsers::new("Bob", 25),
    ])
    .execute()?;

// compile time failure
db.insert(users)
    .values([
        InsertUsers::new("Alice", 30),
        InsertUsers::new("Bob", 25).with_email("bob@example.com"),
    ])
    .execute()?;
```

## Transactions


For multiple different operations or when you need ACID guarantees, use
transactions:

```rust
use drizzle::sqlite::SQLiteTransactionType;

// sync drivers
db.transaction(SQLiteTransactionType::Deferred, |tx| {
    // Insert users
    tx.insert(users)
        .values([InsertUsers::new("Alice", 30)])
        .execute()?;

    // Insert posts
    tx.insert(posts)
        .values([InsertPosts::new(user_id)])
        .execute()?;

    // Update data
    tx.update(users)
        .set(UpdateUsers::default().with_age(31))
        .r#where(eq(users.name, "Alice"))
        .execute()?;

    Ok(())
})?;

// async drivers - api is wip as I think pinning here is gross.
db.transaction(SQLiteTransactionType::Deferred, |tx| Box::pin(async move {
    // Insert users
    tx.insert(users)
        .values([InsertUsers::new("Alice", 30)])
        .execute()
        .await?;

    // Insert posts
    tx.insert(posts)
        .values([InsertPosts::new(user_id)])
        .execute()
        .await?;

    // Update data
    tx.update(users)
        .set(UpdateUsers::default().with_age(31))
        .r#where(eq(users.name, "Alice"))
        .execute()
        .await?;

    Ok(())
})).await?;
```

For more details on transaction types, see the
[SQLite Transaction Documentation](https://www.sqlite.org/lang_transaction.html).

## Table Attributes


```rust
#[SQLiteTable] // Basic table

#[SQLiteTable(name = "custom_name")] // Custom table name

#[SQLiteTable(strict)] // SQLite STRICT mode

#[SQLiteTable(without_rowid)] // WITHOUT ROWID table

#[SQLiteTable(name = "users", strict, without_rowid)] // Combined

```

## Field Attributes


```rust
// Column types
#[integer] // INTEGER column

#[text]    // TEXT column

#[real]    // REAL column

#[blob]    // BLOB column

#[boolean] // Stored as INTEGER (0/1)


// Constraints
#[integer(primary)]              // Primary key

#[integer(primary, autoincrement)] // Auto-incrementing primary key

#[text(unique)]                  // Unique constraint

#[text(primary)]                 // Text primary key


// Default values
#[text(default = "hello")]             // Compile-time default

#[integer(default = 42)]               // Compile-time default

#[text(default_fn = String::new)]      // Runtime default function


// Special types
#[text(enum)]    // Store enum as TEXT

#[integer(enum)] // Store enum as INTEGER

#[text(json)]    // JSON serialized to TEXT

#[blob(json)]    // JSON serialized to BLOB


// Foreign keys
#[integer(references = Users::id)] // Foreign key reference

```

## Nullability


Nullability is controlled by Rust's type system:

```rust
#[SQLiteTable(name = "example")]

struct Example {
    #[integer(primary)]
    id: i32,           // NOT NULL - required field
    #[text]
    name: String,      // NOT NULL - required field
    #[text]
    email: Option<String>, // NULL allowed - optional field
}
```

## Enums


```rust
#[derive(SQLiteEnum, Default)]

enum UserRole {
    #[default]
    User,
    Admin,
    Moderator,
}

#[SQLiteTable(name = "users")]

struct Users {
    #[integer(primary)]
    id: i32,
    #[text(enum)] // Stored as TEXT: "User", "Admin", "Moderator"
    role: UserRole,
}
```

## JSON Fields


```rust
#[derive(serde::Serialize, serde::Deserialize)]

struct UserMetadata {
    preferences: Vec<String>,
    theme: String,
}

#[SQLiteTable(name = "users")]

struct Users {
    #[integer(primary)]
    id: i32,
    #[text(json)] // JSON stored as TEXT
    metadata: Option<UserMetadata>,
    #[blob(json)] // JSON stored as BLOB (binary)
    config: Option<UserMetadata>,
}
```

## FromRow Derive Macro


The `FromRow` derive macro automatically generates `TryFrom<&Row>`
implementations for converting database rows into your structs.

### Basic Usage


```rust
use drizzle::prelude::*;

#[derive(FromRow, Debug)]

struct User {
    id: i32,
    name: String,
    email: String,
}

// Query returns User structs directly
let users: Vec<User> = db.select(()).from(users_table).all()?;
```

### Column Mapping


Use the `#[column]` attribute to map struct fields to specific table columns:

```rust
#[derive(FromRow, Debug)]

struct UserInfo {
    #[column(Users::id)]
    user_id: i32,
    #[column(Users::name)]
    full_name: String,
    #[column(Users::email)]
    email_address: String,
}

// Use in SELECT queries with custom column mapping
// You can collect into your favorite container
let info: Vec<UserInfo> = db
    .select(UserInfo::default())
    .from(users)
    .all()?;
```

### JOIN Queries


Perfect for handling JOIN query results:

```rust
#[derive(FromRow, Debug)]

struct UserPost {
    #[column(Users::id)]
    user_id: i32,
    #[column(Users::name)]
    user_name: String,
    #[column(Posts::id)]
    post_id: i32,
    #[column(Posts::title)]
    post_title: String,
}

let results: Vec<UserPost> = db
    .select(UserPost::default())
    .from(users)
    .inner_join(posts, eq(users.id, posts.user_id))
    .all()?;
```

### Tuple Structs


Also works with tuple structs for simple cases:

```rust
#[derive(FromRow, Debug)]

struct UserName(String);

let names: Vec<UserName> = db
    .select(users.name)
    .from(users)
    .all()?;
```

The macro automatically handles:

- Type conversions between SQLite types and Rust types
- Optional fields (`Option<T>`)
- All supported column types (integers, text, blobs, JSON, enums)

## SQLite PRAGMA Support


```rust
use drizzle::sqlite::pragma::{Pragma, JournalMode};

// Type-safe pragma statements
let pragma = Pragma::foreign_keys(true);
// Execute with drizzle
db.execute(pragma)?;
```