From bca933a05514e860b0a2f27771a21e89a3b33830 Mon Sep 17 00:00:00 2001 From: Billy Chan Date: Wed, 19 Jun 2024 20:40:07 +0800 Subject: [PATCH] CLI: generate `has_one` relation for foreign key of unique index / constraint (#2254) * CLI: generate `has_one` relation for foreign key of unique index / constraint * Primary key column is unique * Bump dependency * Fix --- sea-orm-cli/src/commands/generate.rs | 5 ++++- sea-orm-codegen/src/entity/transformer.rs | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/sea-orm-cli/src/commands/generate.rs b/sea-orm-cli/src/commands/generate.rs index a07ca2e38..31e32af1a 100644 --- a/sea-orm-cli/src/commands/generate.rs +++ b/sea-orm-cli/src/commands/generate.rs @@ -137,7 +137,10 @@ pub async fn run_generate_command( sqlx_connect::(max_connections, url.as_str(), None).await?; println!("Discovering schema ..."); let schema_discovery = SchemaDiscovery::new(connection); - let schema = schema_discovery.discover().await?; + let schema = schema_discovery + .discover() + .await? + .merge_indexes_into_table(); let table_stmts = schema .tables .into_iter() diff --git a/sea-orm-codegen/src/entity/transformer.rs b/sea-orm-codegen/src/entity/transformer.rs index ceeb8cf93..c994d9f12 100644 --- a/sea-orm-codegen/src/entity/transformer.rs +++ b/sea-orm-codegen/src/entity/transformer.rs @@ -148,6 +148,17 @@ impl EntityTransformer { break; } } + if rel.columns.len() == entity.primary_keys.len() { + let mut count_pk = 0; + for primary_key in entity.primary_keys.iter() { + if rel.columns.contains(&primary_key.name) { + count_pk += 1; + } + } + if count_pk == entity.primary_keys.len() { + unique = true; + } + } let rel_type = if unique { RelationType::HasOne } else {