Upstream Changes - 4 (#2168)

* cli: generate entity ignore default database schema

* fixup

* select result is `i32`

* fix

* clippy

* revert

* revert

* revert

* revert
This commit is contained in:
Billy Chan 2024-03-27 16:19:03 +08:00 committed by GitHub
parent 6b52288fcc
commit 0ff000b8f8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 69 additions and 225 deletions

View File

@ -153,10 +153,7 @@ pub async fn run_generate_command(
use sqlx::Postgres; use sqlx::Postgres;
println!("Connecting to Postgres ..."); println!("Connecting to Postgres ...");
let schema = database_schema let schema = database_schema.as_deref().unwrap_or("public");
.as_ref()
.map(|s| s.as_str())
.unwrap_or("public");
let connection = let connection =
sqlx_connect::<Postgres>(max_connections, url.as_str(), Some(schema)) sqlx_connect::<Postgres>(max_connections, url.as_str(), Some(schema))
.await?; .await?;
@ -171,7 +168,7 @@ pub async fn run_generate_command(
.filter(|schema| filter_skip_tables(&schema.info.name)) .filter(|schema| filter_skip_tables(&schema.info.name))
.map(|schema| schema.write()) .map(|schema| schema.write())
.collect(); .collect();
(Some(schema.schema), table_stmts) (database_schema, table_stmts)
} }
_ => unimplemented!("{} is not supported", url.scheme()), _ => unimplemented!("{} is not supported", url.scheme()),
}; };

View File

