drizzle 0.1.6

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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#![cfg(any(feature = "rusqlite", feature = "turso", feature = "libsql"))]
#![allow(clippy::approx_constant)]

use drizzle::core::expr::*;
use drizzle::sqlite::prelude::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

// Test all SQLite column types
#[SQLiteTable]
struct AllTypes {
    #[column(PRIMARY)]
    id: i32,
    text_field: String,
    int_field: i32,
    real_field: f64,
    blob_field: Vec<u8>,
    bool_field: bool,
}

// Test primary key variations
#[SQLiteTable(NAME = "pk_variations")]
struct PrimaryKeyVariations {
    #[column(PRIMARY, AUTOINCREMENT)]
    auto_id: i32,
    name: String,
}

#[SQLiteTable(NAME = "manual_pk")]
struct ManualPrimaryKey {
    #[column(PRIMARY)]
    manual_id: String,
    description: String,
}

// Test unique constraints
#[SQLiteTable]
struct UniqueFields {
    #[column(PRIMARY, AUTOINCREMENT)]
    id: i32,
    #[column(UNIQUE)]
    email: String,
    #[column(UNIQUE)]
    username: String,
    display_name: Option<String>,
}

// Test default values - compile time literals
#[SQLiteTable(NAME = "compile_defaults")]
struct CompileTimeDefaults {
    #[column(PRIMARY, AUTOINCREMENT)]
    id: i32,
    #[column(DEFAULT = "default_name")]
    name: String,
    #[column(DEFAULT = 42)]
    answer: i32,
    #[column(DEFAULT = 3.14)]
    pi: f64,
    #[column(DEFAULT = true)]
    active: bool,
    #[column(DEFAULT = "pending")]
    status: String,
}

// Test default values - runtime functions
#[SQLiteTable]
struct RuntimeDefaults {
    #[column(PRIMARY, AUTOINCREMENT)]
    id: i32,
    #[column(DEFAULT_FN = String::new)]
    empty_text: String,
    #[column(DEFAULT_FN = || 100)]
    computed_int: i32,
    name: String,
}

// Test enums with different storage types
#[derive(SQLiteEnum, Default, Clone, PartialEq, Debug, Copy)]
enum Priority {
    Low = 1,
    #[default]
    Medium = 2,
    High = 3,
}

#[derive(SQLiteEnum, Default, Clone, PartialEq, Debug, Copy)]
enum TaskStatus {
    #[default]
    Todo,
    InProgress,
    Done,
}

#[SQLiteTable]
struct EnumFields {
    #[column(PRIMARY, AUTOINCREMENT)]
    id: i32,
    #[column(INTEGER, ENUM)]
    priority: Priority,
    #[column(ENUM)]
    status: TaskStatus,
    description: String,
}

// Test table with tuple/struct enum fields
#[SQLiteTable]
struct ComplexEnumFields {
    #[column(PRIMARY, AUTOINCREMENT)]
    id: i32,
    notes: String,
}

// Test JSON fields with serde feature
#[cfg(feature = "serde")]
#[derive(Deserialize, Serialize, Default, Debug, Clone, PartialEq)]
struct JsonData {
    value: i32,
    message: String,
}

#[cfg(feature = "serde")]
#[SQLiteTable]
struct JsonFields {
    #[column(PRIMARY, AUTOINCREMENT)]
    id: i32,
    #[column(JSON)]
    text_json: Option<JsonData>,
    regular_text: String,
}

// Test UUID fields
#[cfg(feature = "uuid")]
#[SQLiteTable]
struct UuidFields {
    #[column(PRIMARY, DEFAULT_FN = uuid::Uuid::new_v4)]
    id: uuid::Uuid,
    name: String,
    other_uuid: Option<uuid::Uuid>,
}

