bsql 0.8.0

Safe SQL for Rust — if it compiles, the SQL is correct
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
//! v0.2 integration tests: feature-gated types and pg_enum.
//!
//! These tests require specific features. Run with:
//!   BSQL_DATABASE_URL=postgres://bsql:bsql@localhost/bsql_test \
//!     cargo test -p bsql --test types --features "time,uuid"

use bsql::Pool;

async fn pool() -> Pool {
    Pool::connect("postgres://bsql:bsql@localhost/bsql_test")
        .await
        .expect("Failed to connect to test database. Is PostgreSQL running?")
}

// ---------------------------------------------------------------------------
// pg_enum tests
// ---------------------------------------------------------------------------

#[bsql::pg_enum]
pub enum TicketStatus {
    #[sql("new")]
    New,
    #[sql("in_progress")]
    InProgress,
    #[sql("resolved")]
    Resolved,
    #[sql("closed")]
    Closed,
}

#[tokio::test]
async fn pg_enum_select_as_text() {
    // PG enum columns require ::text cast (EnumString was removed).
    let pool = pool().await;
    let id = 1i32;
    let ticket = bsql::query!("SELECT id, status::text AS status FROM tickets WHERE id = $id: i32")
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(ticket.id, 1);
    // ::text cast produces a computed column, so PG reports it as nullable
    assert_eq!(ticket.status.as_deref(), Some("new"));
}

#[tokio::test]
async fn pg_enum_display() {
    assert_eq!(format!("{}", TicketStatus::New), "new");
    assert_eq!(format!("{}", TicketStatus::InProgress), "in_progress");
    assert_eq!(format!("{}", TicketStatus::Resolved), "resolved");
    assert_eq!(format!("{}", TicketStatus::Closed), "closed");
}

#[tokio::test]
async fn pg_enum_equality() {
    assert_eq!(TicketStatus::New, TicketStatus::New);
    assert_ne!(TicketStatus::New, TicketStatus::Closed);
}

#[tokio::test]
async fn pg_enum_clone_copy() {
    // Prove Copy: use after move
    let status = TicketStatus::InProgress;
    let copied = status;
    assert_eq!(status, copied); // status still usable → Copy works

    // Prove Clone: function that requires Clone bound
    fn needs_clone<T: Clone>(v: &T) -> T {
        v.clone()
    }
    let cloned = needs_clone(&status);
    assert_eq!(status, cloned);
}

#[tokio::test]
async fn pg_enum_debug() {
    assert_eq!(format!("{:?}", TicketStatus::Resolved), "Resolved");
}

// ---------------------------------------------------------------------------
// UUID tests (feature = "uuid")
// ---------------------------------------------------------------------------

#[cfg(feature = "uuid")]
mod uuid_tests {
    use super::*;

    #[tokio::test]
    async fn select_uuid_column() {
        let pool = pool().await;
        let id = 1i32;
        let ticket = bsql::query!("SELECT id, ticket_uuid FROM tickets WHERE id = $id: i32")
            .fetch_one(&pool)
            .await
            .unwrap();

        assert_eq!(ticket.id, 1);
        // UUID was generated by gen_random_uuid() — just verify it's valid
        let _uuid: uuid::Uuid = ticket.ticket_uuid;
    }

    #[tokio::test]
    async fn uuid_round_trip() {
        let pool = pool().await;
        let test_uuid = uuid::Uuid::new_v4();
        let title = "UUID round-trip test";
        let uid = 1i32;

        // Insert with explicit UUID
        let ticket = bsql::query!(
            "INSERT INTO tickets (title, status, created_by_user_id, ticket_uuid)
             VALUES ($title: &str, 'new', $uid: i32, $test_uuid: uuid::Uuid)
             RETURNING id, ticket_uuid"
        )
        .fetch_one(&pool)
        .await
        .unwrap();

        assert_eq!(ticket.ticket_uuid, test_uuid);

        // Clean up
        let inserted_id = ticket.id;
        bsql::query!("DELETE FROM tickets WHERE id = $inserted_id: i32")
            .execute(&pool)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn uuid_param_filter() {
        let pool = pool().await;
        let id = 1i32;

        // First get the UUID of ticket 1
        let ticket = bsql::query!("SELECT id, ticket_uuid FROM tickets WHERE id = $id: i32")
            .fetch_one(&pool)
            .await
            .unwrap();

        let target_uuid = ticket.ticket_uuid;

        // Now query by UUID
        let found =
            bsql::query!("SELECT id FROM tickets WHERE ticket_uuid = $target_uuid: uuid::Uuid")
                .fetch_one(&pool)
                .await
                .unwrap();

        assert_eq!(found.id, 1);
    }
}

// ---------------------------------------------------------------------------
// Time tests (feature = "time")
// ---------------------------------------------------------------------------

#[cfg(feature = "time")]
mod time_tests {
    use super::*;