@ -818,16 +818,9 @@ impl EntityWriter {
} }
pub fn gen_schema_name(schema_name: &Option<String>) -> Option<TokenStream> { pub fn gen_schema_name(schema_name: &Option<String>) -> Option<TokenStream> {
match schema_name { schema_name
Some(schema_name) => { .as_ref()
if schema_name != "public" { .map(|schema_name| quote! { #schema_name })
Some(quote! { #schema_name })
} else {
None
}
}
None => None,
}
} }
} }
@ -1569,27 +1562,6 @@ mod tests {
}) })
.to_string() .to_string()
); );
assert_eq!(
parse_from_file(ENTITY_FILES[i].as_bytes())?.to_string(),
EntityWriter::gen_expanded_code_blocks(
entity,
&crate::WithSerde::None,
&crate::DateTimeCrate::Chrono,
&Some("public".to_owned()),
false,
false,
&TokenStream::new(),
&TokenStream::new(),
false,
)
.into_iter()
.skip(1)
.fold(TokenStream::new(), |mut acc, tok| {
acc.extend(tok);
acc
})
.to_string()
);
assert_eq!( assert_eq!(
parse_from_file(ENTITY_FILES_WITH_SCHEMA_NAME[i].as_bytes())?.to_string(), parse_from_file(ENTITY_FILES_WITH_SCHEMA_NAME[i].as_bytes())?.to_string(),
EntityWriter::gen_expanded_code_blocks( EntityWriter::gen_expanded_code_blocks(
@ -1674,27 +1646,6 @@ mod tests {
}) })
.to_string() .to_string()
); );
assert_eq!(
parse_from_file(ENTITY_FILES[i].as_bytes())?.to_string(),
EntityWriter::gen_compact_code_blocks(
entity,
&crate::WithSerde::None,
&crate::DateTimeCrate::Chrono,
&Some("public".to_owned()),
false,
false,
&TokenStream::new(),
&TokenStream::new(),
false,
)
.into_iter()
.skip(1)
.fold(TokenStream::new(), |mut acc, tok| {
acc.extend(tok);
acc
})
.to_string()
);
assert_eq!( assert_eq!(
parse_from_file(ENTITY_FILES_WITH_SCHEMA_NAME[i].as_bytes())?.to_string(), parse_from_file(ENTITY_FILES_WITH_SCHEMA_NAME[i].as_bytes())?.to_string(),
EntityWriter::gen_compact_code_blocks( EntityWriter::gen_compact_code_blocks(
@ -2344,27 +2295,6 @@ mod tests {
}) })
.to_string() .to_string()
); );
assert_eq!(
parse_from_file(ENTITY_FILES[i].as_bytes())?.to_string(),
EntityWriter::gen_compact_code_blocks(
entity,
&crate::WithSerde::None,
&crate::DateTimeCrate::Chrono,
&Some("public".to_owned()),
false,
false,
&TokenStream::new(),
&TokenStream::new(),
false,
)
.into_iter()
.skip(1)
.fold(TokenStream::new(), |mut acc, tok| {
acc.extend(tok);
acc
})
.to_string()
);
assert_eq!( assert_eq!(
parse_from_file(ENTITY_FILES_EXPANDED[i].as_bytes())?.to_string(), parse_from_file(ENTITY_FILES_EXPANDED[i].as_bytes())?.to_string(),
EntityWriter::gen_expanded_code_blocks( EntityWriter::gen_expanded_code_blocks(

View File

@ -11,7 +11,6 @@ use sea_schema::{mysql::MySql, postgres::Postgres, probe::SchemaProbe, sqlite::S
/// Helper struct for writing migration scripts in migration file /// Helper struct for writing migration scripts in migration file
pub struct SchemaManager<'c> { pub struct SchemaManager<'c> {
conn: SchemaManagerConnection<'c>, conn: SchemaManagerConnection<'c>,
schema: Option<String>,
} }
impl<'c> SchemaManager<'c> { impl<'c> SchemaManager<'c> {
@ -21,7 +20,6 @@ impl<'c> SchemaManager<'c> {
{ {
Self { Self {
conn: conn.into_schema_manager_connection(), conn: conn.into_schema_manager_connection(),
schema: None,
} }
} }
@ -40,18 +38,6 @@ impl<'c> SchemaManager<'c> {
pub fn get_connection(&self) -> &SchemaManagerConnection<'c> { pub fn get_connection(&self) -> &SchemaManagerConnection<'c> {
&self.conn &self.conn
} }
pub fn set_schema<T>(&mut self, schema: T) -> &mut Self
where
T: Into<String>,
{
self.schema = Some(schema.into());
self
}
pub fn get_schema(&self) -> &Option<String> {
&self.schema
}
} }
/// Schema Creation /// Schema Creation
@ -114,7 +100,7 @@ impl<'c> SchemaManager<'c> {
where where
T: AsRef<str>, T: AsRef<str>,
{ {
has_table(&self.conn, self.schema.as_deref(), table).await has_table(&self.conn, table).await
} }
pub async fn has_column<T, C>(&self, table: T, column: C) -> Result<bool, DbErr> pub async fn has_column<T, C>(&self, table: T, column: C) -> Result<bool, DbErr>
@ -160,11 +146,7 @@ impl<'c> SchemaManager<'c> {
} }
} }
pub(crate) async fn has_table<C, T>( pub(crate) async fn has_table<C, T>(conn: &C, table: T) -> Result<bool, DbErr>
conn: &C,
_schema: Option<&str>,
table: T,
) -> Result<bool, DbErr>
where where
C: ConnectionTrait, C: ConnectionTrait,
T: AsRef<str>, T: AsRef<str>,

View File

@ -2,7 +2,7 @@ pub mod common;
use common::features::*; use common::features::*;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet}; use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
#[sea_orm_macros::test] #[sea_orm_macros::test]
#[cfg(feature = "sqlx-postgres")] #[cfg(feature = "sqlx-postgres")]
@ -26,12 +26,7 @@ pub async fn create_and_update(db: &DatabaseConnection) -> Result<(), DbErr> {
bit64: 64, bit64: 64,
}; };
let res = bits::ActiveModel { let res = bits.clone().into_active_model().insert(db).await?;
id: NotSet,
..bits.clone().into_active_model()
}
.insert(db)
.await?;
let model = Bits::find().one(db).await?; let model = Bits::find().one(db).await?;
assert_eq!(model, Some(res)); assert_eq!(model, Some(res));

View File

@ -1,6 +1,6 @@
pub mod common; pub mod common;
pub use common::{features::*, setup::*, TestContext}; pub use common::{features::*, setup::*, TestContext};
use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel, NotSet}; use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel};
#[sea_orm_macros::test] #[sea_orm_macros::test]
async fn main() -> Result<(), DbErr> { async fn main() -> Result<(), DbErr> {
@ -21,12 +21,9 @@ pub async fn create_and_delete_applog(db: &DatabaseConnection) -> Result<(), DbE
created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(), created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(),
}; };
Applog::insert(applog::ActiveModel { Applog::insert(log1.clone().into_active_model())
id: NotSet, .exec(db)
..log1.clone().into_active_model() .await?;
})
.exec(db)
.await?;
let log2 = applog::Model { let log2 = applog::Model {
id: 2, id: 2,
@ -35,12 +32,9 @@ pub async fn create_and_delete_applog(db: &DatabaseConnection) -> Result<(), DbE
created_at: "2022-09-17T17:50:20+08:00".parse().unwrap(), created_at: "2022-09-17T17:50:20+08:00".parse().unwrap(),
}; };
Applog::insert(applog::ActiveModel { Applog::insert(log2.clone().into_active_model())
id: NotSet, .exec(db)
..log2.clone().into_active_model() .await?;
})
.exec(db)
.await?;
let delete_res = Applog::delete_by_id(2).exec(db).await?; let delete_res = Applog::delete_by_id(2).exec(db).await?;
assert_eq!(delete_res.rows_affected, 1); assert_eq!(delete_res.rows_affected, 1);

