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
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
#![allow(dead_code, unused, clippy::type_complexity)]
//! # Multi-Tenant Examples
//!
//! This example demonstrates multi-tenant support in Prax:
//! - Row-level tenant isolation
//! - Schema-based tenant isolation
//! - Database-per-tenant isolation
//! - Tenant middleware configuration
//! - Dynamic tenant resolution
//!
//! ## Running this example
//!
//! ```bash
//! cargo run --example multi_tenant
//! ```

use std::collections::HashMap;

// Tenant isolation strategies
#[derive(Debug, Clone)]
enum IsolationStrategy {
    /// All tenants share tables, filtered by tenant_id column
    RowLevel { tenant_column: String },
    /// Each tenant has a separate database schema
    Schema { schema_prefix: String },
    /// Each tenant has a separate database
    Database { url_template: String },
}

// Tenant context
#[derive(Debug, Clone)]
struct TenantContext {
    id: String,
    name: Option<String>,
    metadata: HashMap<String, String>,
}

impl TenantContext {
    fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: None,
            metadata: HashMap::new(),
        }
    }

    fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }
}

// Tenant configuration
struct TenantConfig {
    strategy: IsolationStrategy,
    default_tenant: Option<String>,
    require_tenant: bool,
}

impl TenantConfig {
    fn builder() -> TenantConfigBuilder {
        TenantConfigBuilder::default()
    }
}

#[derive(Default)]
struct TenantConfigBuilder {
    strategy: Option<IsolationStrategy>,
    default_tenant: Option<String>,
    require_tenant: bool,
}

impl TenantConfigBuilder {
    fn strategy(mut self, strategy: IsolationStrategy) -> Self {
        self.strategy = Some(strategy);
        self
    }

    fn default_tenant(mut self, tenant: impl Into<String>) -> Self {
        self.default_tenant = Some(tenant.into());
        self
    }

    fn require_tenant(mut self) -> Self {
        self.require_tenant = true;
        self
    }

    fn build(self) -> TenantConfig {
        TenantConfig {
            strategy: self.strategy.unwrap_or(IsolationStrategy::RowLevel {
                tenant_column: "tenant_id".to_string(),
            }),
            default_tenant: self.default_tenant,
            require_tenant: self.require_tenant,
        }
    }
}

// Tenant middleware
struct TenantMiddleware {
    config: TenantConfig,
}

impl TenantMiddleware {
    fn new(config: TenantConfig) -> Self {
        Self { config }
    }
}

// Tenant resolver trait
trait TenantResolver: Send + Sync {
    fn resolve(&self, request: &MockRequest) -> Option<TenantContext>;
}

// Header-based resolver
struct HeaderResolver {
    header_name: String,
}

impl HeaderResolver {
    fn new(header_name: impl Into<String>) -> Self {
        Self {
            header_name: header_name.into(),
        }
    }
}

impl TenantResolver for HeaderResolver {
    fn resolve(&self, request: &MockRequest) -> Option<TenantContext> {
        request
            .headers
            .get(&self.header_name)
            .map(|id| TenantContext::new(id.clone()))
    }
}

// Subdomain-based resolver
struct SubdomainResolver;

impl TenantResolver for SubdomainResolver {
    fn resolve(&self, request: &MockRequest) -> Option<TenantContext> {
        request.host.as_ref().and_then(|host| {
            let parts: Vec<&str> = host.split('.').collect();
            if parts.len() >= 2 {
                Some(TenantContext::new(parts[0].to_string()))
            } else {
                None
            }
        })
    }
}

// Mock request for demonstration
struct MockRequest {
    headers: HashMap<String, String>,
    host: Option<String>,
    path: String,
}

// Mock client with tenant support
struct TenantAwareClient {
    tenant: Option<TenantContext>,
    config: TenantConfig,
}

impl TenantAwareClient {
    fn new(config: TenantConfig) -> Self {
        Self {
            tenant: None,
            config,
        }
    }

    fn with_tenant(&self, tenant: impl Into<TenantContext>) -> Self {
        Self {
            tenant: Some(tenant.into()),
            config: TenantConfig {
                strategy: self.config.strategy.clone(),
                default_tenant: self.config.default_tenant.clone(),
                require_tenant: self.config.require_tenant,
            },
        }
    }

    fn user(&self) -> TenantUserQuery {
        TenantUserQuery {
            tenant: self.tenant.clone(),
            strategy: self.config.strategy.clone(),
        }
    }

    fn current_tenant(&self) -> Option<&TenantContext> {
        self.tenant.as_ref()
    }
}

impl From<String> for TenantContext {
    fn from(id: String) -> Self {
        TenantContext::new(id)
    }
}