// Test nullable vs non-nullable fields
#[SQLiteTable]
struct NullableTest {
    #[column(PRIMARY, AUTOINCREMENT)]
    id: i32,
    // Required fields (non-nullable)
    required_text: String,
    required_int: i32,
    required_bool: bool,

    // Optional fields (nullable)
    optional_text: Option<String>,
    optional_int: Option<i32>,
    optional_real: Option<f64>,
    optional_blob: Option<Vec<u8>>,
    optional_bool: Option<bool>,
}

// Schemas for individual table tests
#[derive(SQLiteSchema)]
struct AllTypesSchema {
    all_types: AllTypes,
}

#[derive(SQLiteSchema)]
struct PrimaryKeyVariationsSchema {
    pk_variations: PrimaryKeyVariations,
}

#[derive(SQLiteSchema)]
struct ManualPrimaryKeySchema {
    manual_pk: ManualPrimaryKey,
}

#[derive(SQLiteSchema)]
struct UniqueFieldsSchema {
    unique_fields: UniqueFields,
}

#[derive(SQLiteSchema)]
struct CompileTimeDefaultsSchema {
    compile_defaults: CompileTimeDefaults,
}

#[derive(SQLiteSchema)]
struct RuntimeDefaultsSchema {
    runtime_defaults: RuntimeDefaults,
}

#[derive(SQLiteSchema)]
struct EnumFieldsSchema {
    enum_fields: EnumFields,
}

#[derive(SQLiteSchema)]
struct ComplexEnumFieldsSchema {
    complex_enum_fields: ComplexEnumFields,
}

#[cfg(feature = "serde")]
#[derive(SQLiteSchema)]
struct JsonFieldsSchema {
    json_fields: JsonFields,
}

#[cfg(feature = "uuid")]
#[derive(SQLiteSchema)]
struct UuidFieldsSchema {
    uuid_fields: UuidFields,
}

#[derive(SQLiteSchema)]
struct NullableTestSchema {
    nullable_test: NullableTest,
}

#[drizzle::test]
fn test_all_column_types(db: &mut TestDb<AllTypesSchema>) {
    let all_types = schema.all_types;

    // Test insertion with all column types
    let test_data = InsertAllTypes::new("test text", 123, 45.67, [1, 2, 3, 4, 5], true);

    let result = db.insert(all_types).values([test_data]).execute();
    assert_eq!(result, 1);
}

#[drizzle::test]
fn test_primary_key_autoincrement(db: &mut TestDb<PrimaryKeyVariationsSchema>) {
    let pk_table = schema.pk_variations;

    // Insert multiple records to test autoincrement
    let data1 = InsertPrimaryKeyVariations::new("first");
    let data2 = InsertPrimaryKeyVariations::new("second");

    db.insert(pk_table).values([data1]).execute();
    db.insert(pk_table).values([data2]).execute();

    // Verify autoincrement worked using unified approach
    let select_query = db
        .select((pk_table.auto_id, pk_table.name))
        .from(pk_table)
        .order_by(pk_table.auto_id);

    #[derive(SQLiteFromRow, Debug, PartialEq)]
    struct ReturnResult(i32, String);

    let results: Vec<ReturnResult> = db.all(select_query);

    assert_eq!(results.len(), 2);
    assert_eq!(results[0], ReturnResult(1, "first".to_string()));
    assert_eq!(results[1], ReturnResult(2, "second".to_string()));
}

#[drizzle::test]
fn test_manual_primary_key(db: &mut TestDb<ManualPrimaryKeySchema>) {
    let manual_pk = schema.manual_pk;

    let data = InsertManualPrimaryKey::new("custom_id_123", "Test description");

    let result = db.insert(manual_pk).values([data]).execute();
    assert_eq!(result, 1);

    // Verify the manual primary key using unified query approach
    let select_query = db
        .select(())
        .from(manual_pk)
        .r#where(eq(manual_pk.manual_id, "custom_id_123"));

    #[derive(SQLiteFromRow, Debug, PartialEq)]
    struct ReturnResult(String, String);

    let results: Vec<ReturnResult> = db.all(select_query);

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, "custom_id_123");
    assert_eq!(results[0].1, "Test description");
}

