Fix clippy (#1426)

* Fix clippy

* Fix clippy
This commit is contained in:
Billy Chan 2023-01-27 18:50:20 +08:00 committed by GitHub
parent 5683c83189
commit 71dbffc725
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 102 additions and 111 deletions

View File

@ -211,7 +211,7 @@ where
// Set search_path for Postgres, E.g. Some("public") by default
// MySQL & SQLite connection initialize with schema `None`
if let Some(schema) = schema {
let sql = format!("SET search_path = '{}'", schema);
let sql = format!("SET search_path = '{schema}'");
pool_options = pool_options.after_connect(move |conn, _| {
let sql = sql.clone();
Box::pin(async move {

View File

@ -41,9 +41,9 @@ pub fn run_migrate_command(
// Construct the `--manifest-path`
let manifest_path = if migration_dir.ends_with('/') {
format!("{}Cargo.toml", migration_dir)
format!("{migration_dir}Cargo.toml")
} else {
format!("{}/Cargo.toml", migration_dir)
format!("{migration_dir}/Cargo.toml")
};
// Construct the arguments that will be supplied to `cargo` command
let mut args = vec!["run", "--manifest-path", &manifest_path, "--", subcommand];
@ -80,7 +80,7 @@ pub fn run_migrate_command(
pub fn run_migrate_init(migration_dir: &str) -> Result<(), Box<dyn Error>> {
let migration_dir = match migration_dir.ends_with('/') {
true => migration_dir.to_string(),
false => format!("{}/", migration_dir),
false => format!("{migration_dir}/"),
};
println!("Initializing migration directory...");
macro_rules! write_file {
@ -139,7 +139,7 @@ pub fn run_migrate_generate(
} else {
Local::now().format(FMT)
};
let migration_name = format!("m{}_{}", formatted_now, migration_name);
let migration_name = format!("m{formatted_now}_{migration_name}");
create_new_migration(&migration_name, migration_dir)?;
update_migrator(&migration_name, migration_dir)?;
@ -217,7 +217,7 @@ fn update_migrator(migration_name: &str, migration_dir: &str) -> Result<(), Box<
let mod_regex = Regex::new(r"mod\s+(?P<name>m\d{8}_\d{6}_\w+);")?;
let mods: Vec<_> = mod_regex.captures_iter(&migrator_content).collect();
let mods_end = mods.last().unwrap().get(0).unwrap().end() + 1;
updated_migrator_content.insert_str(mods_end, format!("mod {};\n", migration_name).as_str());
updated_migrator_content.insert_str(mods_end, format!("mod {migration_name};\n").as_str());
// build new vector from declared migration modules
let mut migrations: Vec<&str> = mods
@ -227,11 +227,11 @@ fn update_migrator(migration_name: &str, migration_dir: &str) -> Result<(), Box<
migrations.push(migration_name);
let mut boxed_migrations = migrations
.iter()
.map(|migration| format!(" Box::new({}::Migration),", migration))
.map(|migration| format!(" Box::new({migration}::Migration),"))
.collect::<Vec<String>>()
.join("\n");
boxed_migrations.push('\n');
let boxed_migrations = format!("vec![\n{} ]\n", boxed_migrations);
let boxed_migrations = format!("vec![\n{boxed_migrations} ]\n");
let vec_regex = Regex::new(r"vec!\[[\s\S]+\]\n")?;
let updated_migrator_content = vec_regex.replace(&updated_migrator_content, &boxed_migrations);
@ -249,7 +249,7 @@ impl Display for MigrationCommandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MigrationCommandError::InvalidName(name) => {
write!(f, "Invalid migration name: {}", name)
write!(f, "Invalid migration name: {name}")
}
}
}
@ -265,11 +265,11 @@ mod tests {
fn test_create_new_migration() {
let migration_name = "test_name";
let migration_dir = "/tmp/sea_orm_cli_test_new_migration/";
fs::create_dir_all(format!("{}src", migration_dir)).unwrap();
fs::create_dir_all(format!("{migration_dir}src")).unwrap();
create_new_migration(migration_name, migration_dir).unwrap();
let migration_filepath = Path::new(migration_dir)
.join("src")
.join(format!("{}.rs", migration_name));
.join(format!("{migration_name}.rs"));
assert!(migration_filepath.exists());
let migration_content = fs::read_to_string(migration_filepath).unwrap();
assert_eq!(
@ -283,7 +283,7 @@ mod tests {
fn test_update_migrator() {
let migration_name = "test_name";
let migration_dir = "/tmp/sea_orm_cli_test_update_migrator/";
fs::create_dir_all(format!("{}src", migration_dir)).unwrap();
fs::create_dir_all(format!("{migration_dir}src")).unwrap();
let migrator_filepath = Path::new(migration_dir).join("src").join("lib.rs");
fs::copy("./template/migration/src/lib.rs", &migrator_filepath).unwrap();
update_migrator(migration_name, migration_dir).unwrap();

View File

@ -12,6 +12,6 @@ pub fn handle_error<E>(error: E)
where
E: Display,
{
eprintln!("{}", error);
eprintln!("{error}");
::std::process::exit(1);
}

View File

@ -91,8 +91,8 @@ impl Column {
let col_type = match &self.col_type {
ColumnType::Float => Some("Float".to_owned()),
ColumnType::Double => Some("Double".to_owned()),
ColumnType::Decimal(Some((p, s))) => Some(format!("Decimal(Some(({}, {})))", p, s)),
ColumnType::Money(Some((p, s))) => Some(format!("Money(Some({}, {}))", p, s)),
ColumnType::Decimal(Some((p, s))) => Some(format!("Decimal(Some(({p}, {s})))")),
ColumnType::Money(Some((p, s))) => Some(format!("Money(Some({p}, {s}))")),
ColumnType::Text => Some("Text".to_owned()),
ColumnType::JsonBinary => Some("JsonBinary".to_owned()),
ColumnType::Custom(iden) => {

View File

@ -86,11 +86,11 @@ impl Relation {
pub fn get_attrs(&self) -> TokenStream {
let rel_type = self.get_rel_type();
let module_name = if let Some(module_name) = self.get_module_name() {
format!("super::{}::", module_name)
format!("super::{module_name}::")
} else {
String::new()
};
let ref_entity = format!("{}Entity", module_name);
let ref_entity = format!("{module_name}Entity");
match self.rel_type {
RelationType::HasOne | RelationType::HasMany => {
quote! {
@ -100,8 +100,8 @@ impl Relation {
RelationType::BelongsTo => {
let column_camel_case = self.get_column_camel_case();
let ref_column_camel_case = self.get_ref_column_camel_case();
let from = format!("Column::{}", column_camel_case);
let to = format!("{}Column::{}", module_name, ref_column_camel_case);
let from = format!("Column::{column_camel_case}");
let to = format!("{module_name}Column::{ref_column_camel_case}");
let on_update = if let Some(action) = &self.on_update {
let action = Self::get_foreign_key_action(action);
quote! {

View File

@ -122,8 +122,7 @@ impl FromStr for WithSerde {
"both" => Self::Both,
v => {
return Err(crate::Error::TransformError(format!(
"Unsupported enum variant '{}'",
v
"Unsupported enum variant '{v}'"
)))
}
})
@ -308,8 +307,7 @@ impl EntityWriter {
pub fn write_doc_comment(lines: &mut Vec<String>) {
let ver = env!("CARGO_PKG_VERSION");
let comments = vec![format!(
"//! `SeaORM` Entity. Generated by sea-orm-codegen {}",
ver
"//! `SeaORM` Entity. Generated by sea-orm-codegen {ver}"
)];
lines.extend(comments);
lines.push("".to_owned());

View File

@ -9,8 +9,8 @@ pub enum Error {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::StdIoError(e) => write!(f, "{:?}", e),
Self::TransformError(e) => write!(f, "{:?}", e),
Self::StdIoError(e) => write!(f, "{e:?}"),
Self::TransformError(e) => write!(f, "{e:?}"),
}
}
}

View File

@ -6,9 +6,9 @@ where
{
let string = string.to_string();
if RUST_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("r#{}", string)
format!("r#{string}")
} else if RUST_SPECIAL_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("{}_", string)
format!("{string}_")
} else {
string
}

View File

@ -158,7 +158,7 @@ impl DeriveModel {
.filter_map(ignore)
.collect();
let missing_field_msg = format!("field does not exist on {}", ident);
let missing_field_msg = format!("field does not exist on {ident}");
quote!(
#[automatically_derived]

View File

@ -44,7 +44,7 @@ impl DeriveRelation {
fn impl_relation_trait(&self) -> syn::Result<TokenStream> {
let ident = &self.ident;
let entity_ident = &self.entity_ident;
let no_relation_def_msg = format!("No RelationDef for {}", ident);
let no_relation_def_msg = format!("No RelationDef for {ident}");
let variant_relation_defs: Vec<TokenStream> = self
.variants

View File

@ -46,9 +46,9 @@ where
{
let string = string.to_string();
if RUST_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("r#{}", string)
format!("r#{string}")
} else if RUST_SPECIAL_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("{}_", string)
format!("{string}_")
} else {
string
}

View File

@ -121,6 +121,6 @@ fn handle_error<E>(error: E)
where
E: Display,
{
eprintln!("{}", error);
eprintln!("{error}");
exit(1);
}

View File

@ -35,7 +35,7 @@ impl Display for MigrationStatus {
MigrationStatus::Pending => "Pending",
MigrationStatus::Applied => "Applied",
};
write!(f, "{}", status)
write!(f, "{status}")
}
}
@ -91,7 +91,7 @@ pub trait MigratorTrait: Send {
let errors: Vec<String> = missing_migrations_in_fs
.iter()
.map(|missing_migration| {
format!("Migration file of version '{}' is missing, this migration has been applied but its file is missing", missing_migration)
format!("Migration file of version '{missing_migration}' is missing, this migration has been applied but its file is missing")
}).collect();
if !errors.is_empty() {

View File

@ -35,31 +35,31 @@ async fn run_migration(url: &str, db_name: &str, schema: &str) -> Result<(), DbE
DbBackend::MySql => {
db.execute(Statement::from_string(
db.get_database_backend(),
format!("CREATE DATABASE IF NOT EXISTS `{}`;", db_name),
format!("CREATE DATABASE IF NOT EXISTS `{db_name}`;"),
))
.await?;
let url = format!("{}/{}", url, db_name);
let url = format!("{url}/{db_name}");
db_connect(url).await?
}
DbBackend::Postgres => {
db.execute(Statement::from_string(
db.get_database_backend(),
format!("DROP DATABASE IF EXISTS \"{}\";", db_name),
format!("DROP DATABASE IF EXISTS \"{db_name}\";"),
))
.await?;
db.execute(Statement::from_string(
db.get_database_backend(),
format!("CREATE DATABASE \"{}\";", db_name),
format!("CREATE DATABASE \"{db_name}\";"),
))
.await?;
let url = format!("{}/{}", url, db_name);
let url = format!("{url}/{db_name}");
let db = db_connect(url).await?;
db.execute(Statement::from_string(
db.get_database_backend(),
format!("CREATE SCHEMA IF NOT EXISTS \"{}\";", schema),
format!("CREATE SCHEMA IF NOT EXISTS \"{schema}\";"),
))
.await?;

View File

@ -83,7 +83,7 @@ pub fn derive_database(input: TokenStream) -> TokenStream {
.map(|attr| attr.name)
.ok_or_else(|| s.span().error(ONE_DATABASE_ATTR))?;
let fairing_name = format!("'{}' Database Pool", db_name);
let fairing_name = format!("'{db_name}' Database Pool");
let pool_type = match &s.fields {
syn::Fields::Unnamed(f) => &f.unnamed[0].ty,

View File

@ -131,7 +131,7 @@ pub trait Database:
}
let dbtype = std::any::type_name::<Self>();
let fairing = Paint::default(format!("{}::init()", dbtype)).bold();
let fairing = Paint::default(format!("{dbtype}::init()")).bold();
error!(
"Attempted to fetch unattached database `{}`.",
Paint::default(dbtype).bold()

View File

@ -18,9 +18,9 @@ pub enum Error<A, B = A> {
impl<A: fmt::Display, B: fmt::Display> fmt::Display for Error<A, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Init(e) => write!(f, "failed to initialize database: {}", e),
Error::Get(e) => write!(f, "failed to get db connection: {}", e),
Error::Config(e) => write!(f, "bad configuration: {}", e),
Error::Init(e) => write!(f, "failed to initialize database: {e}"),
Error::Get(e) => write!(f, "failed to get db connection: {e}"),
Error::Config(e) => write!(f, "bad configuration: {e}"),
}
}
}

View File

@ -48,7 +48,7 @@ pub struct MockPoolErr;
impl std::fmt::Display for MockPoolErr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
write!(f, "{self:?}")
}
}

View File

@ -223,15 +223,14 @@ impl MockRow {
T::try_from(
self.values
.get(index)
.unwrap_or_else(|| panic!("No column for ColIdx {:?}", index))
.unwrap_or_else(|| panic!("No column for ColIdx {index:?}"))
.clone(),
)
.map_err(|e| DbErr::Type(e.to_string()))
} else if let Some(index) = index.as_usize() {
let (_, value) = self.values.iter().nth(*index).ok_or_else(|| {
DbErr::Query(RuntimeErr::Internal(format!(
"Column at index {} not found",
index
"Column at index {index} not found"
)))
})?;
T::try_from(value.clone()).map_err(|e| DbErr::Type(e.to_string()))

View File

@ -200,8 +200,7 @@ mod tests {
"B" => Ok(Self::Big),
"S" => Ok(Self::Small),
_ => Err(DbErr::Type(format!(
"unexpected value for Category enum: {}",
v
"unexpected value for Category enum: {v}"
))),
}
}

View File

@ -952,7 +952,7 @@ mod tests {
);
}
delete_by_id(format!("UUID"));
delete_by_id("UUID".to_string());
delete_by_id("UUID".to_string());
delete_by_id("UUID");
delete_by_id(Cow::from("UUID"));

View File

@ -279,7 +279,7 @@ pub trait ColumnTrait: IdenStatic + Iterable + FromStr {
/// );
/// ```
fn starts_with(&self, s: &str) -> SimpleExpr {
let pattern = format!("{}%", s);
let pattern = format!("{s}%");
Expr::col((self.entity_name(), *self)).like(pattern)
}
@ -295,7 +295,7 @@ pub trait ColumnTrait: IdenStatic + Iterable + FromStr {
/// );
/// ```
fn ends_with(&self, s: &str) -> SimpleExpr {
let pattern = format!("%{}", s);
let pattern = format!("%{s}");
Expr::col((self.entity_name(), *self)).like(pattern)
}
@ -311,7 +311,7 @@ pub trait ColumnTrait: IdenStatic + Iterable + FromStr {
/// );
/// ```
fn contains(&self, s: &str) -> SimpleExpr {
let pattern = format!("%{}%", s);
let pattern = format!("%{s}%");
Expr::col((self.entity_name(), *self)).like(pattern)
}

View File

@ -21,7 +21,7 @@ pub trait Linked {
fn find_linked(&self) -> Select<Self::ToEntity> {
let mut select = Select::new();
for (i, mut rel) in self.link().into_iter().rev().enumerate() {
let from_tbl = Alias::new(&format!("r{}", i)).into_iden();
let from_tbl = Alias::new(&format!("r{i}")).into_iden();
let to_tbl = if i > 0 {
Alias::new(&format!("r{}", i - 1)).into_iden()
} else {

View File

@ -28,7 +28,7 @@ pub trait TryGetable: Sized {
/// Get a value from the query result with prefixed column name
fn try_get(res: &QueryResult, pre: &str, col: &str) -> Result<Self, TryGetError> {
let index = format!("{}{}", pre, col);
let index = format!("{pre}{col}");
Self::try_get_by(res, index.as_str())
}
@ -52,7 +52,7 @@ impl From<TryGetError> for DbErr {
match e {
TryGetError::DbErr(e) => e,
TryGetError::Null(s) => {
DbErr::Type(format!("A null value was encountered while decoding {}", s))
DbErr::Type(format!("A null value was encountered while decoding {s}"))
}
}
}
@ -114,7 +114,7 @@ impl fmt::Debug for QueryResultRow {
#[cfg(feature = "sqlx-sqlite")]
Self::SqlxSqlite(_) => write!(f, "QueryResultRow::SqlxSqlite cannot be inspected"),
#[cfg(feature = "mock")]
Self::Mock(row) => write!(f, "{:?}", row),
Self::Mock(row) => write!(f, "{row:?}"),
#[allow(unreachable_patterns)]
_ => unreachable!(),
}
@ -634,7 +634,7 @@ impl TryGetable for u32 {
#[allow(dead_code)]
fn err_null_idx_col<I: ColIdx>(idx: I) -> TryGetError {
TryGetError::Null(format!("{:?}", idx))
TryGetError::Null(format!("{idx:?}"))
}
#[cfg(feature = "postgres-array")]

View File

@ -70,7 +70,7 @@ where
{
let mut slf = self;
for (i, mut rel) in l.link().into_iter().enumerate() {
let to_tbl = Alias::new(&format!("r{}", i)).into_iden();
let to_tbl = Alias::new(&format!("r{i}")).into_iden();
let from_tbl = if i > 0 {
Alias::new(&format!("r{}", i - 1)).into_iden()
} else {

View File

@ -99,7 +99,7 @@ where
{
let key = extract_key(&rel_def.to_col, &value);
acc.insert(format!("{:?}", key), value);
acc.insert(format!("{key:?}"), value);
}
acc
@ -108,7 +108,7 @@ where
let result: Vec<Option<<R as EntityTrait>::Model>> = keys
.iter()
.map(|key| hashmap.get(&format!("{:?}", key)).cloned())
.map(|key| hashmap.get(&format!("{key:?}")).cloned())
.collect();
Ok(result)
@ -145,7 +145,7 @@ where
let mut hashmap: HashMap<String, Vec<<R as EntityTrait>::Model>> =
keys.iter()
.fold(HashMap::new(), |mut acc, key: &ValueTuple| {
acc.insert(format!("{:?}", key), Vec::new());
acc.insert(format!("{key:?}"), Vec::new());
acc
});
@ -155,7 +155,7 @@ where
let key = extract_key(&rel_def.to_col, &value);
let vec = hashmap
.get_mut(&format!("{:?}", key))
.get_mut(&format!("{key:?}"))
.expect("Failed at finding key on hashmap");
vec.push(value);
@ -165,7 +165,7 @@ where
.iter()
.map(|key: &ValueTuple| {
hashmap
.get(&format!("{:?}", key))
.get(&format!("{key:?}"))
.cloned()
.unwrap_or_default()
})

View File

@ -37,7 +37,7 @@ pub trait QueryTrait {
/// query.filter(cake::Column::Id.eq(v))
/// })
/// .apply_if(Some(100), QuerySelect::limit)
/// .apply_if(None, QuerySelect::offset) // no-op
/// .apply_if(None, QuerySelect::offset::<Option<u64>>) // no-op
/// .build(DbBackend::Postgres)
/// .to_string(),
/// r#"SELECT "cake"."id", "cake"."name" FROM "cake" WHERE "cake"."id" = 3 LIMIT 100"#

View File

@ -66,8 +66,7 @@ impl ActiveModelBehavior for ActiveModel {
use rust_decimal_macros::dec;
if self.price.as_ref() == &dec!(0) {
Err(DbErr::Custom(format!(
"[before_save] Invalid Price, insert: {}",
insert
"[before_save] Invalid Price, insert: {insert}"
)))
} else {
Ok(self)
@ -81,8 +80,7 @@ impl ActiveModelBehavior for ActiveModel {
use rust_decimal_macros::dec;
if model.price < dec!(0) {
Err(DbErr::Custom(format!(
"[after_save] Invalid Price, insert: {}",
insert
"[after_save] Invalid Price, insert: {insert}"
)))
} else {
Ok(model)

View File

@ -10,42 +10,42 @@ use sea_query::{
pub async fn setup(base_url: &str, db_name: &str) -> DatabaseConnection {
if cfg!(feature = "sqlx-mysql") {
let url = format!("{}/mysql", base_url);
let url = format!("{base_url}/mysql");
let db = Database::connect(&url).await.unwrap();
let _drop_db_result = db
.execute(Statement::from_string(
DatabaseBackend::MySql,
format!("DROP DATABASE IF EXISTS `{}`;", db_name),
format!("DROP DATABASE IF EXISTS `{db_name}`;"),
))
.await;
let _create_db_result = db
.execute(Statement::from_string(
DatabaseBackend::MySql,
format!("CREATE DATABASE `{}`;", db_name),
format!("CREATE DATABASE `{db_name}`;"),
))
.await;
let url = format!("{}/{}", base_url, db_name);
let url = format!("{base_url}/{db_name}");
Database::connect(&url).await.unwrap()
} else if cfg!(feature = "sqlx-postgres") {
let url = format!("{}/postgres", base_url);
let url = format!("{base_url}/postgres");
let db = Database::connect(&url).await.unwrap();
let _drop_db_result = db
.execute(Statement::from_string(
DatabaseBackend::Postgres,
format!("DROP DATABASE IF EXISTS \"{}\";", db_name),
format!("DROP DATABASE IF EXISTS \"{db_name}\";"),
))
.await;
let _create_db_result = db
.execute(Statement::from_string(
DatabaseBackend::Postgres,
format!("CREATE DATABASE \"{}\";", db_name),
format!("CREATE DATABASE \"{db_name}\";"),
))
.await;
let url = format!("{}/{}", base_url, db_name);
let url = format!("{base_url}/{db_name}");
Database::connect(&url).await.unwrap()
} else {
Database::connect(base_url).await.unwrap()
@ -54,21 +54,21 @@ pub async fn setup(base_url: &str, db_name: &str) -> DatabaseConnection {
pub async fn tear_down(base_url: &str, db_name: &str) {
if cfg!(feature = "sqlx-mysql") {
let url = format!("{}/mysql", base_url);
let url = format!("{base_url}/mysql");
let db = Database::connect(&url).await.unwrap();
let _ = db
.execute(Statement::from_string(
DatabaseBackend::MySql,
format!("DROP DATABASE IF EXISTS \"{}\";", db_name),
format!("DROP DATABASE IF EXISTS \"{db_name}\";"),
))
.await;
} else if cfg!(feature = "sqlx-postgres") {
let url = format!("{}/postgres", base_url);
let url = format!("{base_url}/postgres");
let db = Database::connect(&url).await.unwrap();
let _ = db
.execute(Statement::from_string(
DatabaseBackend::Postgres,
format!("DROP DATABASE IF EXISTS \"{}\";", db_name),
format!("DROP DATABASE IF EXISTS \"{db_name}\";"),
))
.await;
} else {

View File

@ -27,7 +27,7 @@ pub async fn test_create_baker(db: &DbConn) {
let baker_bob = baker::ActiveModel {
name: Set("Baker Bob".to_owned()),
contact_details: Set(serde_json::json!(baker_bob_contact)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};
let res = Baker::insert(baker_bob)

View File

@ -20,7 +20,7 @@ pub async fn test_create_cake(db: &DbConn) {
"home": "0395555555",
"address": "12 Test St, Testville, Vic, Australia"
})),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};
let baker_insert_res = Baker::insert(baker_bob)
@ -34,7 +34,7 @@ pub async fn test_create_cake(db: &DbConn) {
price: Set(dec!(10.25)),
gluten_free: Set(false),
serial: Set(uuid),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};
@ -49,8 +49,8 @@ pub async fn test_create_cake(db: &DbConn) {
.expect("could not find cake");
let cake_baker = cakes_bakers::ActiveModel {
cake_id: Set(cake_insert_res.last_insert_id as i32),
baker_id: Set(baker_insert_res.last_insert_id as i32),
cake_id: Set(cake_insert_res.last_insert_id),
baker_id: Set(baker_insert_res.last_insert_id),
};
let cake_baker_res = CakesBakers::insert(cake_baker.clone())
.exec(db)

View File

@ -23,7 +23,7 @@ pub async fn test_create_lineitem(db: &DbConn) {
"home": "0395555555",
"address": "12 Test St, Testville, Vic, Australia"
})),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};
let baker_insert_res = Baker::insert(baker_bob)
@ -37,7 +37,7 @@ pub async fn test_create_lineitem(db: &DbConn) {
price: Set(dec!(10.25)),
gluten_free: Set(false),
serial: Set(Uuid::new_v4()),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};
@ -48,8 +48,8 @@ pub async fn test_create_lineitem(db: &DbConn) {
// Cake_Baker
let cake_baker = cakes_bakers::ActiveModel {
cake_id: Set(cake_insert_res.last_insert_id as i32),
baker_id: Set(baker_insert_res.last_insert_id as i32),
cake_id: Set(cake_insert_res.last_insert_id),
baker_id: Set(baker_insert_res.last_insert_id),
};
let cake_baker_res = CakesBakers::insert(cake_baker.clone())
.exec(db)
@ -73,8 +73,8 @@ pub async fn test_create_lineitem(db: &DbConn) {
// Order
let order_1 = order::ActiveModel {
bakery_id: Set(bakery_insert_res.last_insert_id as i32),
customer_id: Set(customer_insert_res.last_insert_id as i32),
bakery_id: Set(bakery_insert_res.last_insert_id),
customer_id: Set(customer_insert_res.last_insert_id),
total: Set(dec!(7.55)),
placed_at: Set(Utc::now().naive_utc()),
..Default::default()
@ -86,8 +86,8 @@ pub async fn test_create_lineitem(db: &DbConn) {
// Lineitem
let lineitem_1 = lineitem::ActiveModel {
cake_id: Set(cake_insert_res.last_insert_id as i32),
order_id: Set(order_insert_res.last_insert_id as i32),
cake_id: Set(cake_insert_res.last_insert_id),
order_id: Set(order_insert_res.last_insert_id),
price: Set(dec!(7.55)),
quantity: Set(1),
..Default::default()
@ -122,8 +122,5 @@ pub async fn test_create_lineitem(db: &DbConn) {
.expect("could not find order");
let order_model = order.unwrap();
assert_eq!(
order_model.customer_id,
customer_insert_res.last_insert_id as i32
);
assert_eq!(order_model.customer_id, customer_insert_res.last_insert_id);
}

View File

@ -23,7 +23,7 @@ pub async fn test_create_order(db: &DbConn) {
"home": "0395555555",
"address": "12 Test St, Testville, Vic, Australia"
})),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};
let baker_insert_res = Baker::insert(baker_bob)
@ -37,7 +37,7 @@ pub async fn test_create_order(db: &DbConn) {
price: Set(dec!(10.25)),
gluten_free: Set(false),
serial: Set(Uuid::new_v4()),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};
@ -48,8 +48,8 @@ pub async fn test_create_order(db: &DbConn) {
// Cake_Baker
let cake_baker = cakes_bakers::ActiveModel {
cake_id: Set(cake_insert_res.last_insert_id as i32),
baker_id: Set(baker_insert_res.last_insert_id as i32),
cake_id: Set(cake_insert_res.last_insert_id),
baker_id: Set(baker_insert_res.last_insert_id),
};
let cake_baker_res = CakesBakers::insert(cake_baker.clone())
.exec(db)
@ -73,8 +73,8 @@ pub async fn test_create_order(db: &DbConn) {
// Order
let order_1 = order::ActiveModel {
bakery_id: Set(bakery_insert_res.last_insert_id as i32),
customer_id: Set(customer_insert_res.last_insert_id as i32),
bakery_id: Set(bakery_insert_res.last_insert_id),
customer_id: Set(customer_insert_res.last_insert_id),
total: Set(dec!(15.10)),
placed_at: Set(Utc::now().naive_utc()),
..Default::default()
@ -86,8 +86,8 @@ pub async fn test_create_order(db: &DbConn) {
// Lineitem
let lineitem_1 = lineitem::ActiveModel {
cake_id: Set(cake_insert_res.last_insert_id as i32),
order_id: Set(order_insert_res.last_insert_id as i32),
cake_id: Set(cake_insert_res.last_insert_id),
order_id: Set(order_insert_res.last_insert_id),
price: Set(dec!(7.55)),
quantity: Set(2),
..Default::default()
@ -97,7 +97,7 @@ pub async fn test_create_order(db: &DbConn) {
.await
.expect("could not insert lineitem");
let order: Option<order::Model> = Order::find_by_id(order_insert_res.last_insert_id as i32)
let order: Option<order::Model> = Order::find_by_id(order_insert_res.last_insert_id)
.one(db)
.await
.expect("could not find order");

View File

@ -20,7 +20,7 @@ pub async fn test_delete_cake(db: &DbConn) {
price: Set(dec!(10.25)),
gluten_free: Set(false),
serial: Set(Uuid::new_v4()),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};

View File

@ -19,7 +19,7 @@ pub async fn test_update_cake(db: &DbConn) {
price: Set(dec!(10.25)),
gluten_free: Set(false),
serial: Set(Uuid::new_v4()),
bakery_id: Set(Some(bakery_insert_res.last_insert_id as i32)),
bakery_id: Set(Some(bakery_insert_res.last_insert_id)),
..Default::default()
};