View File

@ -3,8 +3,8 @@ pub mod common;
pub use common::{features::*, setup::*, TestContext}; pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{ use sea_orm::{
entity::prelude::*, DatabaseConnection, Delete, IntoActiveModel, Iterable, NotSet, QueryTrait, entity::prelude::*, DatabaseConnection, Delete, IntoActiveModel, Iterable, QueryTrait, Set,
Set, Update, Update,
}; };
use sea_query::{Expr, Query}; use sea_query::{Expr, Query};
@ -31,10 +31,7 @@ pub async fn dyn_table_name_lazy_static(db: &DatabaseConnection) -> Result<(), D
name: "1st Row".into(), name: "1st Row".into(),
}; };
// Prepare insert statement // Prepare insert statement
let mut insert = Entity::insert(ActiveModel { let mut insert = Entity::insert(model.clone().into_active_model());
id: NotSet,
..model.clone().into_active_model()
});
// Reset the table name of insert statement // Reset the table name of insert statement
insert.query().into_table(entity.table_ref()); insert.query().into_table(entity.table_ref());
// Execute the insert statement // Execute the insert statement

View File

@ -9,7 +9,7 @@ pub use common::{
TestContext, TestContext,
}; };
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet}; use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
#[sea_orm_macros::test] #[sea_orm_macros::test]
#[cfg(all(feature = "sqlx-postgres", feature = "postgres-array"))] #[cfg(all(feature = "sqlx-postgres", feature = "postgres-array"))]
@ -33,12 +33,7 @@ pub async fn insert_event_trigger(db: &DatabaseConnection) -> Result<(), DbErr>
), ),
}; };
let result = event_trigger::ActiveModel { let result = event_trigger.clone().into_active_model().insert(db).await?;
id: NotSet,
..event_trigger.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, event_trigger); assert_eq!(result, event_trigger);

View File

@ -2,7 +2,7 @@ pub mod common;
pub use common::{features::*, setup::*, TestContext}; pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet}; use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
use serde_json::json; use serde_json::json;
#[sea_orm_macros::test] #[sea_orm_macros::test]
@ -41,12 +41,7 @@ pub async fn insert_json_struct_1(db: &DatabaseConnection) -> Result<(), DbErr>
}), }),
}; };
let result = ActiveModel { let result = model.clone().into_active_model().insert(db).await?;
id: NotSet,
..model.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, model); assert_eq!(result, model);
@ -81,12 +76,7 @@ pub async fn insert_json_struct_2(db: &DatabaseConnection) -> Result<(), DbErr>
json_value_opt: None, json_value_opt: None,
}; };
let result = ActiveModel { let result = model.clone().into_active_model().insert(db).await?;
id: NotSet,
..model.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, model); assert_eq!(result, model);

View File