#[drizzle::test]
fn test_unique_constraints(db: &mut TestDb<UniqueFieldsSchema>) {
    let unique_table = schema.unique_fields;

    // Insert first record
    let data1 =
        InsertUniqueFields::new("test@example.com", "testuser").with_display_name("Test User");

    let result1 = db.insert(unique_table).values([data1]).execute();
    assert_eq!(result1, 1);

    // Try to insert duplicate email - should fail
    let data2 = InsertUniqueFields::new("test@example.com", "anotheruser")
        .with_display_name("Another User");

    let result2 = result!(db.insert(unique_table).values([data2]).execute());
    assert!(result2.is_err()); // Should fail due to unique constraint
}

#[drizzle::test]
fn test_compile_time_defaults(db: &mut TestDb<CompileTimeDefaultsSchema>) {
    let defaults_table = schema.compile_defaults;

    // Insert with minimal data - defaults should be used
    let data = InsertCompileTimeDefaults::new();

    let result = db.insert(defaults_table).values([data]).execute();
    assert_eq!(result, 1);

    // Verify compile-time defaults were applied
    let select_query = db
        .select((
            defaults_table.name,
            defaults_table.answer,
            defaults_table.pi,
            defaults_table.active,
            defaults_table.status,
        ))
        .from(defaults_table)
        .r#where(eq(defaults_table.id, 1));

    #[derive(SQLiteFromRow, Debug)]
    struct ReturnResult(String, i32, f64, bool, String);
    let results: Vec<ReturnResult> = db.all(select_query);

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, "default_name");
    assert_eq!(results[0].1, 42);
    assert!((results[0].2 - 3.14).abs() < f64::EPSILON);
    assert!(results[0].3);
    assert_eq!(results[0].4, "pending");
}

#[drizzle::test]
fn test_runtime_defaults(db: &mut TestDb<RuntimeDefaultsSchema>) {
    let RuntimeDefaultsSchema { runtime_defaults } = schema;

    // Insert with minimal data - runtime defaults should be used
    let data = InsertRuntimeDefaults::new("test");

    let result = db.insert(runtime_defaults).values([data]).execute();
    assert_eq!(result, 1);

    // Verify runtime defaults were applied
    let select_query = db
        .select((
            runtime_defaults.empty_text,
            runtime_defaults.computed_int,
            runtime_defaults.name,
        ))
        .from(runtime_defaults)
        .r#where(eq(runtime_defaults.id, 1));

    #[derive(SQLiteFromRow, Debug)]
    struct ReturnResult(String, i32, String);
    let results: Vec<ReturnResult> = db.all(select_query);

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, ""); // String::new() returns empty string
    assert_eq!(results[0].1, 100); // Closure returns 100
    assert_eq!(results[0].2, "test");
}

