ruskit 0.1.5

A modern web framework for Rust inspired by Laravel
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
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};
use sqlx::{FromRow, sqlite::SqliteRow};
use crate::framework::database::{get_pool, DatabaseError};
use crate::framework::database::migration::Migration;
use std::sync::Mutex;
use std::collections::HashMap;
use once_cell::sync::Lazy;
use std::fs;
use std::path::Path;
use serde_json::Value;
use std::marker::PhantomData;
use validator::ValidationError;
use regex::Regex;
use paste;

type MigrationFn = fn() -> Vec<Migration>;

static MODEL_REGISTRY: Lazy<Mutex<HashMap<String, MigrationFn>>> = Lazy::new(|| Mutex::new(HashMap::new()));

pub fn register_model_with_migrations(model_name: String, migrations_fn: MigrationFn) {
    MODEL_REGISTRY.lock().unwrap().insert(model_name, migrations_fn);
}

pub fn get_all_model_migrations() -> Vec<Migration> {
    let registry = MODEL_REGISTRY.lock().unwrap();
    let mut migrations = Vec::new();
    
    for migrations_fn in registry.values() {
        migrations.extend(migrations_fn());
    }
    
    // Sort migrations by timestamp prefix to ensure chronological order
    migrations.sort_by(|a, b| {
        let a_timestamp = a.name.split('_').next().unwrap_or("0")
            .parse::<u64>().unwrap_or(0);
        let b_timestamp = b.name.split('_').next().unwrap_or("0")
            .parse::<u64>().unwrap_or(0);
        a_timestamp.cmp(&b_timestamp)
    });
    
    migrations
}

/// Automatically discover and register all models in the models directory
pub fn discover_and_register_models() -> std::io::Result<()> {
    let models_dir = Path::new("src/app/models");
    if !models_dir.exists() {
        return Ok(());
    }

    // Read all entries in the models directory
    for entry in fs::read_dir(models_dir)? {
        let entry = entry?;
        let path = entry.path();
        
        // Skip mod.rs and non-rust files
        if path.is_file() && 
           path.extension().map_or(false, |ext| ext == "rs") && 
           path.file_name().map_or(false, |name| name != "mod.rs") {
            // Get the model name from the file name
            if let Some(model_name) = path.file_stem().and_then(|s| s.to_str()) {
                // Convert to PascalCase for the struct name
                let model_name = model_name.chars().next().unwrap_or('_').to_uppercase().to_string() + 
                               &model_name[1..];
                let full_type_name = format!("ruskit::app::models::{}", model_name);
                
                // The model will register itself when it's used
                println!("Discovered model: {}", full_type_name);
            }
        }
    }
    
    Ok(())
}

pub struct BelongsTo<Parent: Model> {
    parent_type: PhantomData<Parent>,
    foreign_key: String,
}

pub struct HasMany<Child: Model> {
    child_type: PhantomData<Child>,
    foreign_key: String,
}

pub struct HasOne<Parent: Model, Child: Model> {
    parent_type: PhantomData<Parent>,
    child_type: PhantomData<Child>,
    foreign_key: &'static str,
}

impl<Parent: Model> BelongsTo<Parent> {
    pub fn new<Child: Model>() -> Self {
        // Get the parent table name and remove trailing 's' if present
        let parent_table = Parent::table_name();
        let singular = if parent_table.ends_with('s') {
            &parent_table[..parent_table.len() - 1]
        } else {
            parent_table
        };
        
        // Construct foreign key (e.g., "user_id" from "users")
        let foreign_key = format!("{}_id", singular);
        
        Self {
            parent_type: PhantomData,
            foreign_key,
        }
    }

    pub fn with_key(foreign_key: impl Into<String>) -> Self {
        Self {
            parent_type: PhantomData,
            foreign_key: foreign_key.into(),
        }
    }

    pub async fn get(&self, model: &impl Model) -> Result<Option<Parent>, DatabaseError> {
        let foreign_key_value = model.get_field_value(&self.foreign_key)?;
        Parent::find(foreign_key_value).await
    }
}

impl<Child: Model> HasMany<Child> {
    pub fn new<Parent: Model>() -> Self {
        // Get the parent table name and remove trailing 's' if present
        let parent_table = Parent::table_name();
        let singular = if parent_table.ends_with('s') {
            &parent_table[..parent_table.len() - 1]
        } else {
            parent_table
        };
        
        // Construct foreign key (e.g., "user_id" from "users")
        let foreign_key = format!("{}_id", singular);
        
        Self {
            child_type: PhantomData,
            foreign_key,
        }
    }

    pub fn with_key(foreign_key: impl Into<String>) -> Self {
        Self {
            child_type: PhantomData,
            foreign_key: foreign_key.into(),
        }
    }