impl From<&str> for TenantContext {
    fn from(id: &str) -> Self {
        TenantContext::new(id)
    }
}

#[derive(Debug, Clone)]
struct User {
    id: i32,
    email: String,
    tenant_id: String,
}

struct TenantUserQuery {
    tenant: Option<TenantContext>,
    strategy: IsolationStrategy,
}

impl TenantUserQuery {
    fn find_many(self) -> TenantUserFindMany {
        TenantUserFindMany {
            tenant: self.tenant,
            strategy: self.strategy,
        }
    }

    fn create(self, _data: CreateUserData) -> TenantUserCreate {
        TenantUserCreate {
            tenant: self.tenant,
            strategy: self.strategy,
        }
    }
}

struct TenantUserFindMany {
    tenant: Option<TenantContext>,
    strategy: IsolationStrategy,
}

impl TenantUserFindMany {
    async fn exec(self) -> Result<Vec<User>, Box<dyn std::error::Error>> {
        let tenant_id = self
            .tenant
            .as_ref()
            .map(|t| t.id.clone())
            .unwrap_or_else(|| "default".to_string());

        // Show how the query would be modified
        match &self.strategy {
            IsolationStrategy::RowLevel { tenant_column } => {
                println!(
                    "  [RowLevel] Adding WHERE {} = '{}'",
                    tenant_column, tenant_id
                );
            }
            IsolationStrategy::Schema { schema_prefix } => {
                println!("  [Schema] Using schema: {}_{}", schema_prefix, tenant_id);
            }
            IsolationStrategy::Database { url_template } => {
                println!(
                    "  [Database] Connecting to: {}",
                    url_template.replace("{tenant}", &tenant_id)
                );
            }
        }

        Ok(vec![
            User {
                id: 1,
                email: format!("user1@{}.example.com", tenant_id),
                tenant_id: tenant_id.clone(),
            },
            User {
                id: 2,
                email: format!("user2@{}.example.com", tenant_id),
                tenant_id,
            },
        ])
    }
}

struct CreateUserData {
    email: String,
}

struct TenantUserCreate {
    tenant: Option<TenantContext>,
    strategy: IsolationStrategy,
}