    #[tokio::test]
    async fn select_nullable_timestamptz() {
        // deadline is nullable TIMESTAMPTZ
        let pool = pool().await;
        let id = 1i32;
        let ticket = bsql::query!("SELECT id, deadline FROM tickets WHERE id = $id: i32")
            .fetch_one(&pool)
            .await
            .unwrap();

        assert_eq!(ticket.id, 1);
        // Default is NULL
        assert!(ticket.deadline.is_none());
    }

    #[tokio::test]
    async fn timestamptz_round_trip() {
        let pool = pool().await;
        let now = time::OffsetDateTime::now_utc();
        let id = 1i32;

        // Set deadline
        bsql::query!(
            "UPDATE tickets SET deadline = $now: time::OffsetDateTime WHERE id = $id: i32"
        )
        .execute(&pool)
        .await
        .unwrap();

        // Read it back
        let ticket = bsql::query!("SELECT id, deadline FROM tickets WHERE id = $id: i32")
            .fetch_one(&pool)
            .await
            .unwrap();

        let deadline = ticket.deadline.expect("deadline should be set");
        // PostgreSQL stores microsecond precision, so we compare to within 1ms
        let diff = (deadline - now).whole_milliseconds().unsigned_abs();
        assert!(diff < 2, "timestamps differ by {diff}ms");

        // Clean up — set back to NULL
        bsql::query!("UPDATE tickets SET deadline = NULL WHERE id = $id: i32")
            .execute(&pool)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn select_date_column() {
        let pool = pool().await;
        let id = 1i32;
        let ticket = bsql::query!("SELECT id, created_date FROM tickets WHERE id = $id: i32")
            .fetch_one(&pool)
            .await
            .unwrap();

        assert_eq!(ticket.id, 1);
        // Should be today's date (or whenever setup.sql ran)
        let _date: time::Date = ticket.created_date;
    }

    #[tokio::test]
    async fn select_nullable_time_column() {
        let pool = pool().await;
        // Insert a fresh ticket with no start_time (NULL by default)
        let title = "nullable_time_test";
        let uid = 1i32;
        let ticket = bsql::query!(
            "INSERT INTO tickets (title, status, created_by_user_id)
             VALUES ($title: &str, 'new', $uid: i32)
             RETURNING id, start_time"
        )
        .fetch_one(&pool)
        .await
        .unwrap();

        assert!(ticket.id > 0);
        // start_time has no default → NULL
        assert!(ticket.start_time.is_none());
    }

    #[tokio::test]
    async fn time_round_trip() {
        let pool = pool().await;
        let t = time::Time::from_hms(14, 30, 0).expect("valid time");

        // Create own ticket to avoid interfering with other tests
        let title = "time_round_trip_test";
        let uid = 1i32;
        let ticket = bsql::query!(
            "INSERT INTO tickets (title, status, created_by_user_id, start_time)
             VALUES ($title: &str, 'new', $uid: i32, $t: time::Time)
             RETURNING id, start_time"
        )
        .fetch_one(&pool)
        .await
        .unwrap();

        let start_time = ticket.start_time.expect("start_time should be set");
        assert_eq!(start_time.hour(), 14);
        assert_eq!(start_time.minute(), 30);

        // Clean up — delete our test ticket
        let ticket_id = ticket.id;
        bsql::query!("DELETE FROM tickets WHERE id = $ticket_id: i32")
            .execute(&pool)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn date_param() {
        let pool = pool().await;
        let today = time::OffsetDateTime::now_utc().date();
        // Query tickets created today
        let tickets =
            bsql::query!("SELECT id FROM tickets WHERE created_date = $today: time::Date")
                .fetch_all(&pool)
                .await
                .unwrap();

        // All seed tickets were created today
        assert!(!tickets.is_empty());
    }
}

// ---------------------------------------------------------------------------
// Enum column as text (requires ::text cast)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn enum_column_cast_to_text() {
    let pool = pool().await;
    let id = 1i32;
    let ticket = bsql::query!("SELECT id, status::text AS status FROM tickets WHERE id = $id: i32")
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(ticket.id, 1);
    assert_eq!(ticket.status.as_deref(), Some("new"));
}

#[tokio::test]
async fn insert_with_enum_literal() {
    // PG accepts text literals for enum types
    let pool = pool().await;
    let title = "Enum literal test";
    let uid = 1i32;
    let ticket = bsql::query!(
        "INSERT INTO tickets (title, status, created_by_user_id)
         VALUES ($title: &str, 'resolved', $uid: i32)
         RETURNING id, status::text AS status"
    )
    .fetch_one(&pool)
    .await
    .unwrap();

    assert_eq!(ticket.status.as_deref(), Some("resolved"));

    // Clean up
    let del_id = ticket.id;
    bsql::query!("DELETE FROM tickets WHERE id = $del_id: i32")
        .execute(&pool)
        .await
        .unwrap();
}

// ---------------------------------------------------------------------------
// Enum string parameter tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn enum_string_as_param() {
    let pool = pool().await;
    let status = "new";
    // Cast the enum column to text so &str param is accepted by PG.
    let tickets = bsql::query!("SELECT id FROM tickets WHERE status::text = $status: &str")
        .fetch_all(&pool)
        .await
        .unwrap();
    assert!(!tickets.is_empty());
}

// ---------------------------------------------------------------------------
// Chrono tests (feature = "chrono" without "time")
// ---------------------------------------------------------------------------

#[cfg(all(feature = "chrono", not(feature = "time")))]
mod chrono_tests {
    use super::*;

