sea-orm-relations-kit 0.1.1

Relations SeaORM lacks: polymorphic relations, many-to-many attach/sync/toggle, relation counts and latest-of-many
Documentation
//! Migration helpers for polymorphic columns.

use sea_orm::sea_query::{ColumnDef, Index, IndexCreateStatement};

/// The type of the `*_id` column, matching the owners' primary keys.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyType {
    /// `INTEGER`, for `i32` keys.
    Integer,
    /// `BIGINT`, for `i64` keys; also fits `i32` ones. The usual choice.
    BigInteger,
    /// `UUID`, for UUID keys.
    Uuid,
    /// `VARCHAR(255)`, for string keys such as slugs.
    ///
    /// The `*_id` column should have the same type as the owners' keys: the
    /// subquery filters (`owned_by`, `owners_with`, `delete_orphans`) compare the two
    /// columns directly, and Postgres refuses `varchar = integer`.
    String,
}

/// The `{name}_type` and `{name}_id` columns, `NOT NULL`.
///
/// ```
/// use sea_orm::sea_query::{PostgresQueryBuilder, Table};
/// use sea_orm_relations_kit::schema::{morph_columns, morph_index, KeyType};
///
/// // In a SeaORM migration, pass these to `manager.create_table(...)` and
/// // `manager.create_index(...)`.
/// let [type_column, id_column] = morph_columns("commentable", KeyType::BigInteger);
/// let table = Table::create()
///     .table("comments")
///     .col(type_column)
///     .col(id_column)
///     .to_owned();
///
/// assert_eq!(
///     table.to_string(PostgresQueryBuilder),
///     r#"CREATE TABLE "comments" ( "commentable_type" varchar(255) NOT NULL, "commentable_id" bigint NOT NULL )"#
/// );
/// assert_eq!(
///     morph_index("comments", "commentable").to_string(PostgresQueryBuilder),
///     r#"CREATE INDEX "comments_commentable_type_commentable_id_index" ON "comments" ("commentable_type", "commentable_id")"#
/// );
/// ```
#[must_use]
pub fn morph_columns(name: &str, key: KeyType) -> [ColumnDef; 2] {
    let [mut type_column, mut id_column] = columns(name, key);
    [
        type_column.not_null().to_owned(),
        id_column.not_null().to_owned(),
    ]
}

/// The same columns, nullable, for an optional owner.
#[must_use]
pub fn nullable_morph_columns(name: &str, key: KeyType) -> [ColumnDef; 2] {
    let [mut type_column, mut id_column] = columns(name, key);
    [type_column.null().to_owned(), id_column.null().to_owned()]
}

/// The index on `({name}_type, {name}_id)` that every polymorphic lookup uses, named
/// `{table}_{name}_type_{name}_id_index`.
#[must_use]
pub fn morph_index(table: &str, name: &str) -> IndexCreateStatement {
    let type_column = format!("{name}_type");
    let id_column = format!("{name}_id");
    Index::create()
        .name(format!("{table}_{type_column}_{id_column}_index"))
        .table(table.to_string())
        .col(type_column)
        .col(id_column)
        .to_owned()
}

fn columns(name: &str, key: KeyType) -> [ColumnDef; 2] {
    let mut type_column = ColumnDef::new(format!("{name}_type"));
    type_column.string_len(255);
    let mut id_column = ColumnDef::new(format!("{name}_id"));
    match key {
        KeyType::Integer => id_column.integer(),
        KeyType::BigInteger => id_column.big_integer(),
        KeyType::Uuid => id_column.uuid(),
        KeyType::String => id_column.string_len(255),
    };
    [type_column, id_column]
}