Skip to content

Added clippy to CI and fixed all clippy warnings #613

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ jobs:
- run:
name: "Lint"
command: "cargo fmt --check"
- run:
name: "Clippy"
command: "cargo clippy --all --all-targets -- -Dwarnings"
- run:
name: "Tests"
command: "cargo clean && cargo build && cargo test && bash .circleci/run_tests.sh && .circleci/generate_coverage.sh"
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Thank you for contributing! Just a few tips here:

1. `cargo fmt` your code before opening up a PR
1. `cargo fmt` and `cargo clippy` your code before opening up a PR
2. Run the test suite (e.g. `pgbench`) to make sure everything still works. The tests are in `.circleci/run_tests.sh`.
3. Performance is important, make sure there are no regressions in your branch vs. `main`.

Expand Down
7 changes: 3 additions & 4 deletions src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ where
{
let mut res = BytesMut::new();

let detail_msg = vec![
let detail_msg = [
"",
"SHOW HELP|CONFIG|DATABASES|POOLS|CLIENTS|SERVERS|USERS|VERSION",
// "SHOW PEERS|PEER_POOLS", // missing PEERS|PEER_POOLS
Expand All @@ -301,7 +301,6 @@ where
// "KILL <db>",
// "SUSPEND",
"SHUTDOWN",
// "WAIT_CLOSE [<db>]", // missing
];

res.put(notify("Console usage", detail_msg.join("\n\t")));
Expand Down Expand Up @@ -802,7 +801,7 @@ where
T: tokio::io::AsyncWrite + std::marker::Unpin,
{
let parts: Vec<&str> = match tokens.len() == 2 {
true => tokens[1].split(",").map(|part| part.trim()).collect(),
true => tokens[1].split(',').map(|part| part.trim()).collect(),
false => Vec::new(),
};

Expand Down Expand Up @@ -865,7 +864,7 @@ where
T: tokio::io::AsyncWrite + std::marker::Unpin,
{
let parts: Vec<&str> = match tokens.len() == 2 {
true => tokens[1].split(",").map(|part| part.trim()).collect(),
true => tokens[1].split(',').map(|part| part.trim()).collect(),
false => Vec::new(),
};

Expand Down
39 changes: 16 additions & 23 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ pub async fn client_entrypoint(
// Client requested a TLS connection.
Ok((ClientConnectionType::Tls, _)) => {
// TLS settings are configured, will setup TLS now.
if tls_certificate != None {
if tls_certificate.is_some() {
debug!("Accepting TLS request");

let mut yes = BytesMut::new();
Expand Down Expand Up @@ -448,7 +448,7 @@ where
None => "pgcat",
};

let client_identifier = ClientIdentifier::new(&application_name, &username, &pool_name);
let client_identifier = ClientIdentifier::new(application_name, username, pool_name);

let admin = ["pgcat", "pgbouncer"]
.iter()
Expand Down Expand Up @@ -795,7 +795,7 @@ where
let mut will_prepare = false;

let client_identifier = ClientIdentifier::new(
&self.server_parameters.get_application_name(),
self.server_parameters.get_application_name(),
&self.username,
&self.pool_name,
);
Expand Down Expand Up @@ -982,15 +982,11 @@ where
}

// Check on plugin results.
match plugin_output {
Some(PluginOutput::Deny(error)) => {
self.buffer.clear();
error_response(&mut self.write, &error).await?;
plugin_output = None;
continue;
}

_ => (),
if let Some(PluginOutput::Deny(error)) = plugin_output {
self.buffer.clear();
error_response(&mut self.write, &error).await?;
plugin_output = None;
continue;
};

// Check if the pool is paused and wait until it's resumed.
Expand Down Expand Up @@ -1267,7 +1263,7 @@ where

// Safe to unwrap because we know this message has a certain length and has the code
// This reads the first byte without advancing the internal pointer and mutating the bytes
let code = *message.get(0).unwrap() as char;
let code = *message.first().unwrap() as char;

trace!("Message: {}", code);

Expand Down Expand Up @@ -1325,7 +1321,7 @@ where
self.stats.transaction();
server
.stats()
.transaction(&self.server_parameters.get_application_name());
.transaction(self.server_parameters.get_application_name());

// Release server back to the pool if we are in transaction mode.
// If we are in session mode, we keep the server until the client disconnects.
Expand Down Expand Up @@ -1400,13 +1396,10 @@ where
let close: Close = (&message).try_into()?;

if close.is_prepared_statement() && !close.anonymous() {
match self.prepared_statements.get(&close.name) {
Some(parse) => {
server.will_close(&parse.generated_name);
}

if let Some(parse) = self.prepared_statements.get(&close.name) {
server.will_close(&parse.generated_name);
} else {
// A prepared statement slipped through? Not impossible, since we don't support PREPARE yet.
None => (),
};
}
}
Expand Down Expand Up @@ -1445,7 +1438,7 @@ where

self.buffer.put(&message[..]);

let first_message_code = (*self.buffer.get(0).unwrap_or(&0)) as char;
let first_message_code = (*self.buffer.first().unwrap_or(&0)) as char;

// Almost certainly true
if first_message_code == 'P' && !prepared_statements_enabled {
Expand Down Expand Up @@ -1477,7 +1470,7 @@ where
self.stats.transaction();
server
.stats()
.transaction(&self.server_parameters.get_application_name());
.transaction(self.server_parameters.get_application_name());

// Release server back to the pool if we are in transaction mode.
// If we are in session mode, we keep the server until the client disconnects.
Expand Down Expand Up @@ -1739,7 +1732,7 @@ where
client_stats.query();
server.stats().query(
Instant::now().duration_since(query_start).as_millis() as u64,
&self.server_parameters.get_application_name(),
self.server_parameters.get_application_name(),
);

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion src/cmd_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub struct Args {
}

pub fn parse() -> Args {
return Args::parse();
Args::parse()
}

#[derive(ValueEnum, Clone, Debug)]
Expand Down
103 changes: 45 additions & 58 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,18 +236,14 @@ impl Default for User {

impl User {
fn validate(&self) -> Result<(), Error> {
match self.min_pool_size {
Some(min_pool_size) => {
if min_pool_size > self.pool_size {
error!(
"min_pool_size of {} cannot be larger than pool_size of {}",
min_pool_size, self.pool_size
);
return Err(Error::BadConfig);
}
if let Some(min_pool_size) = self.min_pool_size {
if min_pool_size > self.pool_size {
error!(
"min_pool_size of {} cannot be larger than pool_size of {}",
min_pool_size, self.pool_size
);
return Err(Error::BadConfig);
}

None => (),
};

Ok(())
Expand Down Expand Up @@ -677,9 +673,9 @@ impl Pool {
Some(key) => {
// No quotes in the key so we don't have to compare quoted
// to unquoted idents.
let key = key.replace("\"", "");
let key = key.replace('\"', "");

if key.split(".").count() != 2 {
if key.split('.').count() != 2 {
error!(
"automatic_sharding_key '{}' must be fully qualified, e.g. t.{}`",
key, key
Expand All @@ -692,17 +688,14 @@ impl Pool {
None => None,
};

match self.default_shard {
DefaultShard::Shard(shard_number) => {
if shard_number >= self.shards.len() {
error!("Invalid shard {:?}", shard_number);
return Err(Error::BadConfig);
}
if let DefaultShard::Shard(shard_number) = self.default_shard {
if shard_number >= self.shards.len() {
error!("Invalid shard {:?}", shard_number);
return Err(Error::BadConfig);
}
_ => (),
}

for (_, user) in &self.users {
for user in self.users.values() {
user.validate()?;
}

Expand Down Expand Up @@ -777,8 +770,8 @@ impl<'de> serde::Deserialize<'de> for DefaultShard {
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
if s.starts_with("shard_") {
let shard = s[6..].parse::<usize>().map_err(serde::de::Error::custom)?;
if let Some(s) = s.strip_prefix("shard_") {
Copy link
Contributor

@levkk levkk Oct 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Way better. I wonder how clippy figured this out, pretty impressive.

let shard = s.parse::<usize>().map_err(serde::de::Error::custom)?;
return Ok(DefaultShard::Shard(shard));
}

Expand Down Expand Up @@ -874,7 +867,7 @@ pub trait Plugin {
impl std::fmt::Display for Plugins {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
fn is_enabled<T: Plugin>(arg: Option<&T>) -> bool {
if let Some(ref arg) = arg {
if let Some(arg) = arg {
arg.is_enabled()
} else {
false
Expand Down Expand Up @@ -955,6 +948,7 @@ pub struct Query {
}

impl Query {
#[allow(clippy::needless_range_loop)]
pub fn substitute(&mut self, db: &str, user: &str) {
for col in self.result.iter_mut() {
for i in 0..col.len() {
Expand Down Expand Up @@ -1079,8 +1073,8 @@ impl From<&Config> for std::collections::HashMap<String, String> {
(
format!("pools.{:?}.users", pool_name),
pool.users
.iter()
.map(|(_username, user)| &user.username)
.values()
.map(|user| &user.username)
.cloned()
.collect::<Vec<String>>()
.join(", "),
Expand Down Expand Up @@ -1165,13 +1159,9 @@ impl Config {
Some(tls_certificate) => {
info!("TLS certificate: {}", tls_certificate);

match self.general.tls_private_key.clone() {
Some(tls_private_key) => {
info!("TLS private key: {}", tls_private_key);
info!("TLS support is enabled");
}

None => (),
if let Some(tls_private_key) = self.general.tls_private_key.clone() {
info!("TLS private key: {}", tls_private_key);
info!("TLS support is enabled");
}
}

Expand Down Expand Up @@ -1206,8 +1196,8 @@ impl Config {
pool_name,
pool_config
.users
.iter()
.map(|(_, user_cfg)| user_cfg.pool_size)
.values()
.map(|user_cfg| user_cfg.pool_size)
.sum::<u32>()
.to_string()
);
Expand Down Expand Up @@ -1377,34 +1367,31 @@ impl Config {
}

// Validate TLS!
match self.general.tls_certificate.clone() {
Some(tls_certificate) => {
match load_certs(Path::new(&tls_certificate)) {
Ok(_) => {
// Cert is okay, but what about the private key?
match self.general.tls_private_key.clone() {
Some(tls_private_key) => match load_keys(Path::new(&tls_private_key)) {
Ok(_) => (),
Err(err) => {
error!("tls_private_key is incorrectly configured: {:?}", err);
return Err(Error::BadConfig);
}
},

None => {
error!("tls_certificate is set, but the tls_private_key is not");
if let Some(tls_certificate) = self.general.tls_certificate.clone() {
match load_certs(Path::new(&tls_certificate)) {
Ok(_) => {
// Cert is okay, but what about the private key?
match self.general.tls_private_key.clone() {
Some(tls_private_key) => match load_keys(Path::new(&tls_private_key)) {
Ok(_) => (),
Err(err) => {
error!("tls_private_key is incorrectly configured: {:?}", err);
return Err(Error::BadConfig);
}
};
}
},

Err(err) => {
error!("tls_certificate is incorrectly configured: {:?}", err);
return Err(Error::BadConfig);
}
None => {
error!("tls_certificate is set, but the tls_private_key is not");
return Err(Error::BadConfig);
}
};
}

Err(err) => {
error!("tls_certificate is incorrectly configured: {:?}", err);
return Err(Error::BadConfig);
}
}
None => (),
};

for pool in self.pools.values_mut() {
Expand Down
Loading