Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 72 additions & 6 deletions sea-orm-sync/src/schema/entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use crate::{
PrimaryKeyArity, PrimaryKeyToColumn, PrimaryKeyTrait, RelationTrait, Schema,
};
use sea_query::{
ColumnDef, DynIden, Iden, Index, IndexCreateStatement, SeaRc, TableCreateStatement,
ColumnDef, DynIden, Iden, Index, IndexCreateStatement, IntoTableRef, SeaRc,
TableCreateStatement, TableRef,
extension::postgres::{Type, TypeCreateStatement},
};
use std::collections::BTreeMap;
Expand Down Expand Up @@ -141,7 +142,7 @@ where

pub(crate) fn create_index_from_entity<E>(
entity: E,
_backend: DbBackend,
backend: DbBackend,
) -> Vec<IndexCreateStatement>
where
E: EntityTrait,
Expand All @@ -155,7 +156,7 @@ where
if column_def.indexed && !column_def.unique {
let stmt = Index::create()
.name(format!("idx-{}-{}", entity.to_string(), column.to_string()))
.table(entity)
.table(index_table_ref(entity, backend))
.col(column)
.take();
indexes.push(stmt);
Expand All @@ -169,7 +170,7 @@ where
for (key, cols) in unique_keys {
let mut stmt = Index::create()
.name(format!("idx-{}-{}", entity.to_string(), key))
.table(entity)
.table(index_table_ref(entity, backend))
.unique()
.take();
for col in cols {
Expand All @@ -181,6 +182,16 @@ where
indexes
}

fn index_table_ref<E>(entity: E, backend: DbBackend) -> TableRef
where
E: EntityTrait,
{
match backend {
DbBackend::Postgres => entity.table_ref(),
DbBackend::MySql | DbBackend::Sqlite => entity.into_table_ref(),
}
}

pub(crate) fn create_table_from_entity<E>(entity: E, backend: DbBackend) -> TableCreateStatement
where
E: EntityTrait,
Expand Down Expand Up @@ -274,6 +285,29 @@ mod tests {
use crate::{DbBackend, EntityName, Schema, sea_query::*, tests_cfg::*};
use pretty_assertions::assert_eq;

mod custom_schema_indexes {
use crate as sea_orm;
use crate::entity::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(schema_name = "sys", table_name = "app_user")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(indexed)]
pub email: String,
#[sea_orm(unique_key = "tenant_name")]
pub tenant_id: i32,
#[sea_orm(unique_key = "tenant_name")]
pub name: String,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}
}

#[test]
fn test_create_table_from_entity_table_ref() {
for builder in [DbBackend::MySql, DbBackend::Postgres, DbBackend::Sqlite] {
Expand Down Expand Up @@ -344,16 +378,24 @@ mod tests {
let stmts = schema.create_index_from_entity(indexes::Entity);
assert_eq!(stmts.len(), 2);

let index_table = match builder {
DbBackend::Postgres => indexes::Entity.table_ref(),
DbBackend::MySql | DbBackend::Sqlite => indexes::Entity.into_table_ref(),
};
let idx: IndexCreateStatement = Index::create()
.name("idx-indexes-index1_attr")
.table(indexes::Entity)
.table(index_table)
.col(indexes::Column::Index1Attr)
.to_owned();
assert_eq!(builder.build(&stmts[0]), builder.build(&idx));

let index_table = match builder {
DbBackend::Postgres => indexes::Entity.table_ref(),
DbBackend::MySql | DbBackend::Sqlite => indexes::Entity.into_table_ref(),
};
let idx: IndexCreateStatement = Index::create()
.name("idx-indexes-my_unique")
.table(indexes::Entity)
.table(index_table)
.col(indexes::Column::UniqueKeyA)
.col(indexes::Column::UniqueKeyB)
.unique()
Expand All @@ -362,6 +404,30 @@ mod tests {
}
}

#[test]
fn test_create_index_from_entity_non_default_schema_table_ref() {
let builder = DbBackend::Postgres;
let schema = Schema::new(builder);
let stmts = schema.create_index_from_entity(custom_schema_indexes::Entity);
assert_eq!(stmts.len(), 2);

let idx: IndexCreateStatement = Index::create()
.name("idx-app_user-email")
.table(custom_schema_indexes::Entity.table_ref())
.col(custom_schema_indexes::Column::Email)
.to_owned();
assert_eq!(builder.build(&stmts[0]), builder.build(&idx));

let idx: IndexCreateStatement = Index::create()
.name("idx-app_user-tenant_name")
.table(custom_schema_indexes::Entity.table_ref())
.col(custom_schema_indexes::Column::TenantId)
.col(custom_schema_indexes::Column::Name)
.unique()
.take();
assert_eq!(builder.build(&stmts[1]), builder.build(&idx));
}

fn get_indexes_table_stmt() -> TableCreateStatement {
Table::create()
.col(
Expand Down
105 changes: 105 additions & 0 deletions sea-orm-sync/tests/schema_sync_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,30 @@ mod custom_schema_entity {
impl ActiveModelBehavior for ActiveModel {}
}

// Entity with generated indexes in a non-default PostgreSQL schema.
mod custom_schema_indexed_entity {
use sea_orm::entity::prelude::*;

#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(
schema_name = "test_schema_3084",
table_name = "sync_custom_schema_indexed"
)]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(indexed)]
pub email: String,
#[sea_orm(unique_key = "tenant_name")]
pub tenant_id: i32,
#[sea_orm(unique_key = "tenant_name")]
pub name: String,
}

impl ActiveModelBehavior for ActiveModel {}
}

/// Regression test for <https://github.com/SeaQL/sea-orm/issues/2970>.
///
/// A table with a `#[sea_orm(unique)]` column is created on the first sync.
Expand Down Expand Up @@ -314,6 +338,60 @@ fn test_sync_non_default_schema() -> Result<(), DbErr> {
Ok(())
}

/// Regression test for <https://github.com/SeaQL/sea-orm/issues/3084>.
///
/// An entity with `schema_name` pointing to a non-default PostgreSQL schema
/// should create generated indexes against that schema-qualified table.
#[sea_orm_macros::test]
#[cfg(feature = "sqlx-postgres")]
fn test_sync_non_default_schema_indexes() -> Result<(), DbErr> {
let ctx = TestContext::new("test_sync_non_default_schema_indexes");
let db = &ctx.db;

#[cfg(feature = "schema-sync")]
{
db.execute_raw(Statement::from_string(
DatabaseBackend::Postgres,
"CREATE SCHEMA IF NOT EXISTS test_schema_3084".to_owned(),
))?;

db.get_schema_builder()
.register(custom_schema_indexed_entity::Entity)
.sync(db)?;

assert!(
pg_table_exists_in_schema(db, "test_schema_3084", "sync_custom_schema_indexed")?,
"table should exist in schema `test_schema_3084`"
);

assert!(
pg_index_exists_in_schema(
db,
"test_schema_3084",
"sync_custom_schema_indexed",
"idx-sync_custom_schema_indexed-email"
)?,
"index on `sync_custom_schema_indexed.email` should exist in schema `test_schema_3084`"
);

assert!(
pg_index_exists_in_schema(
db,
"test_schema_3084",
"sync_custom_schema_indexed",
"idx-sync_custom_schema_indexed-tenant_name"
)?,
"unique index on `sync_custom_schema_indexed.(tenant_id, name)` should exist in schema `test_schema_3084`"
);

db.get_schema_builder()
.register(custom_schema_indexed_entity::Entity)
.sync(db)?;
}

Ok(())
}

#[cfg(feature = "sqlx-postgres")]
fn pg_table_exists_in_schema_query(schema: &str, table: &str) -> SelectStatement {
Query::select()
Expand Down Expand Up @@ -351,6 +429,33 @@ fn pg_table_exists_in_schema(
.map_err(DbErr::from)
}

#[cfg(feature = "sqlx-postgres")]
fn pg_index_exists_in_schema_query(schema: &str, table: &str, index: &str) -> SelectStatement {
Query::select()
.expr(Expr::cust("COUNT(*) > 0"))
.from("pg_indexes")
.cond_where(
Condition::all()
.add(Expr::col("schemaname").eq(schema))
.add(Expr::col("tablename").eq(table))
.add(Expr::col("indexname").eq(index)),
)
.to_owned()
}

#[cfg(feature = "sqlx-postgres")]
fn pg_index_exists_in_schema(
db: &DatabaseConnection,
schema: &str,
table: &str,
index: &str,
) -> Result<bool, DbErr> {
db.query_one(&pg_index_exists_in_schema_query(schema, table, index))?
.unwrap()
.try_get_by_index(0)
.map_err(DbErr::from)
}

#[cfg(feature = "sqlx-postgres")]
fn pg_index_exists(db: &DatabaseConnection, table: &str, index: &str) -> Result<bool, DbErr> {
db.query_one(
Expand Down
Loading
Loading