diff --git a/cargo-pgrx/src/command/connect.rs b/cargo-pgrx/src/command/connect.rs index b499e2dd9..dac5a1c47 100644 --- a/cargo-pgrx/src/command/connect.rs +++ b/cargo-pgrx/src/command/connect.rs @@ -73,7 +73,7 @@ impl CommandExecute for Connect { Some(dbname) => dbname, None => { // We should infer from package - get_property(&package_manifest_path, "extname") + get_property(package_manifest_path, "extname") .wrap_err("could not determine extension name")? .ok_or(eyre!("extname not found in control file"))? } @@ -97,5 +97,5 @@ pub(crate) fn connect_psql(pg_config: &PgConfig, dbname: &str, pgcli: bool) -> e } // run psql - exec_psql(&pg_config, dbname, pgcli) + exec_psql(pg_config, dbname, pgcli) } diff --git a/cargo-pgrx/src/command/get.rs b/cargo-pgrx/src/command/get.rs index 1fef9c3cf..401312de7 100644 --- a/cargo-pgrx/src/command/get.rs +++ b/cargo-pgrx/src/command/get.rs @@ -40,7 +40,7 @@ impl CommandExecute for Get { crate::manifest::manifest_path(&metadata, self.package.as_ref()) .wrap_err("Couldn't get manifest path")?; - if let Some(value) = get_property(&package_manifest_path, &self.name)? { + if let Some(value) = get_property(package_manifest_path, &self.name)? { println!("{}", value); } Ok(()) @@ -72,7 +72,7 @@ pub fn get_property(manifest_path: impl AsRef, name: &str) -> eyre::Result continue; } - let (k, v) = (parts.get(0).unwrap().trim(), parts.get(1).unwrap().trim()); + let (k, v) = (parts.first().unwrap().trim(), parts.get(1).unwrap().trim()); if k == name { let v = v.trim_start_matches('\''); diff --git a/cargo-pgrx/src/command/init.rs b/cargo-pgrx/src/command/init.rs index 6d58ef899..1759ad34b 100644 --- a/cargo-pgrx/src/command/init.rs +++ b/cargo-pgrx/src/command/init.rs @@ -26,7 +26,7 @@ use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::OnceLock; -static PROCESS_ENV_DENYLIST: &'static [&'static str] = &[ +static PROCESS_ENV_DENYLIST: &[&str] = &[ "DEBUG", "MAKEFLAGS", "MAKELEVEL", @@ -131,14 +131,14 @@ impl CommandExecute for Init { default_pgrx .as_ref() .unwrap() // We just set this - .get(&pgver) + .get(pgver) .wrap_err_with(|| format!("{} is not a known Postgres version", pgver))? .clone() } else { let config = PgConfig::new_with_defaults(pg_config_path.as_str().into()); let label = config.label().ok(); // We allow None in case it's configured via the environment or something. - if label != None && label.as_deref() != Some(pgver) { + if label.is_some() && label.as_deref() != Some(pgver) { return Err(eyre!( "wrong `pg_config` given to `--{pgver}` `{pg_config_path:?}` is for PostgreSQL {}", config.major_version()?, @@ -254,9 +254,9 @@ fn download_postgres( } let mut buf = Vec::new(); let _count = http_response.into_reader().read_to_end(&mut buf)?; - let pgdir = untar(&buf, pgrx_home, pg_config, &init)?; - configure_postgres(pg_config, &pgdir, &init)?; - make_postgres(pg_config, &pgdir, &init)?; + let pgdir = untar(&buf, pgrx_home, pg_config, init)?; + configure_postgres(pg_config, &pgdir, init)?; + make_postgres(pg_config, &pgdir, init)?; make_install_postgres(pg_config, &pgdir, init) // returns a new PgConfig object } @@ -431,7 +431,7 @@ fn configure_postgres(pg_config: &PgConfig, pgdir: &PathBuf, init: &Init) -> eyr .stderr(std::process::Stdio::piped()) .stdin(std::process::Stdio::null()) .env("PATH", prefix_path(pgdir)) - .current_dir(&pgdir); + .current_dir(pgdir); for var in PROCESS_ENV_DENYLIST { command.env_remove(var); } @@ -472,7 +472,7 @@ fn make_postgres(pg_config: &PgConfig, pgdir: &PathBuf, init: &Init) -> eyre::Re .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .stdin(std::process::Stdio::null()) - .current_dir(&pgdir); + .current_dir(pgdir); for var in PROCESS_ENV_DENYLIST { command.env_remove(var); @@ -514,7 +514,7 @@ fn make_install_postgres( .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .stdin(std::process::Stdio::null()) - .current_dir(&pgdir); + .current_dir(pgdir); for var in PROCESS_ENV_DENYLIST { command.env_remove(var); } @@ -606,7 +606,7 @@ pub(crate) fn initdb(bindir: &PathBuf, datadir: &PathBuf) -> eyre::Result<()> { .stderr(Stdio::piped()) .args(get_c_locale_flags()) .arg("-D") - .arg(&datadir); + .arg(datadir); let command_str = format!("{:?}", command); tracing::debug!(command = %command_str, "Running"); diff --git a/cargo-pgrx/src/command/install.rs b/cargo-pgrx/src/command/install.rs index bec7e2ec0..ee2cd36d7 100644 --- a/cargo-pgrx/src/command/install.rs +++ b/cargo-pgrx/src/command/install.rs @@ -85,7 +85,7 @@ impl CommandExecute for Install { let pg_version = format!("pg{}", pg_config.major_version()?); let profile = CargoProfile::from_flags( self.profile.as_deref(), - self.release.then_some(CargoProfile::Release).unwrap_or(CargoProfile::Dev), + if self.release { CargoProfile::Release } else { CargoProfile::Dev }, )?; crate::manifest::modify_features_for_version( @@ -96,7 +96,7 @@ impl CommandExecute for Install { self.test, ); - display_version_info(&pg_config, &PgVersionSource::PgConfig(pg_config.label()?.into())); + display_version_info(&pg_config, &PgVersionSource::PgConfig(pg_config.label()?)); install_extension( self.manifest_path.as_ref(), self.package.as_ref(), @@ -146,7 +146,7 @@ pub(crate) fn install_extension( let versioned_so = get_property(&package_manifest_path, "module_pathname")?.is_none(); let build_command_output = - build_extension(user_manifest_path.as_ref(), user_package, &profile, &features)?; + build_extension(user_manifest_path.as_ref(), user_package, profile, features)?; let build_command_bytes = build_command_output.stdout; let build_command_reader = BufReader::new(build_command_bytes.as_slice()); let build_command_stream = cargo_metadata::Message::parse_stream(build_command_reader); @@ -162,7 +162,7 @@ pub(crate) fn install_extension( let mut dest = base_directory.clone(); dest.push(&extdir); dest.push( - &control_file + control_file .file_name() .ok_or_else(|| eyre!("Could not get filename for `{}`", control_file.display()))?, ); @@ -260,18 +260,18 @@ fn copy_file( })?, }; - println!("{} {} to {}", " Copying".bold().green(), msg, format_display_path(&dest)?.cyan()); + println!("{} {} to {}", " Copying".bold().green(), msg, format_display_path(dest)?.cyan()); if do_filter { // we want to filter the contents of the file we're to copy - let input = std::fs::read_to_string(&src) + let input = std::fs::read_to_string(src) .wrap_err_with(|| format!("failed to read `{}`", src.display()))?; let input = filter_contents(package_manifest_path, input)?; - std::fs::write(&dest, &input).wrap_err_with(|| { + std::fs::write(dest, input).wrap_err_with(|| { format!("failed writing `{}` to `{}`", src.display(), dest.display()) })?; } else { - std::fs::copy(&src, &dest).wrap_err_with(|| { + std::fs::copy(src, dest).wrap_err_with(|| { format!("failed copying `{}` to `{}`", src.display(), dest.display()) })?; } @@ -461,10 +461,10 @@ pub(crate) fn get_version(manifest_path: impl AsRef) -> eyre::Result) -> eyre::Result { let path_string = manifest_path.as_ref().to_owned(); if let Some(hash) = GIT_HASH.lock().unwrap().get(&path_string) { - return Ok(hash.clone()); + Ok(hash.clone()) } else { let hash = match get_property(manifest_path, "git_hash")? { Some(hash) => hash, @@ -504,7 +504,7 @@ fn make_relative(path: PathBuf) -> PathBuf { let mut relative = PathBuf::new(); let mut components = path.components(); components.next(); // skip the root - while let Some(part) = components.next() { + for part in components { relative.push(part) } relative @@ -514,7 +514,7 @@ pub(crate) fn format_display_path(path: impl AsRef) -> eyre::Result eyre::Result { +fn build_agent_for_url(url: &str) -> eyre::Result { if let Some(proxy_url) = for_url_str(url).to_string() { Ok(AgentBuilder::new().proxy(Proxy::new(proxy_url)?).build()) } else { diff --git a/cargo-pgrx/src/command/new.rs b/cargo-pgrx/src/command/new.rs index 5c7aa37d2..20c9b4e04 100644 --- a/cargo-pgrx/src/command/new.rs +++ b/cargo-pgrx/src/command/new.rs @@ -82,7 +82,7 @@ fn create_control_file(path: &PathBuf, name: &str) -> Result<(), std::io::Error> filename.push(format!("{}.control", name)); let mut file = std::fs::File::create(filename)?; - file.write_all(&format!(include_str!("../templates/control"), name = name).as_bytes())?; + file.write_all(format!(include_str!("../templates/control"), name = name).as_bytes())?; Ok(()) } @@ -93,7 +93,7 @@ fn create_cargo_toml(path: &PathBuf, name: &str) -> Result<(), std::io::Error> { filename.push("Cargo.toml"); let mut file = std::fs::File::create(filename)?; - file.write_all(&format!(include_str!("../templates/cargo_toml"), name = name).as_bytes())?; + file.write_all(format!(include_str!("../templates/cargo_toml"), name = name).as_bytes())?; Ok(()) } @@ -119,10 +119,10 @@ fn create_lib_rs(path: &PathBuf, name: &str, is_bgworker: bool) -> Result<(), st if is_bgworker { file.write_all( - &format!(include_str!("../templates/bgworker_lib_rs"), name = name).as_bytes(), + format!(include_str!("../templates/bgworker_lib_rs"), name = name).as_bytes(), )?; } else { - file.write_all(&format!(include_str!("../templates/lib_rs"), name = name).as_bytes())?; + file.write_all(format!(include_str!("../templates/lib_rs"), name = name).as_bytes())?; } Ok(()) diff --git a/cargo-pgrx/src/command/package.rs b/cargo-pgrx/src/command/package.rs index 3716fdb1b..3a779fbde 100644 --- a/cargo-pgrx/src/command/package.rs +++ b/cargo-pgrx/src/command/package.rs @@ -60,7 +60,7 @@ impl Package { let pg_config = match self.pg_config { None => PgConfig::from_path(), - Some(config) => PgConfig::new_with_defaults(PathBuf::from(config)), + Some(config) => PgConfig::new_with_defaults(config), }; let pg_version = format!("pg{}", pg_config.major_version()?); @@ -74,7 +74,7 @@ impl Package { let profile = CargoProfile::from_flags( self.profile.as_deref(), // NB: `cargo pgrx package` defaults to "--release" whereas all other commands default to "debug" - self.debug.then_some(CargoProfile::Dev).unwrap_or(CargoProfile::Release), + if self.debug { CargoProfile::Dev } else { CargoProfile::Release }, )?; let out_dir = if let Some(out_dir) = self.out_dir { out_dir @@ -127,7 +127,7 @@ pub(crate) fn package_extension( std::fs::create_dir_all(&out_dir)?; } - display_version_info(pg_config, &PgVersionSource::PgConfig(pg_config.label()?.into())); + display_version_info(pg_config, &PgVersionSource::PgConfig(pg_config.label()?)); install_extension( user_manifest_path, user_package, diff --git a/cargo-pgrx/src/command/run.rs b/cargo-pgrx/src/command/run.rs index 3af391467..3f29f9ab4 100644 --- a/cargo-pgrx/src/command/run.rs +++ b/cargo-pgrx/src/command/run.rs @@ -74,7 +74,7 @@ impl CommandExecute for Run { }; let profile = CargoProfile::from_flags( self.profile.as_deref(), - self.release.then_some(CargoProfile::Release).unwrap_or(CargoProfile::Dev), + if self.release { CargoProfile::Release } else { CargoProfile::Dev }, )?; run( diff --git a/cargo-pgrx/src/command/schema.rs b/cargo-pgrx/src/command/schema.rs index f28eeb344..27aa82807 100644 --- a/cargo-pgrx/src/command/schema.rs +++ b/cargo-pgrx/src/command/schema.rs @@ -106,7 +106,7 @@ impl CommandExecute for Schema { let profile = CargoProfile::from_flags( self.profile.as_deref(), - self.release.then_some(CargoProfile::Release).unwrap_or(CargoProfile::Dev), + if self.release { CargoProfile::Release } else { CargoProfile::Dev }, )?; generate_schema( @@ -306,7 +306,7 @@ pub(crate) fn generate_schema( let lib_so_data = std::fs::read(&lib_so).wrap_err("couldn't read extension shared object")?; let lib_so_obj_file = - parse_object(&*lib_so_data).wrap_err("couldn't parse extension shared object")?; + parse_object(&lib_so_data).wrap_err("couldn't parse extension shared object")?; let lib_so_exports = lib_so_obj_file.exports().wrap_err("couldn't get exports from extension shared object")?; @@ -340,11 +340,8 @@ pub(crate) fn generate_schema( let mut num_aggregates = 0_usize; for func in &fns_to_call { if func.starts_with("__pgrx_internals_schema_") { - let schema = func - .split('_') - .skip(5) - .next() - .expect("Schema extern name was not of expected format"); + let schema = + func.split('_').nth(5).expect("Schema extern name was not of expected format"); seen_schemas.push(schema); } else if func.starts_with("__pgrx_internals_fn_") { num_funcs += 1; @@ -369,8 +366,8 @@ pub(crate) fn generate_schema( "{} {} SQL entities: {} schemas ({} unique), {} functions, {} types, {} enums, {} sqls, {} ords, {} hashes, {} aggregates, {} triggers", " Discovered".bold().green(), fns_to_call.len().to_string().bold().cyan(), - seen_schemas.iter().count().to_string().bold().cyan(), - seen_schemas.iter().collect::>().iter().count().to_string().bold().cyan(), + seen_schemas.len().to_string().bold().cyan(), + seen_schemas.iter().collect::>().len().to_string().bold().cyan(), num_funcs.to_string().bold().cyan(), num_types.to_string().bold().cyan(), num_enums.to_string().bold().cyan(), @@ -502,7 +499,7 @@ fn create_stub( } let postmaster_obj_file = - parse_object(&*postmaster_bin_data).wrap_err("couldn't parse postmaster")?; + parse_object(&postmaster_bin_data).wrap_err("couldn't parse postmaster")?; let postmaster_exports = postmaster_obj_file .exports() .wrap_err("couldn't get exports from extension shared object")?; @@ -528,7 +525,7 @@ fn create_stub( let mut so_rustc_invocation = crate::env::rustc(); so_rustc_invocation.stderr(Stdio::inherit()); - if let Some(rustc_flags_str) = std::env::var("RUSTFLAGS").ok() { + if let Ok(rustc_flags_str) = std::env::var("RUSTFLAGS") { let rustc_flags = rustc_flags_str.split(' ').collect::>(); so_rustc_invocation.args(rustc_flags); } @@ -564,20 +561,20 @@ fn create_stub( } fn parse_object(data: &[u8]) -> object::Result { - let kind = object::FileKind::parse(&*data)?; + let kind = object::FileKind::parse(data)?; match kind { FileKind::MachOFat32 => { let arch = env::consts::ARCH; - match slice_arch32(&*data, arch) { - Some(slice) => parse_object(&*slice), + match slice_arch32(data, arch) { + Some(slice) => parse_object(slice), None => { panic!("Failed to slice architecture '{arch}' from universal binary.") } } } - _ => object::File::parse(&*data), + _ => object::File::parse(data), } } @@ -593,10 +590,10 @@ fn slice_arch32<'a>(data: &'a [u8], arch: &str) -> Option<&'a [u8]> { _ => Architecture::Unknown, }; - let candidates = FatHeader::parse_arch32(&*data).ok()?; + let candidates = FatHeader::parse_arch32(data).ok()?; let architecture = candidates.iter().find(|a| a.architecture() == target)?; - architecture.data(&*data).ok() + architecture.data(data).ok() } #[cfg(test)] @@ -629,7 +626,7 @@ mod tests { let slice = slice_arch32(&bin, "aarch64") .expect("Failed to slice architecture 'aarch64' from universal binary."); - assert!(parse_object(&slice).is_ok()); + assert!(parse_object(slice).is_ok()); } #[test] diff --git a/cargo-pgrx/src/command/start.rs b/cargo-pgrx/src/command/start.rs index bb8554c67..aeb6391c9 100644 --- a/cargo-pgrx/src/command/start.rs +++ b/cargo-pgrx/src/command/start.rs @@ -44,7 +44,7 @@ impl CommandExecute for Start { me.manifest_path, )?; let (pg_config, _) = - pg_config_and_version(&pgrx, &package_manifest, me.pg_version, None, false)?; + pg_config_and_version(pgrx, &package_manifest, me.pg_version, None, false)?; start_postgres(&pg_config) } diff --git a/cargo-pgrx/src/command/stop.rs b/cargo-pgrx/src/command/stop.rs index d52c1e2aa..98e269c00 100644 --- a/cargo-pgrx/src/command/stop.rs +++ b/cargo-pgrx/src/command/stop.rs @@ -43,7 +43,7 @@ impl CommandExecute for Stop { me.manifest_path, )?; let (pg_config, _) = - pg_config_and_version(&pgrx, &package_manifest, me.pg_version, None, false)?; + pg_config_and_version(pgrx, &package_manifest, me.pg_version, None, false)?; stop_postgres(&pg_config) } @@ -67,7 +67,7 @@ pub(crate) fn stop_postgres(pg_config: &PgConfig) -> eyre::Result<()> { let datadir = pg_config.data_dir()?; let bindir = pg_config.bin_dir()?; - if status_postgres(pg_config)? == false { + if !(status_postgres(pg_config)?) { // it's not running, no need to stop it tracing::debug!("Already stopped"); return Ok(()); diff --git a/cargo-pgrx/src/command/sudo_install.rs b/cargo-pgrx/src/command/sudo_install.rs index 8f20dd791..3d0650e36 100644 --- a/cargo-pgrx/src/command/sudo_install.rs +++ b/cargo-pgrx/src/command/sudo_install.rs @@ -29,7 +29,7 @@ impl From for SudoInstall { release: value.release, profile: value.profile, test: value.test, - pg_config: value.pg_config.map(|path| PathBuf::from(path)), + pg_config: value.pg_config.map(PathBuf::from), out_dir: None, features: value.features, verbose: value.verbose, diff --git a/cargo-pgrx/src/command/test.rs b/cargo-pgrx/src/command/test.rs index f47f2fde4..4bb0bcea3 100644 --- a/cargo-pgrx/src/command/test.rs +++ b/cargo-pgrx/src/command/test.rs @@ -55,7 +55,7 @@ impl CommandExecute for Test { let (package_manifest, _package_manifest_path) = get_package_manifest(&me.features, me.package.as_ref(), me.manifest_path.as_ref())?; let (pg_config, _pg_version) = pg_config_and_version( - &pgrx, + pgrx, &package_manifest, me.pg_version.clone(), Some(&mut features), @@ -64,7 +64,7 @@ impl CommandExecute for Test { let profile = CargoProfile::from_flags( me.profile.as_deref(), - me.release.then_some(CargoProfile::Release).unwrap_or(CargoProfile::Dev), + if me.release { CargoProfile::Release } else { CargoProfile::Dev }, )?; test_extension( @@ -173,11 +173,9 @@ pub fn test_extension( tracing::debug!(command = ?command, "Running"); let status = command.status().wrap_err("failed to run cargo test")?; tracing::trace!(status_code = %status, command = ?command, "Finished"); - if !status.success() { - if !status.success() { - // We explicitly do not want to return a spantraced error here. - std::process::exit(1) - } + if !status.success() && !status.success() { + // We explicitly do not want to return a spantraced error here. + std::process::exit(1) } Ok(()) diff --git a/cargo-pgrx/src/main.rs b/cargo-pgrx/src/main.rs index ca0e095eb..56b16b97f 100644 --- a/cargo-pgrx/src/main.rs +++ b/cargo-pgrx/src/main.rs @@ -87,18 +87,13 @@ fn main() -> color_eyre::Result<()> { _ => "trace", }; let filter_layer = EnvFilter::new("warn"); - let filter_layer = - filter_layer.add_directive(format!("cargo_pgrx={}", log_level).parse()?); - let filter_layer = filter_layer.add_directive(format!("pgrx={}", log_level).parse()?); - let filter_layer = - filter_layer.add_directive(format!("pgrx_macros={}", log_level).parse()?); - let filter_layer = - filter_layer.add_directive(format!("pgrx_tests={}", log_level).parse()?); - let filter_layer = - filter_layer.add_directive(format!("pgrx_pg_sys={}", log_level).parse()?); - let filter_layer = - filter_layer.add_directive(format!("pgrx_utils={}", log_level).parse()?); filter_layer + .add_directive(format!("cargo_pgrx={}", log_level).parse()?) + .add_directive(format!("pgrx={}", log_level).parse()?) + .add_directive(format!("pgrx_macros={}", log_level).parse()?) + .add_directive(format!("pgrx_tests={}", log_level).parse()?) + .add_directive(format!("pgrx_pg_sys={}", log_level).parse()?) + .add_directive(format!("pgrx_utils={}", log_level).parse()?) } }; diff --git a/cargo-pgrx/src/manifest.rs b/cargo-pgrx/src/manifest.rs index 8b38c45ad..8b8b6e28c 100644 --- a/cargo-pgrx/src/manifest.rs +++ b/cargo-pgrx/src/manifest.rs @@ -118,8 +118,8 @@ pub(crate) fn modify_features_for_version( } } -pub(crate) fn pg_config_and_version<'a>( - pgrx: &'a Pgrx, +pub(crate) fn pg_config_and_version( + pgrx: &Pgrx, manifest: &Manifest, specified_pg_version: Option, user_features: Option<&mut Features>, @@ -172,7 +172,7 @@ pub(crate) fn pg_config_and_version<'a>( // we have determined a Postgres version modify_features_for_version(pgrx, user_features, manifest, &pg_version, false); - let pg_config = pgrx.get(&pg_version.label())?; + let pg_config = pgrx.get(pg_version.label())?; if verbose { display_version_info(&pg_config, &pg_version); @@ -199,7 +199,7 @@ pub(crate) fn get_package_manifest( package_nane: Option<&String>, manifest_path: Option>, ) -> eyre::Result<(Manifest, PathBuf)> { - let metadata = crate::metadata::metadata(&features, manifest_path.as_ref()) + let metadata = crate::metadata::metadata(features, manifest_path.as_ref()) .wrap_err("couldn't get cargo metadata")?; crate::metadata::validate(manifest_path.as_ref(), &metadata)?; let package_manifest_path = crate::manifest::manifest_path(&metadata, package_nane) diff --git a/pgrx-examples/aggregate/src/lib.rs b/pgrx-examples/aggregate/src/lib.rs index c9ba56c1e..0af3c474e 100644 --- a/pgrx-examples/aggregate/src/lib.rs +++ b/pgrx-examples/aggregate/src/lib.rs @@ -18,6 +18,7 @@ pgrx::pg_module_magic!(); #[derive(Copy, Clone, PostgresType, Serialize, Deserialize)] #[pgvarlena_inoutfuncs] +#[derive(Default)] pub struct IntegerAvgState { sum: i32, n: i32, @@ -136,12 +137,6 @@ impl Aggregate for IntegerAvgState { // } } -impl Default for IntegerAvgState { - fn default() -> Self { - Self { sum: 0, n: 0 } - } -} - #[cfg(any(test, feature = "pg_test"))] #[pg_schema] mod tests { diff --git a/pgrx-examples/arrays/src/lib.rs b/pgrx-examples/arrays/src/lib.rs index a90f78121..f40e54f85 100644 --- a/pgrx-examples/arrays/src/lib.rs +++ b/pgrx-examples/arrays/src/lib.rs @@ -37,7 +37,7 @@ fn default_array() -> Vec { #[pg_extern(requires = [ default_array, ])] fn sum_array(input: default!(Array, "default_array()")) -> i64 { - let mut sum = 0 as i64; + let mut sum = 0_i64; for i in input { sum += i.unwrap_or(-1) as i64; @@ -48,7 +48,7 @@ fn sum_array(input: default!(Array, "default_array()")) -> i64 { #[pg_extern] fn sum_vec(mut input: Vec>) -> i64 { - let mut sum = 0 as i64; + let mut sum = 0_i64; input.push(Some(6)); @@ -66,14 +66,11 @@ fn static_names() -> Vec> { #[pg_extern] fn static_names_set() -> SetOfIterator<'static, Vec>> { - SetOfIterator::new( - vec![ - vec![Some("Brandy"), Some("Sally"), None, Some("Anchovy")], - vec![Some("Eric"), Some("David")], - vec![Some("ZomboDB"), Some("PostgreSQL"), Some("Elasticsearch")], - ] - .into_iter(), - ) + SetOfIterator::new(vec![ + vec![Some("Brandy"), Some("Sally"), None, Some("Anchovy")], + vec![Some("Eric"), Some("David")], + vec![Some("ZomboDB"), Some("PostgreSQL"), Some("Elasticsearch")], + ]) } #[pg_extern] @@ -88,7 +85,7 @@ fn i32_array_with_nulls() -> Vec> { #[pg_extern] fn strip_nulls(input: Vec>) -> Vec { - input.into_iter().filter(|i| i.is_some()).map(|i| i.unwrap()).collect() + input.into_iter().flatten().collect() } #[derive(PostgresType, Serialize, Deserialize, Debug, Eq, PartialEq)] @@ -115,17 +112,17 @@ mod vectors { #[pg_extern] fn sum_vector_array(input: Array) -> f32 { - input.iter_deny_null().map(|v| v as f32).sum() + input.iter_deny_null().sum() } #[pg_extern] fn sum_vector_vec(input: Vec) -> f32 { - input.into_iter().map(|v| v as f32).sum() + input.into_iter().sum() } #[pg_extern] fn sum_vector_slice(input: Array) -> Result { - Ok(input.as_slice()?.iter().map(|v| *v as f32).sum()) + Ok(input.as_slice()?.iter().copied().sum()) } #[pg_extern] diff --git a/pgrx-examples/bad_ideas/src/lib.rs b/pgrx-examples/bad_ideas/src/lib.rs index 9f2d4e9d5..976083510 100644 --- a/pgrx-examples/bad_ideas/src/lib.rs +++ b/pgrx-examples/bad_ideas/src/lib.rs @@ -115,10 +115,8 @@ pub unsafe extern "C" fn _PG_init() { extern "C" fn random_abort_callback(event: pg_sys::XactEvent, _arg: *mut std::os::raw::c_void) { // info!("in global xact callback: event={}", event); - if event == pg_sys::XactEvent_XACT_EVENT_PRE_COMMIT { - if rand::random::() { - // panic!("aborting transaction"); - } + if event == pg_sys::XactEvent_XACT_EVENT_PRE_COMMIT && rand::random::() { + // panic!("aborting transaction"); } } diff --git a/pgrx-examples/custom_types/src/fixed_size.rs b/pgrx-examples/custom_types/src/fixed_size.rs index 0cf02d773..678411dde 100644 --- a/pgrx-examples/custom_types/src/fixed_size.rs +++ b/pgrx-examples/custom_types/src/fixed_size.rs @@ -32,7 +32,7 @@ impl PgVarlenaInOutFuncs for FixedF32Array { fn output(&self, buffer: &mut StringInfo) { self.array.iter().for_each(|v| { - if buffer.len() > 0 { + if !buffer.is_empty() { buffer.push(','); } buffer.push_str(&v.to_string()); diff --git a/pgrx-examples/custom_types/src/hstore_clone.rs b/pgrx-examples/custom_types/src/hstore_clone.rs index d5f8325f7..605e6e929 100644 --- a/pgrx-examples/custom_types/src/hstore_clone.rs +++ b/pgrx-examples/custom_types/src/hstore_clone.rs @@ -13,14 +13,9 @@ use serde::*; use std::collections::HashMap; #[derive(PostgresType, Serialize, Deserialize, Debug, Eq, PartialEq)] +#[derive(Default)] pub struct RustStore(HashMap); -impl Default for RustStore { - fn default() -> Self { - RustStore(HashMap::default()) - } -} - #[pg_extern] fn rstore(key: String, value: String) -> RustStore { RustStore(hashmap!(key => value)) @@ -35,7 +30,7 @@ fn rstore_put(rstore: Option, key: String, value: String) -> RustStor #[pg_extern] fn rstore_get(rstore: Option, key: String) -> Option { - rstore.map_or(None, |rstore| rstore.0.get(&key).cloned()) + rstore.and_then(|rstore| rstore.0.get(&key).cloned()) } #[pg_extern] @@ -64,7 +59,7 @@ fn rstore_table( rstore: Option, ) -> TableIterator<'static, (name!(key, String), name!(value, String))> { match rstore { - Some(rstore) => TableIterator::new(rstore.0.into_iter()), + Some(rstore) => TableIterator::new(rstore.0), None => TableIterator::once((String::new(), String::new())), } } diff --git a/pgrx-examples/custom_types/src/ordered.rs b/pgrx-examples/custom_types/src/ordered.rs index 6f2f6ddcd..66d4e3025 100644 --- a/pgrx-examples/custom_types/src/ordered.rs +++ b/pgrx-examples/custom_types/src/ordered.rs @@ -40,12 +40,10 @@ impl Ord for OrderedThing { } else { std::cmp::Ordering::Greater } + } else if starts_lower(other) { + std::cmp::Ordering::Less } else { - if starts_lower(other) { - std::cmp::Ordering::Less - } else { - self.item.cmp(&other.item).reverse() - } + self.item.cmp(&other.item).reverse() } } } diff --git a/pgrx-examples/errors/src/lib.rs b/pgrx-examples/errors/src/lib.rs index 4c0fe36ff..cd5687f39 100644 --- a/pgrx-examples/errors/src/lib.rs +++ b/pgrx-examples/errors/src/lib.rs @@ -14,7 +14,7 @@ pgrx::pg_module_magic!(); #[pg_extern] fn array_with_null_and_panic(input: Vec>) -> i64 { - let mut sum = 0 as i64; + let mut sum = 0_i64; for i in input { sum += i.expect("NULL elements in input array are not supported") as i64; diff --git a/pgrx-examples/numeric/src/lib.rs b/pgrx-examples/numeric/src/lib.rs index dee38645e..6885a3034 100644 --- a/pgrx-examples/numeric/src/lib.rs +++ b/pgrx-examples/numeric/src/lib.rs @@ -33,7 +33,7 @@ fn math() -> Numeric<10, 3> { n *= 5; n -= 2.234; - n /= 4 as i128; + n /= 4_i128; n %= 19; n += 99.42; diff --git a/pgrx-examples/operators/src/pgvarlena.rs b/pgrx-examples/operators/src/pgvarlena.rs index 255c64d70..4ca944b42 100644 --- a/pgrx-examples/operators/src/pgvarlena.rs +++ b/pgrx-examples/operators/src/pgvarlena.rs @@ -112,19 +112,19 @@ mod tests { "SELECT '1;2;3;[1,2,3,4,5]'::pgvarlenathing < '2;2;3;[1,2,3,4,5]'::pgvarlenathing", )? .unwrap(); - assert_eq!(lt, true); + assert!(lt); let gt = Spi::get_one::( "SELECT '2;2;3;[1,2,3,4,5]'::pgvarlenathing > '1;2;3;[1,2,3,4,5]'::pgvarlenathing", )? .unwrap(); - assert_eq!(gt, true); + assert!(gt); let eq = Spi::get_one::( "SELECT '1;2;3;[1,2,3,4,5]'::pgvarlenathing = '1;2;3;[1,2,3,4,5]'::pgvarlenathing", )? .unwrap(); - assert_eq!(eq, true); + assert!(eq); Ok(()) } diff --git a/pgrx-examples/pgtrybuilder/src/lib.rs b/pgrx-examples/pgtrybuilder/src/lib.rs index 80f2ccdee..f1a801a1f 100644 --- a/pgrx-examples/pgtrybuilder/src/lib.rs +++ b/pgrx-examples/pgtrybuilder/src/lib.rs @@ -26,7 +26,7 @@ fn is_valid_number(i: i32) -> i32 { .finally(|| finished = true) .execute(); - assert_eq!(finished, true); + assert!(finished); result } diff --git a/pgrx-examples/shmem/src/lib.rs b/pgrx-examples/shmem/src/lib.rs index e34d015a5..576fdd122 100644 --- a/pgrx-examples/shmem/src/lib.rs +++ b/pgrx-examples/shmem/src/lib.rs @@ -22,15 +22,12 @@ pgrx::pg_module_magic!(); #[derive(Copy, Clone)] // This is for general Postgres type support -- not strictly necessary if the type is not exposed via SQL #[derive(PostgresType, Serialize, Deserialize)] +#[derive(Default)] pub struct Pgtest { value1: i32, value2: i32, } -impl Default for Pgtest { - fn default() -> Self { - Pgtest { value1: 0, value2: 0 } - } -} + unsafe impl PGRXSharedMemory for Pgtest {} static DEQUE: PgLwLock> = PgLwLock::new(); @@ -52,7 +49,7 @@ pub extern "C" fn _PG_init() { #[pg_extern] fn vec_select() -> SetOfIterator<'static, Pgtest> { - SetOfIterator::new(VEC.share().iter().map(|i| *i).collect::>().into_iter()) + SetOfIterator::new(VEC.share().iter().copied().collect::>()) } #[pg_extern] @@ -63,9 +60,9 @@ fn vec_count() -> i32 { #[pg_extern] fn vec_drain() -> SetOfIterator<'static, Pgtest> { let mut vec = VEC.exclusive(); - let r = vec.iter().map(|i| *i).collect::>(); + let r = vec.iter().copied().collect::>(); vec.clear(); - SetOfIterator::new(r.into_iter()) + SetOfIterator::new(r) } #[pg_extern] @@ -80,7 +77,7 @@ fn vec_pop() -> Option { #[pg_extern] fn deque_select() -> SetOfIterator<'static, Pgtest> { - SetOfIterator::new(DEQUE.share().iter().map(|i| *i).collect::>().into_iter()) + SetOfIterator::new(DEQUE.share().iter().copied().collect::>()) } #[pg_extern] @@ -91,9 +88,9 @@ fn deque_count() -> i32 { #[pg_extern] fn deque_drain() -> SetOfIterator<'static, Pgtest> { let mut vec = DEQUE.exclusive(); - let r = vec.iter().map(|i| *i).collect::>(); + let r = vec.iter().copied().collect::>(); vec.clear(); - SetOfIterator::new(r.into_iter()) + SetOfIterator::new(r) } #[pg_extern] @@ -134,7 +131,7 @@ fn hash_get(key: i32) -> Option { #[pg_extern] fn struct_get() -> Pgtest { - STRUCT.share().clone() + *STRUCT.share() } #[pg_extern] @@ -144,7 +141,7 @@ fn struct_set(value1: i32, value2: i32) { #[pg_extern] fn primitive_get() -> i32 { - PRIMITIVE.share().clone() + *PRIMITIVE.share() } #[pg_extern] diff --git a/pgrx-examples/spi/src/lib.rs b/pgrx-examples/spi/src/lib.rs index b0c6a206b..4611f9350 100644 --- a/pgrx-examples/spi/src/lib.rs +++ b/pgrx-examples/spi/src/lib.rs @@ -57,7 +57,7 @@ fn spi_return_query() -> Result< .map(|row| (row["oid"].value(), row[2].value())) .collect::>()) }) - .map(|results| TableIterator::new(results)) + .map(TableIterator::new) } #[pg_extern(immutable, parallel_safe)] diff --git a/pgrx-examples/spi_srf/src/lib.rs b/pgrx-examples/spi_srf/src/lib.rs index a536c2b94..50ef3dee5 100644 --- a/pgrx-examples/spi_srf/src/lib.rs +++ b/pgrx-examples/spi_srf/src/lib.rs @@ -56,9 +56,9 @@ fn calculate_human_years() -> Result< Spi::connect(|client| { let mut results = Vec::new(); - let mut tup_table = client.select(query, None, None)?; + let tup_table = client.select(query, None, None)?; - while let Some(row) = tup_table.next() { + for row in tup_table { let dog_name = row["dog_name"].value::(); let dog_age = row["dog_age"].value::()?.expect("dog_age was null"); let dog_breed = row["dog_breed"].value::(); @@ -66,7 +66,7 @@ fn calculate_human_years() -> Result< results.push((dog_name, dog_age, dog_breed, human_age)); } - Ok(TableIterator::new(results.into_iter())) + Ok(TableIterator::new(results)) }) } @@ -98,7 +98,7 @@ fn filter_by_breed( let filtered = tup_table .map(|row| (row["dog_name"].value(), row["dog_age"].value(), row["dog_breed"].value())) .collect::>(); - Ok(TableIterator::new(filtered.into_iter())) + Ok(TableIterator::new(filtered)) }) } diff --git a/pgrx-examples/strings/src/lib.rs b/pgrx-examples/strings/src/lib.rs index eacd38670..868cffc2d 100644 --- a/pgrx-examples/strings/src/lib.rs +++ b/pgrx-examples/strings/src/lib.rs @@ -35,12 +35,12 @@ fn append(mut input: String, extra: &str) -> String { #[pg_extern] fn split(input: &'static str, pattern: &str) -> Vec<&'static str> { - input.split_terminator(pattern).into_iter().collect() + input.split_terminator(pattern).collect() } #[pg_extern] fn split_set<'a>(input: &'a str, pattern: &'a str) -> SetOfIterator<'a, &'a str> { - SetOfIterator::new(input.split_terminator(pattern).into_iter()) + SetOfIterator::new(input.split_terminator(pattern)) } #[pg_extern] diff --git a/pgrx-pg-config/src/lib.rs b/pgrx-pg-config/src/lib.rs index d9ca553e4..d6a1a79cd 100644 --- a/pgrx-pg-config/src/lib.rs +++ b/pgrx-pg-config/src/lib.rs @@ -268,7 +268,7 @@ impl PgConfig { } else { PgMinorVersion::Release(minor) }; - return Ok((major, minor)); + Ok((major, minor)) } fn get_version(&self) -> eyre::Result<(u16, PgMinorVersion)> { @@ -611,7 +611,7 @@ impl Pgrx { /// such as `pg14` or `pg15` pub fn is_feature_flag(&self, label: &str) -> bool { for pgver in SUPPORTED_VERSIONS() { - if label == &format!("pg{}", pgver.major) { + if label == format!("pg{}", pgver.major) { return true; } } @@ -738,7 +738,7 @@ fn does_db_exist(pg_config: &PgConfig, dbname: &str) -> eyre::Result { .arg("-c") .arg(&format!( "select count(*) from pg_database where datname = '{}';", - dbname.replace("'", "''") + dbname.replace('\'', "''") )) .stdout(Stdio::piped()) .stderr(Stdio::piped()); @@ -747,15 +747,15 @@ fn does_db_exist(pg_config: &PgConfig, dbname: &str) -> eyre::Result { let output = command.output()?; if !output.status.success() { - return Err(eyre!( + Err(eyre!( "problem checking if database '{}' exists: {}\n\n{}{}", dbname, command_str, String::from_utf8(output.stdout).unwrap(), String::from_utf8(output.stderr).unwrap() - )); + )) } else { - let count = i32::from_str(&String::from_utf8(output.stdout).unwrap().trim()) + let count = i32::from_str(String::from_utf8(output.stdout).unwrap().trim()) .wrap_err("result is not a number")?; Ok(count > 0) } diff --git a/pgrx-tests/src/framework.rs b/pgrx-tests/src/framework.rs index df42cb085..911af3c39 100644 --- a/pgrx-tests/src/framework.rs +++ b/pgrx-tests/src/framework.rs @@ -60,7 +60,7 @@ where Option<&[&(dyn postgres::types::ToSql + Sync)]>, ) -> Result, { - let result = f(query.clone(), query_params.clone()); + let result = f(query.clone(), query_params); match result { Ok(result) => Ok(result), @@ -103,7 +103,7 @@ where Err(eyre!(message)) } else { - return Err(e).wrap_err("non-DbError"); + Err(e).wrap_err("non-DbError") } } } @@ -161,7 +161,7 @@ pub fn run_test( (pg_location, rust_location, received_error_message.to_string()) } else { - ("".to_string(), "".to_string(), format!("{error_as_string}")) + ("".to_string(), "".to_string(), error_as_string.to_string()) }; // wait a second for Postgres to get log messages written to stderr @@ -247,7 +247,7 @@ pub fn client() -> eyre::Result<(postgres::Client, String)> { .host(pg_config.host()) .port(pg_config.test_port().expect("unable to determine test port")) .user(&get_pg_user()) - .dbname(&get_pg_dbname()) + .dbname(get_pg_dbname()) .connect(postgres::NoTls) .wrap_err("Error connecting to Postgres")?; @@ -550,7 +550,7 @@ fn monitor_pg(mut command: Command, cmd_string: String, loglines: LogLines) -> S // wait for the database to say its ready to start up let reader = BufReader::new(child.stderr.take().expect("couldn't take postmaster stderr")); - let regex = regex::Regex::new(r#"\[.*?\] \[.*?\] \[(?P.*?)\]"#).unwrap(); + let regex = regex::Regex::new(r"\[.*?\] \[.*?\] \[(?P.*?)\]").unwrap(); let mut is_started_yet = false; let mut lines = reader.lines(); while let Some(Ok(line)) = lines.next() { @@ -584,7 +584,7 @@ fn monitor_pg(mut command: Command, cmd_string: String, loglines: LogLines) -> S // } let mut loglines = loglines.lock().unwrap(); - let session_lines = loglines.entry(session_id).or_insert_with(Vec::new); + let session_lines = loglines.entry(session_id).or_default(); session_lines.push(line); } @@ -668,7 +668,7 @@ fn get_extension_name() -> eyre::Result { // https://github.com/rust-lang/cargo/issues/45 let path = PathBuf::from(dir).join("Cargo.toml"); let name = pgrx_pg_config::cargo::read_manifest(path)?.lib_name()?; - Ok(name.replace("-", "_")) + Ok(name.replace('-', "_")) } fn get_pgdata_path() -> eyre::Result { @@ -680,7 +680,7 @@ fn get_pgdata_path() -> eyre::Result { fn get_pid_file() -> eyre::Result { let mut pgdata = get_pgdata_path()?; pgdata.push("postmaster.pid"); - return Ok(pgdata); + Ok(pgdata) } pub(crate) fn get_pg_dbname() -> &'static str { @@ -697,10 +697,7 @@ pub fn get_named_capture( name: &'static str, against: &str, ) -> Option { - match regex.captures(against) { - Some(cap) => Some(cap[name].to_string()), - None => None, - } + regex.captures(against).map(|cap| cap[name].to_string()) } fn get_cargo_test_features() -> eyre::Result { @@ -754,7 +751,7 @@ fn get_cargo_args() -> Vec { && !process.cmd().iter().any(|arg| arg == "pgrx") { // ... do we want its args - return process.cmd().iter().cloned().collect(); + return process.cmd().to_vec(); } }