    pub async fn get(&self, model: &impl Model) -> Result<Vec<Child>, DatabaseError> {
        let pool = get_pool()?;
        let query = format!(
            "SELECT * FROM {} WHERE {} = ?",
            Child::table_name(),
            self.foreign_key
        );
        
        let results = sqlx::query_as::<sqlx::Sqlite, Child>(&query)
            .bind(model.id())
            .fetch_all(pool.as_ref())
            .await?;
            
        Ok(results)
    }

    pub async fn create(&self, mut model: Child) -> Result<Child, DatabaseError> {
        let pool = get_pool()?;
        let query = format!(
            "UPDATE {} SET {} = ? WHERE id = ?",
            Child::table_name(),
            self.foreign_key
        );
        
        let created = Child::create(model).await?;
        sqlx::query(&query)
            .bind(created.id())
            .execute(pool.as_ref())
            .await?;
            
        Ok(created)
    }
}

impl<Parent: Model, Child: Model> HasOne<Parent, Child> {
    pub fn new(foreign_key: &'static str) -> Self {
        Self {
            parent_type: PhantomData,
            child_type: PhantomData,
            foreign_key,
        }
    }

    pub async fn get(&self, model: &Parent) -> Result<Option<Child>, DatabaseError> {
        let pool = get_pool()?;
        let query = format!(
            "SELECT * FROM {} WHERE {} = ? LIMIT 1",
            Child::table_name(),
            self.foreign_key
        );
        
        let result = sqlx::query_as::<sqlx::Sqlite, Child>(&query)
            .bind(model.id())
            .fetch_optional(pool.as_ref())
            .await?;
            
        Ok(result)
    }
}

// Validation rules
#[derive(Clone)]
pub enum Rule {
    Required,
    Email,
    MinLength(usize),
    MaxLength(usize),
    Regex(String),
}

pub struct Rules(Vec<Rule>);

impl Rules {
    pub fn new() -> Self {
        Self(Vec::new())
    }

    pub fn required(mut self) -> Self {
        self.0.push(Rule::Required);
        self
    }

    pub fn email(mut self) -> Self {
        self.0.push(Rule::Email);
        self
    }

    pub fn min(mut self, length: usize) -> Self {
        self.0.push(Rule::MinLength(length));
        self
    }

    pub fn max(mut self, length: usize) -> Self {
        self.0.push(Rule::MaxLength(length));
        self
    }

    pub fn regex(mut self, pattern: &str) -> Self {
        self.0.push(Rule::Regex(pattern.to_string()));
        self
    }
}

impl Rule {
    fn validate(&self, field: &str, value: &str) -> Result<(), ValidationError> {
        match self {
            Rule::Required => {
                if value.trim().is_empty() {
                    return Err(ValidationError::new("required field"));
                }
            }
            Rule::Email => {
                let email_regex = Regex::new(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$").unwrap();
                if !email_regex.is_match(value) {
                    return Err(ValidationError::new("invalid email format"));
                }
            }
            Rule::MinLength(min) => {
                if value.len() < *min {
                    return Err(ValidationError::new("too short"));
                }
            }
            Rule::MaxLength(max) => {
                if value.len() > *max {
                    return Err(ValidationError::new("too long"));
                }
            }
            Rule::Regex(pattern) => {
                let regex = Regex::new(pattern).unwrap();
                if !regex.is_match(value) {
                    return Err(ValidationError::new("invalid format"));
                }
            }
        }
        Ok(())
    }
}

pub struct Field<T> {
    name: &'static str,
    _type: PhantomData<T>,
}

impl<T> Field<T> {
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            _type: PhantomData,
        }
    }
}

pub trait Validate {
    fn validate(&self, rules: Rules) -> Result<(), ValidationError>;
}

impl Validate for String {
    fn validate(&self, rules: Rules) -> Result<(), ValidationError> {
        for rule in rules.0 {
            rule.validate(self, self.as_str())?;
        }
        Ok(())
    }
}

/// Trait for custom validation rules
pub trait ValidationRules {
    fn validate_rules(&self) -> Result<(), ValidationError> {
        Ok(())
    }
}

/// Trait for defining model-specific validation rules
pub trait ModelValidation: Sized {
    type Fields;
    
    fn fields() -> Self::Fields;
    
    fn validate(&self) -> Result<(), ValidationError> where Self: ValidationRules {
        self.validate_rules()
    }
}

#[async_trait]
pub trait Model: for<'r> FromRow<'r, SqliteRow> + Serialize + DeserializeOwned + Send + Sync + Sized + Unpin + ModelValidation + ValidationRules {
    /// Get the table name for the model
    fn table_name() -> &'static str;