@ -27,12 +27,7 @@ pub async fn insert_json_vec(db: &DatabaseConnection) -> Result<(), DbErr> {
])), ])),
}; };
let result = json_vec::ActiveModel { let result = json_vec.clone().into_active_model().insert(db).await?;
id: NotSet,
..json_vec.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, json_vec); assert_eq!(result, json_vec);
@ -77,7 +72,7 @@ pub async fn insert_json_string_vec_derive(db: &DatabaseConnection) -> Result<()
pub async fn insert_json_struct_vec_derive(db: &DatabaseConnection) -> Result<(), DbErr> { pub async fn insert_json_struct_vec_derive(db: &DatabaseConnection) -> Result<(), DbErr> {
let json_vec = json_vec_derive::json_struct_vec::Model { let json_vec = json_vec_derive::json_struct_vec::Model {
id: 1, id: 2,
struct_vec: vec![ struct_vec: vec![
json_vec_derive::json_struct_vec::JsonColumn { json_vec_derive::json_struct_vec::JsonColumn {
value: "4".to_string(), value: "4".to_string(),
@ -91,13 +86,7 @@ pub async fn insert_json_struct_vec_derive(db: &DatabaseConnection) -> Result<()
], ],
}; };
let result = json_vec_derive::json_struct_vec::ActiveModel { let result = json_vec.clone().into_active_model().insert(db).await?;
id: NotSet,
..json_vec.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, json_vec);
let model = json_vec_derive::json_struct_vec::Entity::find() let model = json_vec_derive::json_struct_vec::Entity::find()
.filter(json_vec_derive::json_struct_vec::Column::Id.eq(json_vec.id)) .filter(json_vec_derive::json_struct_vec::Column::Id.eq(json_vec.id))

View File

@ -2,7 +2,7 @@ pub mod common;
use common::{features::*, setup::*, TestContext}; use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet}; use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
use std::str::FromStr; use std::str::FromStr;
#[sea_orm_macros::test] #[sea_orm_macros::test]
@ -24,12 +24,7 @@ pub async fn create_and_update_pi(db: &DatabaseConnection) -> Result<(), DbErr>
big_decimal_opt: None, big_decimal_opt: None,
}; };
let res = pi::ActiveModel { let res = pi.clone().into_active_model().insert(db).await?;
id: NotSet,
..pi.clone().into_active_model()
}
.insert(db)
.await?;
let model = Pi::find().one(db).await?; let model = Pi::find().one(db).await?;
assert_eq!(model, Some(res)); assert_eq!(model, Some(res));

View File

@ -325,10 +325,15 @@ pub async fn group_by() {
.await .await
.expect("could not insert order"); .expect("could not insert order");
#[cfg(any(feature = "sqlx-postgres"))]
type Type = i64;
#[cfg(not(any(feature = "sqlx-postgres")))]
type Type = i32;
#[derive(Debug, FromQueryResult)] #[derive(Debug, FromQueryResult)]
struct SelectResult { struct SelectResult {
name: String, name: String,
number_orders: Option<i64>, number_orders: Option<Type>,
total_spent: Option<Decimal>, total_spent: Option<Decimal>,
min_spent: Option<Decimal>, min_spent: Option<Decimal>,
max_spent: Option<Decimal>, max_spent: Option<Decimal>,

View File

@ -87,10 +87,10 @@ async fn update_many() {
create_tables(db).await?; create_tables(db).await?;
Entity::insert( Entity::insert(
ActiveModel { Model {
action: Set("before_save".into()), id: 1,
values: Set(json!({ "id": "unique-id-001" })), action: "before_save".into(),
..Default::default() values: json!({ "id": "unique-id-001" }),
} }
.into_active_model(), .into_active_model(),
) )
@ -98,10 +98,10 @@ async fn update_many() {
.await?; .await?;
Entity::insert( Entity::insert(
ActiveModel { Model {
action: Set("before_save".into()), id: 2,
values: Set(json!({ "id": "unique-id-002" })), action: "before_save".into(),
..Default::default() values: json!({ "id": "unique-id-002" }),
} }
.into_active_model(), .into_active_model(),
) )
@ -109,10 +109,10 @@ async fn update_many() {
.await?; .await?;
Entity::insert( Entity::insert(
ActiveModel { Model {
action: Set("before_save".into()), id: 3,
values: Set(json!({ "id": "unique-id-003" })), action: "before_save".into(),
..Default::default() values: json!({ "id": "unique-id-003" }),
} }
.into_active_model(), .into_active_model(),
) )

View File

@ -28,13 +28,12 @@ pub async fn test_error(db: &DatabaseConnection) {
// if compiling without sqlx, this assignment will complain, // if compiling without sqlx, this assignment will complain,
// but the whole test is useless in that case anyway. // but the whole test is useless in that case anyway.
#[allow(unused_variables, clippy::match_single_binding)] #[allow(unused_variables)]
let error: DbErr = match db.get_database_backend() { let error: DbErr = cake
_ => cake.into_active_model(), .into_active_model()
} .insert(db)
.insert(db) .await
.await .expect_err("inserting should fail due to duplicate primary key");
.expect_err("inserting should fail due to duplicate primary key");
assert!(matches!( assert!(matches!(
error.sql_err(), error.sql_err(),

View File

@ -1,7 +1,7 @@
pub mod common; pub mod common;
pub use common::{features::*, setup::*, TestContext}; pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, ActiveValue::NotSet, DatabaseConnection, IntoActiveModel}; use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel};
use serde_json::json; use serde_json::json;
use time::macros::{date, time}; use time::macros::{date, time};
@ -25,12 +25,9 @@ pub async fn create_transaction_log(db: &DatabaseConnection) -> Result<(), DbErr
.assume_utc(), .assume_utc(),
}; };
let res = TransactionLog::insert(transaction_log::ActiveModel { let res = TransactionLog::insert(transaction_log.clone().into_active_model())
id: NotSet, .exec(db)
..transaction_log.clone().into_active_model() .await?;
})
.exec(db)
.await?;
assert_eq!(transaction_log.id, res.last_insert_id); assert_eq!(transaction_log.id, res.last_insert_id);
assert_eq!( assert_eq!(

View File

@ -1,7 +1,7 @@
pub mod common; pub mod common;
pub use common::{features::*, setup::*, TestContext}; pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel, NotSet}; use sea_orm::{entity::prelude::*, DatabaseConnection, IntoActiveModel};
#[sea_orm_macros::test] #[sea_orm_macros::test]
async fn main() -> Result<(), DbErr> { async fn main() -> Result<(), DbErr> {
@ -23,12 +23,9 @@ pub async fn create_applog(db: &DatabaseConnection) -> Result<(), DbErr> {
created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(), created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(),
}; };
let res = Applog::insert(applog::ActiveModel { let res = Applog::insert(log.clone().into_active_model())
id: NotSet, .exec(db)
..log.clone().into_active_model() .await?;
})
.exec(db)
.await?;
assert_eq!(log.id, res.last_insert_id); assert_eq!(log.id, res.last_insert_id);
assert_eq!(Applog::find().one(db).await?, Some(log.clone())); assert_eq!(Applog::find().one(db).await?, Some(log.clone()));
@ -75,12 +72,9 @@ pub async fn create_satellites_log(db: &DatabaseConnection) -> Result<(), DbErr>
deployment_date: "2022-01-07T12:11:23Z".parse().unwrap(), deployment_date: "2022-01-07T12:11:23Z".parse().unwrap(),
}; };
let res = Satellite::insert(satellite::ActiveModel { let res = Satellite::insert(archive.clone().into_active_model())
id: NotSet, .exec(db)
..archive.clone().into_active_model() .await?;
})
.exec(db)
.await?;
assert_eq!(archive.id, res.last_insert_id); assert_eq!(archive.id, res.last_insert_id);
assert_eq!(Satellite::find().one(db).await?, Some(archive.clone())); assert_eq!(Satellite::find().one(db).await?, Some(archive.clone()));

View File

@ -2,7 +2,7 @@ pub mod common;
pub use common::{features::*, setup::*, TestContext}; pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet}; use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
#[sea_orm_macros::test] #[sea_orm_macros::test]
async fn main() -> Result<(), DbErr> { async fn main() -> Result<(), DbErr> {
@ -26,12 +26,7 @@ pub async fn insert_uuid_fmt(db: &DatabaseConnection) -> Result<(), DbErr> {
uuid_urn: uuid.urn(), uuid_urn: uuid.urn(),
}; };
let result = uuid_fmt::ActiveModel { let result = uuid_fmt.clone().into_active_model().insert(db).await?;
id: NotSet,
..uuid_fmt.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, uuid_fmt); assert_eq!(result, uuid_fmt);

View File

@ -12,7 +12,7 @@ pub use common::{
TestContext, TestContext,
}; };
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet}; use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
use sea_query::{ArrayType, ColumnType, Value, ValueType, ValueTypeErr}; use sea_query::{ArrayType, ColumnType, Value, ValueType, ValueTypeErr};
#[sea_orm_macros::test] #[sea_orm_macros::test]
@ -40,12 +40,7 @@ pub async fn insert_value(db: &DatabaseConnection) -> Result<(), DbErr> {
id: 1, id: 1,
number: 48.into(), number: 48.into(),
}; };
let result = value_type_general::ActiveModel { let result = model.clone().into_active_model().insert(db).await?;
id: NotSet,
..model.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, model); assert_eq!(result, model);
Ok(()) Ok(())
@ -57,12 +52,7 @@ pub async fn postgres_insert_value(db: &DatabaseConnection) -> Result<(), DbErr>
number: 48.into(), number: 48.into(),
str_vec: StringVec(vec!["ab".to_string(), "cd".to_string()]), str_vec: StringVec(vec!["ab".to_string(), "cd".to_string()]),
}; };
let result = value_type_pg::ActiveModel { let result = model.clone().into_active_model().insert(db).await?;
id: NotSet,
..model.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, model); assert_eq!(result, model);
Ok(()) Ok(())