prax-orm 0.6.5

A next-generation, type-safe ORM for Rust inspired by Prisma
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
#![allow(dead_code, unused, clippy::type_complexity)]
//! # Raw SQL Examples
//!
//! This example demonstrates raw SQL capabilities in Prax:
//! - Simple raw queries
//! - Parameterized queries
//! - Type-safe parameter binding
//! - Raw execute for mutations
//! - SQL interpolation safety
//!
//! ## Running this example
//!
//! ```bash
//! cargo run --example raw_sql
//! ```

use std::collections::HashMap;

// Mock types for demonstration
#[derive(Debug, Clone, Default)]
struct User {
    id: i32,
    email: String,
    name: Option<String>,
}

#[derive(Debug, Clone, Default)]
struct UserStats {
    total_users: i64,
    active_users: i64,
    new_this_month: i64,
}

// Raw SQL builder
struct Sql {
    query: String,
    params: Vec<SqlParam>,
}

#[derive(Debug, Clone)]
enum SqlParam {
    Int(i32),
    BigInt(i64),
    Float(f64),
    String(String),
    Bool(bool),
    Null,
    IntArray(Vec<i32>),
    StringArray(Vec<String>),
}

impl Sql {
    fn new(query: impl Into<String>) -> Self {
        Self {
            query: query.into(),
            params: Vec::new(),
        }
    }

    fn bind<T: IntoSqlParam>(mut self, value: T) -> Self {
        self.params.push(value.into_sql_param());
        self
    }

    fn query(&self) -> &str {
        &self.query
    }

    fn params(&self) -> &[SqlParam] {
        &self.params
    }
}

trait IntoSqlParam {
    fn into_sql_param(self) -> SqlParam;
}

impl IntoSqlParam for i32 {
    fn into_sql_param(self) -> SqlParam {
        SqlParam::Int(self)
    }
}

impl IntoSqlParam for i64 {
    fn into_sql_param(self) -> SqlParam {
        SqlParam::BigInt(self)
    }
}

impl IntoSqlParam for f64 {
    fn into_sql_param(self) -> SqlParam {
        SqlParam::Float(self)
    }
}

impl IntoSqlParam for &str {
    fn into_sql_param(self) -> SqlParam {
        SqlParam::String(self.to_string())
    }
}

impl IntoSqlParam for String {
    fn into_sql_param(self) -> SqlParam {
        SqlParam::String(self)
    }
}

impl IntoSqlParam for bool {
    fn into_sql_param(self) -> SqlParam {
        SqlParam::Bool(self)
    }
}

impl<T: IntoSqlParam> IntoSqlParam for Option<T> {
    fn into_sql_param(self) -> SqlParam {
        match self {
            Some(v) => v.into_sql_param(),
            None => SqlParam::Null,
        }
    }
}

impl IntoSqlParam for Vec<i32> {
    fn into_sql_param(self) -> SqlParam {
        SqlParam::IntArray(self)
    }
}

impl IntoSqlParam for Vec<String> {
    fn into_sql_param(self) -> SqlParam {
        SqlParam::StringArray(self)
    }
}

// Mock client
struct MockClient;

impl MockClient {
    async fn query_raw<T>(&self, sql: Sql) -> Result<Vec<T>, Box<dyn std::error::Error>>
    where
        T: Default,
    {
        println!("  Executing: {}", sql.query());
        println!("  Parameters: {:?}", sql.params());
        Ok(vec![])
    }

    async fn query_raw_one<T>(&self, sql: Sql) -> Result<Option<T>, Box<dyn std::error::Error>>
    where
        T: Default,
    {
        println!("  Executing: {}", sql.query());
        println!("  Parameters: {:?}", sql.params());
        Ok(None)
    }

    async fn execute_raw(&self, sql: Sql) -> Result<u64, Box<dyn std::error::Error>> {
        println!("  Executing: {}", sql.query());
        println!("  Parameters: {:?}", sql.params());
        Ok(1)
    }
}