    #[tokio::test]
    async fn chrono_timestamptz_round_trip() {
        let pool = pool().await;
        let now = chrono::Utc::now();
        let id = 1i32;

        // Set deadline using chrono
        bsql::query!(
            "UPDATE tickets SET deadline = $now: chrono::DateTime<chrono::Utc> WHERE id = $id: i32"
        )
        .execute(&pool)
        .await
        .unwrap();

        // Read it back
        let ticket = bsql::query!("SELECT id, deadline FROM tickets WHERE id = $id: i32")
            .fetch_one(&pool)
            .await
            .unwrap();

        let deadline = ticket.deadline.expect("deadline should be set");
        let diff = (deadline - now).num_milliseconds().unsigned_abs();
        assert!(diff < 2, "timestamps differ by {diff}ms");

        // Clean up
        bsql::query!("UPDATE tickets SET deadline = NULL WHERE id = $id: i32")
            .execute(&pool)
            .await
            .unwrap();
    }
}

// ---------------------------------------------------------------------------
// Decimal tests (feature = "decimal")
// ---------------------------------------------------------------------------

#[cfg(feature = "decimal")]
mod decimal_tests {
    use super::*;

    #[tokio::test]
    async fn decimal_round_trip() {
        let pool = pool().await;
        let budget = rust_decimal::Decimal::new(12345, 2); // 123.45
        let id = 1i32;

        // Set budget
        bsql::query!(
            "UPDATE tickets SET budget = $budget: rust_decimal::Decimal WHERE id = $id: i32"
        )
        .execute(&pool)
        .await
        .unwrap();

        // Read it back
        let ticket = bsql::query!("SELECT id, budget FROM tickets WHERE id = $id: i32")
            .fetch_one(&pool)
            .await
            .unwrap();

        assert_eq!(ticket.id, 1);
        let read_budget = ticket.budget.expect("budget should be set");
        assert_eq!(read_budget, budget);

        // Clean up -- set back to NULL
        bsql::query!("UPDATE tickets SET budget = NULL WHERE id = $id: i32")
            .execute(&pool)
            .await
            .unwrap();
    }
}