    /// Get the primary key name (defaults to "id")
    fn primary_key() -> &'static str {
        "id"
    }

    /// Get the model's ID
    fn id(&self) -> i64;

    /// Get the migrations for this model
    fn migrations() -> Vec<Migration>;

    /// Register this model in the registry
    fn register() {
        register_model_with_migrations(
            std::any::type_name::<Self>().to_string(),
            Self::migrations
        );
    }

    /// Find a model by its primary key
    async fn find(id: i64) -> Result<Option<Self>, DatabaseError> {
        let pool = get_pool()?;
        let query = format!(
            "SELECT * FROM {} WHERE {} = ?",
            Self::table_name(),
            Self::primary_key()
        );
        
        let result = sqlx::query_as::<sqlx::Sqlite, Self>(&query)
            .bind(id)
            .fetch_optional(pool.as_ref())
            .await?;
            
        Ok(result)
    }

    /// Get all records
    async fn all() -> Result<Vec<Self>, DatabaseError> {
        let pool = get_pool()?;
        let query = format!("SELECT * FROM {}", Self::table_name());
        
        let results = sqlx::query_as::<sqlx::Sqlite, Self>(&query)
            .fetch_all(pool.as_ref())
            .await?;
            
        Ok(results)
    }

    /// Create a new record
    async fn create(model: Self) -> Result<Self, DatabaseError> {
        println!("Creating new record...");
        let pool = get_pool()?;
        println!("Got database pool successfully");
        
        // Convert the model to a JSON Value for field extraction
        let data = serde_json::to_value(&model)?;
        let obj = data.as_object().unwrap();
        
        // Filter out the id field since it's auto-generated
        let columns: Vec<String> = obj.keys()
            .filter(|&k| k != "id")
            .cloned()
            .collect();
            
        let placeholders: Vec<String> = (1..=columns.len()).map(|_| "?".to_string()).collect();

        // Create the insert query
        let insert_query = format!(
            "INSERT INTO {} ({}) VALUES ({})",
            Self::table_name(),
            columns.join(", "),
            placeholders.join(", ")
        );

        println!("Executing query: {}", insert_query);
        println!("With values: {:?}", obj);

        // Start a transaction
        let mut tx = pool.begin().await?;

        // Build and execute the insert query
        let mut query_builder = sqlx::query::<sqlx::Sqlite>(&insert_query);
        for column in &columns {
            if let Some(value) = obj.get(column) {
                match value {
                    Value::Number(n) => {
                        if let Some(i) = n.as_i64() {
                            query_builder = query_builder.bind(i);
                        } else if let Some(f) = n.as_f64() {
                            query_builder = query_builder.bind(f);
                        }
                    },
                    Value::String(s) => {
                        // Get the raw string value without JSON escaping
                        let raw_string = s.as_str();
                        query_builder = query_builder.bind(raw_string);
                    },
                    Value::Bool(b) => query_builder = query_builder.bind(b),
                    Value::Null => query_builder = query_builder.bind(None::<String>),
                    _ => return Err(DatabaseError::Other(format!("Unsupported value type for column {}: {:?}", column, value))),
                }
            }
        }

        // Execute the insert
        let result = query_builder.execute(&mut *tx).await?;

        // Get the ID of the inserted row
        let id: i64 = result.last_insert_rowid();


        // Commit the transaction
        tx.commit().await?;

        // Log the result of the insert
        println!("Insert result: {:?}", result.last_insert_rowid());
        println!("Insert result: {:?}", result.rows_affected());
       
        

        // Fetch the created record
        let row = sqlx::query_as::<sqlx::Sqlite, Self>(&format!(
            "SELECT * FROM {} WHERE {} = ?",
            Self::table_name(),
            Self::primary_key()
        ))
        .bind(id)
        .fetch_one(pool.as_ref())
        .await?;

        Ok(row)
    }

    /// Get a field value by name (used for relationships)
    fn get_field_value(&self, field: &str) -> Result<i64, DatabaseError> {
        let value = serde_json::to_value(self)?;
        value.get(field)
            .and_then(|v| v.as_i64())
            .ok_or_else(|| DatabaseError::Other(format!("Field {} not found or invalid type", field)))
    }

    /// Create a new record with validation
    async fn create_validated(model: Self) -> Result<Self, DatabaseError> {
        model.validate().map_err(|e| DatabaseError::Other(e.to_string()))?;
        Self::create(model).await
    }
}

#[macro_export]
macro_rules! define_fields {
    ($name:ident { $($field:ident: $type:ty),* $(,)? }) => {
        pub struct $name {
            $(pub $field: Field<$type>,)*
        }

        impl $name {
            pub fn new() -> Self {
                Self {
                    $($field: Field::new(stringify!($field)),)*
                }
            }
        }
    };
}

#[macro_export]
macro_rules! generate_validation_fields {
    ($model:ident) => {
        paste::paste! {
            pub struct [<$model Fields>] {
                $(pub $field: Field<$type>,)*
            }

            impl [<$model Fields>] {
                pub fn new() -> Self {
                    Self {
                        $(pub $field: Field::new(stringify!($field)),)*
                    }
                }
            }

            impl ModelValidation for $model {
                type Fields = [<$model Fields>];

                fn fields() -> Self::Fields {
                    [<$model Fields>]::new()
                }
            }
        }
    };
}