impl TenantUserCreate {
    async fn exec(self) -> Result<User, Box<dyn std::error::Error>> {
        let tenant_id = self
            .tenant
            .as_ref()
            .map(|t| t.id.clone())
            .unwrap_or_else(|| "default".to_string());

        match &self.strategy {
            IsolationStrategy::RowLevel { tenant_column } => {
                println!("  [RowLevel] Setting {} = '{}'", tenant_column, tenant_id);
            }
            IsolationStrategy::Schema { schema_prefix } => {
                println!(
                    "  [Schema] Inserting into: {}_{}.users",
                    schema_prefix, tenant_id
                );
            }
            IsolationStrategy::Database { .. } => {
                println!("  [Database] Inserting into tenant database");
            }
        }

        Ok(User {
            id: 3,
            email: format!("new@{}.example.com", tenant_id),
            tenant_id,
        })
    }
}

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

    // =========================================================================
    // ROW-LEVEL ISOLATION
    // =========================================================================
    println!("--- Row-Level Tenant Isolation ---");
    println!("All tenants share the same tables, filtered by tenant_id column.\n");

    let config = TenantConfig::builder()
        .strategy(IsolationStrategy::RowLevel {
            tenant_column: "tenant_id".to_string(),
        })
        .require_tenant()
        .build();

    let client = TenantAwareClient::new(config);

    // Set tenant context
    let tenant_client = client.with_tenant("acme-corp");

    println!("Querying users for tenant 'acme-corp':");
    let users = tenant_client.user().find_many().exec().await?;
    for user in &users {
        println!("  {} (tenant: {})", user.email, user.tenant_id);
    }
    println!();

    // Different tenant
    let other_tenant = client.with_tenant("other-corp");
    println!("Querying users for tenant 'other-corp':");
    let users = other_tenant.user().find_many().exec().await?;
    for user in &users {
        println!("  {} (tenant: {})", user.email, user.tenant_id);
    }
    println!();

    // =========================================================================
    // SCHEMA-BASED ISOLATION
    // =========================================================================
    println!("--- Schema-Based Tenant Isolation ---");
    println!("Each tenant has a separate database schema.\n");

    let schema_config = TenantConfig::builder()
        .strategy(IsolationStrategy::Schema {
            schema_prefix: "tenant".to_string(),
        })
        .build();

    let schema_client = TenantAwareClient::new(schema_config);
    let tenant_client = schema_client.with_tenant("acme");

    println!("Querying users in schema 'tenant_acme':");
    let _users = tenant_client.user().find_many().exec().await?;
    println!();

    // =========================================================================
    // DATABASE-PER-TENANT ISOLATION
    // =========================================================================
    println!("--- Database-Per-Tenant Isolation ---");
    println!("Each tenant has a separate database.\n");

    let db_config = TenantConfig::builder()
        .strategy(IsolationStrategy::Database {
            url_template: "postgresql://localhost/{tenant}_db".to_string(),
        })
        .build();

    let db_client = TenantAwareClient::new(db_config);
    let tenant_client = db_client.with_tenant("acme");

    println!("Querying users in database 'acme_db':");
    let _users = tenant_client.user().find_many().exec().await?;
    println!();

    // =========================================================================
    // TENANT RESOLUTION
    // =========================================================================
    println!("--- Tenant Resolution ---");

    // Header-based resolution
    println!("Header-based resolver (X-Tenant-ID):");
    let header_resolver = HeaderResolver::new("X-Tenant-ID");

    let request = MockRequest {
        headers: [("X-Tenant-ID".to_string(), "acme-corp".to_string())]
            .into_iter()
            .collect(),
        host: None,
        path: "/api/users".to_string(),
    };

    if let Some(tenant) = header_resolver.resolve(&request) {
        println!("  Resolved tenant: {}", tenant.id);
    }
    println!();

    // Subdomain-based resolution
    println!("Subdomain-based resolver:");
    let subdomain_resolver = SubdomainResolver;

    let request = MockRequest {
        headers: HashMap::new(),
        host: Some("acme.myapp.com".to_string()),
        path: "/api/users".to_string(),
    };

    if let Some(tenant) = subdomain_resolver.resolve(&request) {
        println!("  Resolved tenant from 'acme.myapp.com': {}", tenant.id);
    }
    println!();

    // =========================================================================
    // TENANT CONTEXT WITH METADATA
    // =========================================================================
    println!("--- Tenant Context with Metadata ---");

    let tenant = TenantContext::new("acme-corp")
        .with_name("Acme Corporation")
        .with_metadata("plan", "enterprise")
        .with_metadata("region", "us-west");

    println!(
        "Tenant: {} ({})",
        tenant.id,
        tenant.name.as_deref().unwrap_or("")
    );
    println!("Metadata:");
    for (key, value) in &tenant.metadata {
        println!("  {}: {}", key, value);
    }
    println!();

    // =========================================================================
    // CREATING RECORDS WITH TENANT
    // =========================================================================
    println!("--- Creating Records with Tenant Context ---");

    let row_config = TenantConfig::builder()
        .strategy(IsolationStrategy::RowLevel {
            tenant_column: "tenant_id".to_string(),
        })
        .build();

    let client = TenantAwareClient::new(row_config);
    let tenant_client = client.with_tenant("acme-corp");

    println!("Creating user for tenant 'acme-corp':");
    let user = tenant_client
        .user()
        .create(CreateUserData {
            email: "new@acme-corp.example.com".to_string(),
        })
        .exec()
        .await?;

    println!("  Created: {} (tenant: {})", user.email, user.tenant_id);
    println!();

    // =========================================================================
    // CONFIGURATION REFERENCE
    // =========================================================================
    println!("--- Configuration Reference ---");
    println!(
        r#"
Multi-tenant configuration in prax.toml:

```toml
[tenant]
# Enable multi-tenant support
enabled = true

# Isolation strategy: "row_level", "schema", or "database"
strategy = "row_level"

# Row-level isolation settings
[tenant.row_level]
tenant_column = "tenant_id"
auto_filter = true
auto_set = true

# Schema-based isolation settings
[tenant.schema]
schema_prefix = "tenant_"
create_on_demand = true

# Database-per-tenant settings
[tenant.database]
url_template = "postgresql://localhost/{{tenant}}_db"
pool_per_tenant = true
max_tenants_cached = 100

# Tenant resolution
[tenant.resolver]
type = "header"  # "header", "subdomain", "path", or "custom"
header_name = "X-Tenant-ID"

# Default tenant (optional)
default_tenant = "public"

# Require tenant for all queries
require_tenant = true
```

Usage in code:

```rust
use prax_orm::tenant::{{TenantConfig, IsolationStrategy}};

let config = TenantConfig::builder()
    .strategy(IsolationStrategy::RowLevel {{
        tenant_column: "tenant_id".into(),
    }})
    .require_tenant()
    .build();

let client = PraxClient::new(database_url)
    .await?
    .with_tenant_config(config);

// Set tenant for requests
let tenant_client = client.with_tenant("acme-corp");

// All queries are now scoped to this tenant
let users = tenant_client.user().find_many().exec().await?;
```
"#
    );

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

    Ok(())
}