Skip to main content

sea_orm_relations_kit/
schema.rs

1//! Migration helpers for polymorphic columns.
2
3use sea_orm::sea_query::{ColumnDef, Index, IndexCreateStatement};
4
5/// The type of the `*_id` column, matching the owners' primary keys.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum KeyType {
8    /// `INTEGER`, for `i32` keys.
9    Integer,
10    /// `BIGINT`, for `i64` keys; also fits `i32` ones. The usual choice.
11    BigInteger,
12    /// `UUID`, for UUID keys.
13    Uuid,
14    /// `VARCHAR(255)`, for string keys such as slugs.
15    ///
16    /// The `*_id` column should have the same type as the owners' keys: the
17    /// subquery filters (`owned_by`, `owners_with`, `delete_orphans`) compare the two
18    /// columns directly, and Postgres refuses `varchar = integer`.
19    String,
20}
21
22/// The `{name}_type` and `{name}_id` columns, `NOT NULL`.
23///
24/// ```
25/// use sea_orm::sea_query::{PostgresQueryBuilder, Table};
26/// use sea_orm_relations_kit::schema::{morph_columns, morph_index, KeyType};
27///
28/// // In a SeaORM migration, pass these to `manager.create_table(...)` and
29/// // `manager.create_index(...)`.
30/// let [type_column, id_column] = morph_columns("commentable", KeyType::BigInteger);
31/// let table = Table::create()
32///     .table("comments")
33///     .col(type_column)
34///     .col(id_column)
35///     .to_owned();
36///
37/// assert_eq!(
38///     table.to_string(PostgresQueryBuilder),
39///     r#"CREATE TABLE "comments" ( "commentable_type" varchar(255) NOT NULL, "commentable_id" bigint NOT NULL )"#
40/// );
41/// assert_eq!(
42///     morph_index("comments", "commentable").to_string(PostgresQueryBuilder),
43///     r#"CREATE INDEX "comments_commentable_type_commentable_id_index" ON "comments" ("commentable_type", "commentable_id")"#
44/// );
45/// ```
46#[must_use]
47pub fn morph_columns(name: &str, key: KeyType) -> [ColumnDef; 2] {
48    let [mut type_column, mut id_column] = columns(name, key);
49    [
50        type_column.not_null().to_owned(),
51        id_column.not_null().to_owned(),
52    ]
53}
54
55/// The same columns, nullable, for an optional owner.
56#[must_use]
57pub fn nullable_morph_columns(name: &str, key: KeyType) -> [ColumnDef; 2] {
58    let [mut type_column, mut id_column] = columns(name, key);
59    [type_column.null().to_owned(), id_column.null().to_owned()]
60}
61
62/// The index on `({name}_type, {name}_id)` that every polymorphic lookup uses, named
63/// `{table}_{name}_type_{name}_id_index`.
64#[must_use]
65pub fn morph_index(table: &str, name: &str) -> IndexCreateStatement {
66    let type_column = format!("{name}_type");
67    let id_column = format!("{name}_id");
68    Index::create()
69        .name(format!("{table}_{type_column}_{id_column}_index"))
70        .table(table.to_string())
71        .col(type_column)
72        .col(id_column)
73        .to_owned()
74}
75
76fn columns(name: &str, key: KeyType) -> [ColumnDef; 2] {
77    let mut type_column = ColumnDef::new(format!("{name}_type"));
78    type_column.string_len(255);
79    let mut id_column = ColumnDef::new(format!("{name}_id"));
80    match key {
81        KeyType::Integer => id_column.integer(),
82        KeyType::BigInteger => id_column.big_integer(),
83        KeyType::Uuid => id_column.uuid(),
84        KeyType::String => id_column.string_len(255),
85    };
86    [type_column, id_column]
87}