#[drizzle::test]
fn test_enum_storage_types(db: &mut TestDb<EnumFieldsSchema>) {
    let enum_table = schema.enum_fields;

    // Test different enum storage types
    let data = InsertEnumFields::new(Priority::High, TaskStatus::InProgress, "Test task");

    let result = db.insert(enum_table).values([data]).execute();
    assert_eq!(result, 1);

    // Verify enum storage using typeof helper
    let priority_col = enum_table.priority;
    let status_col = enum_table.status;
    let select_query = db
        .select((
            priority_col,
            status_col,
            alias(r#typeof(priority_col), "priority_type"),
            alias(r#typeof(status_col), "status_type"),
        ))
        .from(enum_table)
        .r#where(eq(enum_table.id, 1));

    #[derive(SQLiteFromRow, Debug)]
    struct ReturnResult(i32, String, String, String);
    let results: Vec<ReturnResult> = db.all(select_query);

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, 3); // Priority::High = 3
    assert_eq!(results[0].1, "InProgress"); // TaskStatus::InProgress as text
    assert_eq!(results[0].2, "integer"); // integer(enum) stores as INTEGER
    assert_eq!(results[0].3, "text"); // text(enum) stores as TEXT
}

// Verify full SelectEnumFields round-trip: INTEGER enum (Priority) and TEXT enum (TaskStatus)
// are correctly deserialized back to their Rust enum types.
#[drizzle::test]
fn test_enum_full_round_trip(db: &mut TestDb<EnumFieldsSchema>) {
    let enum_table = schema.enum_fields;

    // Insert all variants of both enums
    let data = vec![
        InsertEnumFields::new(Priority::High, TaskStatus::Done, "urgent"),
        InsertEnumFields::new(Priority::Medium, TaskStatus::InProgress, "normal"),
        InsertEnumFields::new(Priority::Low, TaskStatus::Todo, "backlog"),
    ];
    db.insert(enum_table).values(data).execute();

    // Full select returning SelectEnumFields (includes both enum columns)
    let results: Vec<SelectEnumFields> = db
        .select(())
        .from(enum_table)
        .order_by(asc(enum_table.id))
        .all();
    assert_eq!(results.len(), 3);

    // Verify INTEGER-stored enum (Priority) round-trips correctly
    assert_eq!(results[0].priority, Priority::High);
    assert_eq!(results[1].priority, Priority::Medium);
    assert_eq!(results[2].priority, Priority::Low);

    // Verify TEXT-stored enum (TaskStatus) round-trips correctly
    assert_eq!(results[0].status, TaskStatus::Done);
    assert_eq!(results[1].status, TaskStatus::InProgress);
    assert_eq!(results[2].status, TaskStatus::Todo);
}

// Verify enum WHERE conditions work with both INTEGER and TEXT storage.
#[drizzle::test]
fn test_enum_where_conditions(db: &mut TestDb<EnumFieldsSchema>) {
    let enum_table = schema.enum_fields;

    let data = vec![
        InsertEnumFields::new(Priority::High, TaskStatus::Done, "task 1"),
        InsertEnumFields::new(Priority::High, TaskStatus::Todo, "task 2"),
        InsertEnumFields::new(Priority::Low, TaskStatus::Done, "task 3"),
    ];
    db.insert(enum_table).values(data).execute();

    // Filter by INTEGER enum
    let results: Vec<SelectEnumFields> = db
        .select(())
        .from(enum_table)
        .r#where(eq(enum_table.priority, Priority::High))
        .all();
    assert_eq!(results.len(), 2);
    assert!(results.iter().all(|r| r.priority == Priority::High));

    // Filter by TEXT enum
    let results: Vec<SelectEnumFields> = db
        .select(())
        .from(enum_table)
        .r#where(eq(enum_table.status, TaskStatus::Done))
        .all();
    assert_eq!(results.len(), 2);
    assert!(results.iter().all(|r| r.status == TaskStatus::Done));
}

#[cfg(feature = "serde")]
#[drizzle::test]
fn test_json_storage_types(db: &mut TestDb<JsonFieldsSchema>) {
    let json_table = schema.json_fields;

    let json_data = JsonData {
        value: 42,
        message: "Hello JSON".to_string(),
    };

    let data = InsertJsonFields::new("regular").with_text_json(json_data);

    let result = db.insert(json_table).values([data]).execute();

    assert_eq!(result, 1);

    // Verify JSON storage type
    let text_json_col = json_table.text_json;
    let select_query = db
        .select(alias(r#typeof(text_json_col), "text_type"))
        .from(json_table)
        .r#where(eq(json_table.id, 1));

    #[derive(SQLiteFromRow, Debug)]
    struct ReturnResult(String);
    let results: Vec<ReturnResult> = db.all(select_query);

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].0, "text"); // text(json) stores as TEXT
}

#[cfg(feature = "uuid")]
#[drizzle::test]
fn test_uuid_primary_key_with_default_fn(db: &mut TestDb<UuidFieldsSchema>) {
    let uuid_table = schema.uuid_fields;

    // Insert without specifying UUID - default_fn should generate one
    let data = InsertUuidFields::new("uuid test");

    let result = db.insert(uuid_table).values([data]).execute();

    assert_eq!(result, 1);

    // Verify UUID was generated and is valid
    let select_query = db
        .select((uuid_table.id, uuid_table.name))
        .from(uuid_table)
        .r#where(eq(uuid_table.name, "uuid test"));

    #[derive(SQLiteFromRow, Debug)]
    struct ReturnResult(uuid::Uuid, String);
    let results: Vec<ReturnResult> = db.all(select_query);

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].1, "uuid test");

    // Validate UUID format and version
    let generated_uuid = results[0].0;
    assert_ne!(generated_uuid, uuid::Uuid::nil());
    assert_eq!(generated_uuid.get_version(), Some(uuid::Version::Random));

    // Verify UUID storage type using typeof
    let id_col = uuid_table.id;
    let type_query = db
        .select(alias(r#typeof(id_col), "id_type"))
        .from(uuid_table)
        .r#where(eq(uuid_table.name, "uuid test"));

    #[derive(SQLiteFromRow, Debug)]
    struct TypeResult(String);
    let type_results: Vec<TypeResult> = db.all(type_query);

    assert_eq!(type_results.len(), 1);
    assert_eq!(type_results[0].0, "blob"); // blob(primary) stores UUIDs as BLOB
}

#[drizzle::test]
fn test_nullable_vs_non_nullable(db: &mut TestDb<NullableTestSchema>) {
    let nullable_table = schema.nullable_test;

    // Test 1: Insert with all required fields, no optional fields
    let minimal_data = InsertNullableTest::new("required", 123, true);

    let result = db.insert(nullable_table).values([minimal_data]).execute();

    assert_eq!(result, 1);

    // Test 2: Insert with all fields populated
    let full_data = InsertNullableTest::new("full", 456, false)
        .with_optional_text("optional text")
        .with_optional_int(789)
        .with_optional_real(12.34)
        .with_optional_blob([9, 8, 7])
        .with_optional_bool(true);

    let result = db.insert(nullable_table).values([full_data]).execute();

    assert_eq!(result, 1);

    // Verify both records using unified query approach
    let select_query = db
        .select((
            nullable_table.required_text,
            nullable_table.optional_text,
            nullable_table.optional_int,
        ))
        .from(nullable_table)
        .order_by(nullable_table.id);

    #[derive(SQLiteFromRow, Debug)]
    struct ReturnResult(String, Option<String>, Option<i32>);
    let results: Vec<ReturnResult> = db.all(select_query);

    assert_eq!(results.len(), 2);

    // First record: minimal data
    assert_eq!(results[0].0, "required");
    assert_eq!(results[0].1, None);
    assert_eq!(results[0].2, None);

    // Second record: full data
    assert_eq!(results[1].0, "full");
    assert_eq!(results[1].1, Some("optional text".to_string()));
    assert_eq!(results[1].2, Some(789));
}

#[test]
fn test_schema_generation() {
    // Test that all schema SQL generates without errors
    let _ = AllTypes::SQL;
    let _ = PrimaryKeyVariations::SQL;
    let _ = UniqueFields::SQL;
    let _ = CompileTimeDefaults::SQL;
    let _ = RuntimeDefaults::SQL;
    let _ = EnumFields::SQL;
    let _ = NullableTest::SQL;

    #[cfg(feature = "serde")]
    let _ = JsonFields::SQL;

    #[cfg(feature = "uuid")]
    let _ = UuidFields::SQL;

    // If we reach this point, all table definitions compiled and didn't panic.
}