rusticx-core 1.0.0

Core traits, types, and abstractions for the Rusticx multi-database ORM
Documentation
/// Describes one column in a table schema.
///
/// `ColumnDef` is produced by `#[derive(Model)]` from your struct fields
/// and consumed by each backend's `create_table` implementation to emit
/// the appropriate DDL (`CREATE TABLE` for SQL, `createCollection` + indexes
/// for MongoDB).
///
/// You rarely construct these manually unless you are implementing a custom
/// backend or building schemas programmatically.
#[derive(Debug, Clone)]
pub struct ColumnDef {
    pub name: String,
    pub col_type: ColumnType,
    pub nullable: bool,
    pub primary_key: bool,
    pub unique: bool,
    pub default: Option<String>,
    pub references: Option<ForeignKey>,
}

/// Database-agnostic column type.
///
/// Each backend maps these to its own DDL type string via [`SqlDialect::sql_type`].
/// The `#[derive(Model)]` macro infers the correct variant from your Rust field type.
/// Use `Dynamic` for arbitrary JSON/BSON payloads that have no fixed schema.
#[derive(Debug, Clone, PartialEq)]
pub enum ColumnType {
    Bool,
    SmallInt,
    Int,
    BigInt,
    Float,
    Double,
    Decimal { precision: u8, scale: u8 },
    Text,
    Varchar(u32),
    Char(u32),
    Bytes,
    Uuid,
    Timestamp,
    TimestampTz,
    Date,
    Time,
    Json,
    Jsonb,
    Array(Box<ColumnType>),
    // NoSQL passthrough
    Dynamic,
}

#[derive(Debug, Clone)]
pub struct ForeignKey {
    pub table: String,
    pub column: String,
    pub on_delete: ReferentialAction,
    pub on_update: ReferentialAction,
}

#[derive(Debug, Clone, Default)]
pub enum ReferentialAction {
    #[default]
    NoAction,
    Cascade,
    SetNull,
    Restrict,
}

impl ColumnDef {
    pub fn new(name: impl Into<String>, col_type: ColumnType) -> Self {
        Self {
            name: name.into(),
            col_type,
            nullable: true,
            primary_key: false,
            unique: false,
            default: None,
            references: None,
        }
    }

    pub fn primary_key(mut self) -> Self {
        self.primary_key = true;
        self.nullable = false;
        self
    }

    pub fn not_null(mut self) -> Self {
        self.nullable = false;
        self
    }

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

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

    pub fn references(mut self, table: impl Into<String>, column: impl Into<String>) -> Self {
        self.references = Some(ForeignKey {
            table: table.into(),
            column: column.into(),
            on_delete: ReferentialAction::NoAction,
            on_update: ReferentialAction::NoAction,
        });
        self
    }
}