/// Macro for type-safe SQL with interpolation
macro_rules! raw_query {
    ($query:expr $(, $param:expr)*) => {{
        let sql = Sql::new($query);
        $(
            let sql = sql.bind($param);
        )*
        sql
    }};
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Prax Raw SQL Examples ===\n");

    let client = MockClient;

    // =========================================================================
    // SIMPLE RAW QUERY
    // =========================================================================
    println!("--- Simple Raw Query ---");

    let sql = Sql::new("SELECT * FROM users WHERE active = true ORDER BY created_at DESC");
    let _users: Vec<User> = client.query_raw(sql).await?;
    println!();

    // =========================================================================
    // PARAMETERIZED QUERY
    // =========================================================================
    println!("--- Parameterized Query ---");

    let sql = Sql::new("SELECT * FROM users WHERE id = $1").bind(42i32);
    let _user: Option<User> = client.query_raw_one(sql).await?;
    println!();

    // Multiple parameters
    println!("--- Multiple Parameters ---");

    let sql = Sql::new("SELECT * FROM users WHERE email = $1 AND active = $2")
        .bind("test@example.com")
        .bind(true);
    let _users: Vec<User> = client.query_raw(sql).await?;
    println!();

    // =========================================================================
    // USING THE MACRO
    // =========================================================================
    println!("--- Using raw_query! Macro ---");

    let email = "alice@example.com";
    let sql = raw_query!("SELECT * FROM users WHERE email = $1", email);
    let _users: Vec<User> = client.query_raw(sql).await?;
    println!();

    // Multiple parameters with macro
    println!("--- Macro with Multiple Parameters ---");

    let status = "active";
    let min_age = 18;
    let sql = raw_query!(
        "SELECT * FROM users WHERE status = $1 AND age >= $2",
        status,
        min_age
    );
    let _users: Vec<User> = client.query_raw(sql).await?;
    println!();

    // =========================================================================
    // ARRAY PARAMETERS
    // =========================================================================
    println!("--- Array Parameters ---");

    let ids = vec![1, 2, 3, 4, 5];
    let sql = Sql::new("SELECT * FROM users WHERE id = ANY($1)").bind(ids);
    let _users: Vec<User> = client.query_raw(sql).await?;
    println!();

    // =========================================================================
    // RAW EXECUTE (INSERT/UPDATE/DELETE)
    // =========================================================================
    println!("--- Raw Execute (Mutations) ---");

    // Insert
    let sql = Sql::new("INSERT INTO users (email, name, active) VALUES ($1, $2, $3)")
        .bind("new@example.com")
        .bind("New User")
        .bind(true);
    let affected = client.execute_raw(sql).await?;
    println!("  Rows affected: {}", affected);
    println!();

    // Update
    println!("--- Raw Update ---");
    let sql = Sql::new("UPDATE users SET active = $1 WHERE last_login < $2")
        .bind(false)
        .bind("2024-01-01");
    let affected = client.execute_raw(sql).await?;
    println!("  Rows affected: {}", affected);
    println!();

    // Delete
    println!("--- Raw Delete ---");
    let sql = Sql::new("DELETE FROM users WHERE deleted_at IS NOT NULL AND deleted_at < $1")
        .bind("2024-01-01");
    let affected = client.execute_raw(sql).await?;
    println!("  Rows affected: {}", affected);
    println!();

    // =========================================================================
    // COMPLEX QUERIES
    // =========================================================================
    println!("--- Complex Query with Joins ---");

    let sql = Sql::new(
        r#"
        SELECT u.id, u.email, COUNT(p.id) as post_count
        FROM users u
        LEFT JOIN posts p ON p.author_id = u.id
        WHERE u.active = $1
        GROUP BY u.id, u.email
        HAVING COUNT(p.id) >= $2
        ORDER BY post_count DESC
        LIMIT $3
    "#,
    )
    .bind(true)
    .bind(5i32)
    .bind(10i32);

    let _results: Vec<HashMap<String, String>> = client.query_raw(sql).await?;
    println!();

    // =========================================================================
    // AGGREGATE QUERIES
    // =========================================================================
    println!("--- Aggregate Query ---");

    let sql = Sql::new(
        r#"
        SELECT
            COUNT(*) as total_users,
            COUNT(*) FILTER (WHERE active = true) as active_users,
            COUNT(*) FILTER (WHERE created_at > NOW() - INTERVAL '30 days') as new_this_month
        FROM users
    "#,
    );

    let _stats: Option<UserStats> = client.query_raw_one(sql).await?;
    println!();

    // =========================================================================
    // NULL HANDLING
    // =========================================================================
    println!("--- NULL Parameter Handling ---");

    let name: Option<&str> = None;
    let sql = Sql::new("UPDATE users SET name = $1 WHERE id = $2")
        .bind(name)
        .bind(42i32);
    let _affected = client.execute_raw(sql).await?;
    println!();

    // =========================================================================
    // SQL INJECTION PREVENTION
    // =========================================================================
    println!("--- SQL Injection Prevention ---");

    println!("❌ NEVER do this (vulnerable to SQL injection):");
    println!("   let query = format!(\"SELECT * FROM users WHERE email = '{{}}'\", user_input);");
    println!();

    println!("✓ ALWAYS use parameterized queries:");
    let user_input = "alice@example.com'; DROP TABLE users; --";
    let sql = Sql::new("SELECT * FROM users WHERE email = $1").bind(user_input);
    println!("  Safe query with potentially malicious input:");
    let _users: Vec<User> = client.query_raw(sql).await?;
    println!();

    // =========================================================================
    // DATABASE-SPECIFIC FEATURES
    // =========================================================================
    println!("--- Database-Specific Features ---");

    // PostgreSQL JSON operations
    println!("PostgreSQL JSON query:");
    let sql = Sql::new(
        r#"
        SELECT * FROM users
        WHERE metadata->>'role' = $1
        AND (metadata->'permissions') @> $2::jsonb
    "#,
    )
    .bind("admin")
    .bind(r#"["write", "delete"]"#);
    let _users: Vec<User> = client.query_raw(sql).await?;
    println!();

    // Full-text search
    println!("PostgreSQL Full-text Search:");
    let sql = Sql::new(r#"
        SELECT * FROM posts
        WHERE to_tsvector('english', title || ' ' || content) @@ plainto_tsquery('english', $1)
        ORDER BY ts_rank(to_tsvector('english', title || ' ' || content), plainto_tsquery('english', $1)) DESC
    "#)
        .bind("rust async programming");
    let _posts: Vec<HashMap<String, String>> = client.query_raw(sql).await?;
    println!();

    // =========================================================================
    // UPSERT EXAMPLE
    // =========================================================================
    println!("--- Upsert (ON CONFLICT) ---");

    let sql = Sql::new(
        r#"
        INSERT INTO users (email, name, active)
        VALUES ($1, $2, $3)
        ON CONFLICT (email)
        DO UPDATE SET
            name = EXCLUDED.name,
            updated_at = NOW()
        RETURNING *
    "#,
    )
    .bind("alice@example.com")
    .bind("Alice Updated")
    .bind(true);
    let _user: Option<User> = client.query_raw_one(sql).await?;
    println!();

    // =========================================================================
    // CTE (Common Table Expressions)
    // =========================================================================
    println!("--- CTE (WITH clause) ---");

    let sql = Sql::new(
        r#"
        WITH active_users AS (
            SELECT * FROM users WHERE active = true
        ),
        user_post_counts AS (
            SELECT author_id, COUNT(*) as count
            FROM posts
            GROUP BY author_id
        )
        SELECT u.*, COALESCE(p.count, 0) as post_count
        FROM active_users u
        LEFT JOIN user_post_counts p ON u.id = p.author_id
        ORDER BY post_count DESC
        LIMIT $1
    "#,
    )
    .bind(10i32);
    let _results: Vec<HashMap<String, String>> = client.query_raw(sql).await?;
    println!();

    // =========================================================================
    // API REFERENCE
    // =========================================================================
    println!("--- API Reference ---");
    println!(
        r#"
Raw SQL API:

// Query returning multiple rows
let users: Vec<User> = client
    .query_raw(Sql::new("SELECT * FROM users WHERE active = $1")
        .bind(true))
    .await?;

// Query returning single row
let user: Option<User> = client
    .query_raw_one(Sql::new("SELECT * FROM users WHERE id = $1")
        .bind(user_id))
    .await?;

// Execute mutation (INSERT/UPDATE/DELETE)
let affected: u64 = client
    .execute_raw(Sql::new("DELETE FROM users WHERE id = $1")
        .bind(user_id))
    .await?;

// Using the macro
let users: Vec<User> = client
    .query_raw(raw_query!(
        "SELECT * FROM users WHERE email LIKE $1 AND age > $2",
        "%@example.com",
        18
    ))
    .await?;

Supported parameter types:
- i32, i64 (integers)
- f64 (floating point)
- &str, String (text)
- bool (boolean)
- Option<T> (nullable)
- Vec<i32>, Vec<String> (arrays)
- chrono::DateTime, chrono::NaiveDate (dates)
- uuid::Uuid (UUIDs)
- serde_json::Value (JSON)
"#
    );

    println!("=== All examples completed successfully! ===");

    Ok(())
}