njord-rs / njord

A versatile, feature-rich Rust ORM ⛵
https://njord.rs
BSD 3-Clause "New" or "Revised" License
410 stars 21 forks source link

Create custom field type: PrimaryKey #74

Closed mjovanc closed 1 month ago

mjovanc commented 6 months ago

Just thinking of creating a custom field type called PrimaryKey to add to a field for example id: https://github.com/njord-rs/njord/blob/master/njord/tests/sqlite_test.rs#L15

Some example implementation:

pub struct PrimaryKey<T>(Option<T>);

impl<T> PrimaryKey<T> {
    pub fn new(value: Option<T>) -> Self {
        PrimaryKey(value)
    }

    pub fn get(&self) -> Option<&T> {
        self.0.as_ref()
    }
}

impl<T> Default for PrimaryKey<T> {
    fn default() -> Self {
        PrimaryKey(None)
    }
}

Usage example:

let table_row: User = User {
    id: PrimaryKey::default(),
    username: "mjovanc".to_string(),
    email: "mjovanc@icloud.com".to_string(),
    address: "Some Random Address 1".to_string(),
};

When setting it to ::default we are saying that we want the database to increment the id field automatically using autoincrement.