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;
println!("Connecting to Postgres ...");
let schema = database_schema
.as_ref()
.map(|s| s.as_str())
.unwrap_or("public");
let schema = database_schema.as_deref().unwrap_or("public");
let connection =
sqlx_connect::<Postgres>(max_connections, url.as_str(), Some(schema))
.await?;
@ -171,7 +168,7 @@ pub async fn run_generate_command(
.filter(|schema| filter_skip_tables(&schema.info.name))
.map(|schema| schema.write())
.collect();
(Some(schema.schema), table_stmts)
(database_schema, table_stmts)
}
_ => 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> {
match schema_name {
Some(schema_name) => {
if schema_name != "public" {
Some(quote! { #schema_name })
} else {
None
}
}
None => None,
}
schema_name
.as_ref()
.map(|schema_name| quote! { #schema_name })
}
}
@ -1569,27 +1562,6 @@ mod tests {
})
.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!(
parse_from_file(ENTITY_FILES_WITH_SCHEMA_NAME[i].as_bytes())?.to_string(),
EntityWriter::gen_expanded_code_blocks(
@ -1674,27 +1646,6 @@ mod tests {
})
.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!(
parse_from_file(ENTITY_FILES_WITH_SCHEMA_NAME[i].as_bytes())?.to_string(),
EntityWriter::gen_compact_code_blocks(
@ -2344,27 +2295,6 @@ mod tests {
})
.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!(
parse_from_file(ENTITY_FILES_EXPANDED[i].as_bytes())?.to_string(),
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
pub struct SchemaManager<'c> {
conn: SchemaManagerConnection<'c>,
schema: Option<String>,
}
impl<'c> SchemaManager<'c> {
@ -21,7 +20,6 @@ impl<'c> SchemaManager<'c> {
{
Self {
conn: conn.into_schema_manager_connection(),
schema: None,
}
}
@ -40,18 +38,6 @@ impl<'c> SchemaManager<'c> {
pub fn get_connection(&self) -> &SchemaManagerConnection<'c> {
&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
@ -114,7 +100,7 @@ impl<'c> SchemaManager<'c> {
where
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>
@ -160,11 +146,7 @@ impl<'c> SchemaManager<'c> {
}
}
pub(crate) async fn has_table<C, T>(
conn: &C,
_schema: Option<&str>,
table: T,
) -> Result<bool, DbErr>
pub(crate) async fn has_table<C, T>(conn: &C, table: T) -> Result<bool, DbErr>
where
C: ConnectionTrait,
T: AsRef<str>,

View File

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

View File

@ -1,6 +1,6 @@
pub mod common;
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]
async fn main() -> Result<(), DbErr> {
@ -21,10 +21,7 @@ pub async fn create_and_delete_applog(db: &DatabaseConnection) -> Result<(), DbE
created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(),
};
Applog::insert(applog::ActiveModel {
id: NotSet,
..log1.clone().into_active_model()
})
Applog::insert(log1.clone().into_active_model())
.exec(db)
.await?;
@ -35,10 +32,7 @@ pub async fn create_and_delete_applog(db: &DatabaseConnection) -> Result<(), DbE
created_at: "2022-09-17T17:50:20+08:00".parse().unwrap(),
};
Applog::insert(applog::ActiveModel {
id: NotSet,
..log2.clone().into_active_model()
})
Applog::insert(log2.clone().into_active_model())
.exec(db)
.await?;

View File

@ -3,8 +3,8 @@ pub mod common;
pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq;
use sea_orm::{
entity::prelude::*, DatabaseConnection, Delete, IntoActiveModel, Iterable, NotSet, QueryTrait,
Set, Update,
entity::prelude::*, DatabaseConnection, Delete, IntoActiveModel, Iterable, QueryTrait, Set,
Update,
};
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(),
};
// Prepare insert statement
let mut insert = Entity::insert(ActiveModel {
id: NotSet,
..model.clone().into_active_model()
});
let mut insert = Entity::insert(model.clone().into_active_model());
// Reset the table name of insert statement
insert.query().into_table(entity.table_ref());
// Execute the insert statement

View File

@ -9,7 +9,7 @@ pub use common::{
TestContext,
};
use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet};
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
#[sea_orm_macros::test]
#[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 {
id: NotSet,
..event_trigger.clone().into_active_model()
}
.insert(db)
.await?;
let result = event_trigger.clone().into_active_model().insert(db).await?;
assert_eq!(result, event_trigger);

View File

@ -2,7 +2,7 @@ pub mod common;
pub use common::{features::*, setup::*, TestContext};
use pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet};
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
use serde_json::json;
#[sea_orm_macros::test]
@ -41,12 +41,7 @@ pub async fn insert_json_struct_1(db: &DatabaseConnection) -> Result<(), DbErr>
}),
};
let result = ActiveModel {
id: NotSet,
..model.clone().into_active_model()
}
.insert(db)
.await?;
let result = model.clone().into_active_model().insert(db).await?;
assert_eq!(result, model);
@ -81,12 +76,7 @@ pub async fn insert_json_struct_2(db: &DatabaseConnection) -> Result<(), DbErr>
json_value_opt: None,
};
let result = ActiveModel {
id: NotSet,
..model.clone().into_active_model()
}
.insert(db)
.await?;
let result = model.clone().into_active_model().insert(db).await?;
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 {
id: NotSet,
..json_vec.clone().into_active_model()
}
.insert(db)
.await?;
let result = json_vec.clone().into_active_model().insert(db).await?;
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> {
let json_vec = json_vec_derive::json_struct_vec::Model {
id: 1,
id: 2,
struct_vec: vec![
json_vec_derive::json_struct_vec::JsonColumn {
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 {
id: NotSet,
..json_vec.clone().into_active_model()
}
.insert(db)
.await?;
assert_eq!(result, json_vec);
let result = json_vec.clone().into_active_model().insert(db).await?;
let model = json_vec_derive::json_struct_vec::Entity::find()
.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 pretty_assertions::assert_eq;
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection, NotSet};
use sea_orm::{entity::prelude::*, entity::*, DatabaseConnection};
use std::str::FromStr;
#[sea_orm_macros::test]
@ -24,12 +24,7 @@ pub async fn create_and_update_pi(db: &DatabaseConnection) -> Result<(), DbErr>
big_decimal_opt: None,
};
let res = pi::ActiveModel {
id: NotSet,
..pi.clone().into_active_model()
}
.insert(db)
.await?;
let res = pi.clone().into_active_model().insert(db).await?;
let model = Pi::find().one(db).await?;
assert_eq!(model, Some(res));

View File

@ -325,10 +325,15 @@ pub async fn group_by() {
.await
.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)]
struct SelectResult {
name: String,
number_orders: Option<i64>,
number_orders: Option<Type>,
total_spent: Option<Decimal>,
min_spent: Option<Decimal>,
max_spent: Option<Decimal>,

View File

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

View File

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

View File

@ -1,7 +1,7 @@
pub mod common;
pub use common::{features::*, setup::*, TestContext};
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 time::macros::{date, time};
@ -25,10 +25,7 @@ pub async fn create_transaction_log(db: &DatabaseConnection) -> Result<(), DbErr
.assume_utc(),
};
let res = TransactionLog::insert(transaction_log::ActiveModel {
id: NotSet,
..transaction_log.clone().into_active_model()
})
let res = TransactionLog::insert(transaction_log.clone().into_active_model())
.exec(db)
.await?;

View File

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

View File

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

View File

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