Cleanup format arguments (#2650)

Inlined format args make code more readable, and code more compact.

I ran this clippy command to fix most cases, and then cleaned up a few trailing commas and uncaught edge cases.

```
cargo clippy --bins --examples  --benches --tests --lib --workspace --fix -- -A clippy::all -W clippy::uninlined_format_args
```
This commit is contained in:
Yuri Astrakhan 2023-07-31 22:27:04 +02:00 committed by GitHub
parent 9463b7592f
commit a824e8468c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
80 changed files with 270 additions and 307 deletions

View file

@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {
match args.cmd {
Some(Command::Add { description }) => {
println!("Adding new todo with description '{}'", &description);
println!("Adding new todo with description '{description}'");
let todo_id = add_todo(&pool, description).await?;
println!("Added new todo with id {}", todo_id);
println!("Added new todo with id {todo_id}");
}
Some(Command::Done { id }) => {
println!("Marking todo {} as done", id);
println!("Marking todo {id} as done");
if complete_todo(&pool, id).await? {
println!("Todo {} is marked as done", id);
println!("Todo {id} is marked as done");
} else {
println!("Invalid id {}", id);
println!("Invalid id {id}");
}
}
None => {

View file

@ -49,7 +49,7 @@ impl IntoResponse for Error {
// Normally you wouldn't just print this, but it's useful for debugging without
// using a logging framework.
println!("API error: {:?}", self);
println!("API error: {self:?}");
(
self.status_code(),

View file

@ -53,14 +53,14 @@ pub async fn response_json(resp: &mut Response<BoxBody>) -> serde_json::Value {
pub fn expect_string(value: &serde_json::Value) -> &str {
value
.as_str()
.unwrap_or_else(|| panic!("expected string, got {:?}", value))
.unwrap_or_else(|| panic!("expected string, got {value:?}"))
}
#[track_caller]
pub fn expect_uuid(value: &serde_json::Value) -> Uuid {
expect_string(value)
.parse::<Uuid>()
.unwrap_or_else(|e| panic!("failed to parse UUID from {:?}: {}", value, e))
.unwrap_or_else(|e| panic!("failed to parse UUID from {value:?}: {e}"))
}
#[track_caller]
@ -68,5 +68,5 @@ pub fn expect_rfc3339_timestamp(value: &serde_json::Value) -> OffsetDateTime {
let s = expect_string(value);
OffsetDateTime::parse(s, &Rfc3339)
.unwrap_or_else(|e| panic!("failed to parse RFC-3339 timestamp from {:?}: {}", value, e))
.unwrap_or_else(|e| panic!("failed to parse RFC-3339 timestamp from {value:?}: {e}"))
}

View file

@ -157,7 +157,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
terminal.show_cursor()?;
if let Err(err) = res {
println!("{:?}", err)
println!("{err:?}")
}
Ok(())

View file

@ -41,7 +41,7 @@ async fn main() -> anyhow::Result<()> {
.await?;
for post_with_author in posts_with_authors {
println!("{}", post_with_author);
println!("{post_with_author}");
}
Ok(())

View file

@ -47,7 +47,7 @@ async fn main() -> anyhow::Result<()> {
);
let person_id = add_person(&pool, person).await?;
println!("Added new person with ID {}", person_id);
println!("Added new person with ID {person_id}");
}
None => {
println!("Printing all people");

View file

@ -38,7 +38,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut counter = 0usize;
loop {
let notification = listener.recv().await?;
println!("[from recv]: {:?}", notification);
println!("[from recv]: {notification:?}");
counter += 1;
if counter >= 3 {
@ -58,7 +58,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::select! {
res = stream.try_next() => {
if let Some(notification) = res? {
println!("[from stream]: {:?}", notification);
println!("[from stream]: {notification:?}");
} else {
break;
}
@ -106,5 +106,5 @@ from (
.execute(pool)
.await;
println!("[from notify]: {:?}", res);
println!("[from notify]: {res:?}");
}

View file

@ -39,14 +39,14 @@ async fn handle_command(
&description
)?;
let todo_id = todo_repo.add_todo(description).await?;
writeln!(writer, "Added new todo with id {}", todo_id)?;
writeln!(writer, "Added new todo with id {todo_id}")?;
}
Some(Command::Done { id }) => {
writeln!(writer, "Marking todo {} as done", id)?;
writeln!(writer, "Marking todo {id} as done")?;
if todo_repo.complete_todo(id).await? {
writeln!(writer, "Todo {} is marked as done", id)?;
writeln!(writer, "Todo {id} is marked as done")?;
} else {
writeln!(writer, "Invalid id {}", id)?;
writeln!(writer, "Invalid id {id}")?;
}
}
None => {

View file

@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {
match args.cmd {
Some(Command::Add { description }) => {
println!("Adding new todo with description '{}'", &description);
println!("Adding new todo with description '{description}'");
let todo_id = add_todo(&pool, description).await?;
println!("Added new todo with id {}", todo_id);
println!("Added new todo with id {todo_id}");
}
Some(Command::Done { id }) => {
println!("Marking todo {} as done", id);
println!("Marking todo {id} as done");
if complete_todo(&pool, id).await? {
println!("Todo {} is marked as done", id);
println!("Todo {id} is marked as done");
} else {
println!("Invalid id {}", id);
println!("Invalid id {id}");
}
}
None => {

View file

@ -21,16 +21,16 @@ async fn main() -> anyhow::Result<()> {
match args.cmd {
Some(Command::Add { description }) => {
println!("Adding new todo with description '{}'", &description);
println!("Adding new todo with description '{description}'");
let todo_id = add_todo(&pool, description).await?;
println!("Added new todo with id {}", todo_id);
println!("Added new todo with id {todo_id}");
}
Some(Command::Done { id }) => {
println!("Marking todo {} as done", id);
println!("Marking todo {id} as done");
if complete_todo(&pool, id).await? {
println!("Todo {} is marked as done", id);
println!("Todo {id} is marked as done");
} else {
println!("Invalid id {}", id);
println!("Invalid id {id}");
}
}
None => {

View file

@ -12,7 +12,7 @@ fn bench_pgpool_acquire(c: &mut Criterion) {
let fairness = if fair { "(fair)" } else { "(unfair)" };
group.bench_with_input(
format!("{} concurrent {}", concurrent, fairness),
format!("{concurrent} concurrent {fairness}"),
&(concurrent, fair),
|b, &(concurrent, fair)| do_bench_acquire(b, concurrent, fair),
);
@ -47,7 +47,7 @@ fn do_bench_acquire(b: &mut Bencher, concurrent: u32, fair: bool) {
let conn = match pool.acquire().await {
Ok(conn) => conn,
Err(sqlx::Error::PoolClosed) => break,
Err(e) => panic!("failed to acquire concurrent connection: {}", e),
Err(e) => panic!("failed to acquire concurrent connection: {e}"),
};
// pretend we're using the connection

View file

@ -37,7 +37,7 @@ fn main() -> sqlx::Result<()> {
);
let elapsed = chrono::Utc::now() - start;
println!("elapsed {}", elapsed);
println!("elapsed {elapsed}");
}
Ok(())

View file

@ -73,7 +73,7 @@ fn ask_to_continue(connect_opts: &ConnectOpts) -> bool {
}
}
Err(e) => {
println!("{}", e);
println!("{e}");
return false;
}
}

View file

@ -48,7 +48,7 @@ impl MigrationOrdering {
}
fn sequential(version: i64) -> MigrationOrdering {
Self::Sequential(format!("{:04}", version))
Self::Sequential(format!("{version:04}"))
}
fn file_prefix(&self) -> &str {
@ -149,7 +149,7 @@ pub async fn add(
if !has_existing_migrations {
let quoted_source = if migration_source != "migrations" {
format!("{:?}", migration_source)
format!("{migration_source:?}")
} else {
"".to_string()
};
@ -178,7 +178,7 @@ See: https://docs.rs/sqlx/0.5/sqlx/macro.migrate.html
fn short_checksum(checksum: &[u8]) -> String {
let mut s = String::with_capacity(checksum.len() * 2);
for b in checksum {
write!(&mut s, "{:02x?}", b).expect("should not fail to write to str");
write!(&mut s, "{b:02x?}").expect("should not fail to write to str");
}
s
}
@ -341,7 +341,7 @@ pub async fn run(
style(migration.version).cyan(),
style(migration.migration_type.label()).green(),
migration.description,
style(format!("({:?})", elapsed)).dim()
style(format!("({elapsed:?})")).dim()
);
}
}
@ -431,7 +431,7 @@ pub async fn revert(
style(migration.version).cyan(),
style(migration.migration_type.label()).green(),
migration.description,
style(format!("({:?})", elapsed)).dim()
style(format!("({elapsed:?})")).dim()
);
is_applied = true;
@ -467,9 +467,8 @@ pub fn build_script(migration_source: &str, force: bool) -> anyhow::Result<()> {
r#"// generated by `sqlx migrate build-script`
fn main() {{
// trigger recompilation when a new migration is added
println!("cargo:rerun-if-changed={}");
println!("cargo:rerun-if-changed={migration_source}");
}}"#,
migration_source
);
fs::write("build.rs", contents)?;

View file

@ -30,7 +30,7 @@ pub fn add_file(name: &str) -> anyhow::Result<()> {
file.write_all(b"-- Add migration script here")
.context("Could not write to file")?;
println!("Created migration: '{}'", file_name);
println!("Created migration: '{file_name}'");
Ok(())
}
@ -143,7 +143,7 @@ fn load_migrations() -> anyhow::Result<Vec<Migration>> {
if let Some(ext) = e.path().extension() {
if ext != "sql" {
println!("Wrong ext: {:?}", ext);
println!("Wrong ext: {ext:?}");
continue;
}
} else {

View file

@ -252,7 +252,7 @@ fn minimal_project_clean(
for file in touch_paths {
let now = filetime::FileTime::now();
filetime::set_file_times(&file, now, now)
.with_context(|| format!("Failed to update mtime for {:?}", file))?;
.with_context(|| format!("Failed to update mtime for {file:?}"))?;
}
// Clean entire packages.

View file

@ -139,6 +139,6 @@ pub(crate) fn from_url(url: &Url) -> crate::Result<&'static AnyDriver> {
.iter()
.find(|driver| driver.url_schemes.contains(&url.scheme()))
.ok_or_else(|| {
Error::Configuration(format!("no driver found for URL scheme {:?}", scheme).into())
Error::Configuration(format!("no driver found for URL scheme {scheme:?}").into())
})
}

View file

@ -61,7 +61,7 @@ impl FromStr for AnyKind {
Err(Error::Configuration("database URL has the scheme of a MSSQL database but the `mssql` feature is not enabled".into()))
}
_ => Err(Error::Configuration(format!("unrecognized database url: {:?}", url).into()))
_ => Err(Error::Configuration(format!("unrecognized database url: {url:?}").into()))
}
}
}

View file

@ -60,7 +60,7 @@ impl Row for AnyRow {
T::decode(value)
}
.map_err(|source| Error::ColumnDecode {
index: format!("{:?}", index),
index: format!("{index:?}"),
source,
})
}

View file

@ -80,8 +80,7 @@ impl<DB: Database> Describe<DB> {
AnyTypeInfo::try_from(type_info).map_err(|_| {
crate::Error::AnyDriverError(
format!(
"Any driver does not support type {} of parameter {}",
type_info, i
"Any driver does not support type {type_info} of parameter {i}"
)
.into(),
)

View file

@ -253,10 +253,7 @@ impl dyn DatabaseError {
/// specific error type. In other cases, use `try_downcast_ref`.
pub fn downcast_ref<E: DatabaseError>(&self) -> &E {
self.try_downcast_ref().unwrap_or_else(|| {
panic!(
"downcast to wrong DatabaseError type; original error: {}",
self
)
panic!("downcast to wrong DatabaseError type; original error: {self}")
})
}
@ -268,12 +265,8 @@ impl dyn DatabaseError {
/// `Error::downcast` which returns `Option<E>`. In normal usage, you should know the
/// specific error type. In other cases, use `try_downcast`.
pub fn downcast<E: DatabaseError>(self: Box<Self>) -> Box<E> {
self.try_downcast().unwrap_or_else(|e| {
panic!(
"downcast to wrong DatabaseError type; original error: {}",
e
)
})
self.try_downcast()
.unwrap_or_else(|e| panic!("downcast to wrong DatabaseError type; original error: {e}"))
}
/// Downcast a reference to this generic database error to a specific

View file

@ -202,7 +202,7 @@ pub trait Execute<'q, DB: Database>: Send + Sized {
}
// NOTE: `Execute` is explicitly not implemented for String and &String to make it slightly more
// involved to write `conn.execute(format!("SELECT {}", val))`
// involved to write `conn.execute(format!("SELECT {val}"))`
impl<'q, DB: Database> Execute<'q, DB> for &'q str {
#[inline]
fn sql(&self) -> &'q str {

View file

@ -116,7 +116,7 @@ where
pub fn push(&mut self, sql: impl Display) -> &mut Self {
self.sanity_check();
write!(self.query, "{}", sql).expect("error formatting `sql`");
write!(self.query, "{sql}").expect("error formatting `sql`");
self
}
@ -258,9 +258,9 @@ where
/// // This would normally produce values forever!
/// let users = (0..).map(|i| User {
/// id: i,
/// username: format!("test_user_{}", i),
/// email: format!("test-user-{}@example.com", i),
/// password: format!("Test!User@Password#{}", i),
/// username: format!("test_user_{i}"),
/// email: format!("test-user-{i}@example.com"),
/// password: format!("Test!User@Password#{i}"),
/// });
///
/// let mut query_builder: QueryBuilder<MySql> = QueryBuilder::new(
@ -365,9 +365,9 @@ where
/// // This would normally produce values forever!
/// let users = (0..).map(|i| User {
/// id: i,
/// username: format!("test_user_{}", i),
/// email: format!("test-user-{}@example.com", i),
/// password: format!("Test!User@Password#{}", i),
/// username: format!("test_user_{i}"),
/// email: format!("test-user-{i}@example.com"),
/// password: format!("Test!User@Password#{i}"),
/// });
///
/// let mut query_builder: QueryBuilder<MySql> = QueryBuilder::new(

View file

@ -121,14 +121,14 @@ pub trait Row: Unpin + Send + Sync + 'static {
if !ty.is_null() && !T::compatible(&ty) {
return Err(Error::ColumnDecode {
index: format!("{:?}", index),
index: format!("{index:?}"),
source: mismatched_types::<Self::Database, T>(&ty),
});
}
}
T::decode(value).map_err(|source| Error::ColumnDecode {
index: format!("{:?}", index),
index: format!("{index:?}"),
source,
})
}
@ -158,7 +158,7 @@ pub trait Row: Unpin + Send + Sync + 'static {
let value = self.try_get_raw(&index)?;
T::decode(value).map_err(|source| Error::ColumnDecode {
index: format!("{:?}", index),
index: format!("{index:?}"),
source,
})
}

View file

@ -128,7 +128,7 @@ where
continue;
}
query.push(format_args!("INSERT INTO {} (", table));
query.push(format_args!("INSERT INTO {table} ("));
let mut separated = query.separated(", ");

View file

@ -191,7 +191,7 @@ where
.is_err();
if close_timed_out {
eprintln!("test {} held onto Pool after exiting", test_path);
eprintln!("test {test_path} held onto Pool after exiting");
}
res

View file

@ -244,7 +244,7 @@ pub fn begin_ansi_transaction_sql(depth: usize) -> Cow<'static, str> {
if depth == 0 {
Cow::Borrowed("BEGIN")
} else {
Cow::Owned(format!("SAVEPOINT _sqlx_savepoint_{}", depth))
Cow::Owned(format!("SAVEPOINT _sqlx_savepoint_{depth}"))
}
}

View file

@ -70,7 +70,7 @@ pub fn quote_args<DB: DatabaseExt>(
}
})?
.parse::<TokenStream>()
.map_err(|_| format!("Rust type mapping for {} not parsable", param_ty))?
.map_err(|_| format!("Rust type mapping for {param_ty} not parsable"))?
}
};

View file

@ -15,7 +15,7 @@ use sqlx_core::describe::Describe;
use crate::database::DatabaseExt;
#[derive(serde::Serialize)]
#[serde(bound(serialize = "Describe<DB>: serde::Serialize",))]
#[serde(bound(serialize = "Describe<DB>: serde::Serialize"))]
#[derive(Debug)]
pub struct QueryData<DB: Database> {
db_name: SerializeDbName<DB>,
@ -161,20 +161,20 @@ where
// Use a temp directory inside the workspace to avoid potential issues
// with persisting the file across filesystems.
let mut tmp_file = tempfile::NamedTempFile::new_in(tmp_dir)
.map_err(|err| format!("failed to create query file: {:?}", err))?;
.map_err(|err| format!("failed to create query file: {err:?}"))?;
serde_json::to_writer_pretty(tmp_file.as_file_mut(), self)
.map_err(|err| format!("failed to serialize query data to file: {:?}", err))?;
.map_err(|err| format!("failed to serialize query data to file: {err:?}"))?;
// Ensure there is a newline at the end of the JSON file to avoid accidental modification by IDE
// and make github diff tool happier
tmp_file
.as_file_mut()
.write_all(b"\n")
.map_err(|err| format!("failed to append a newline to file: {:?}", err))?;
.map_err(|err| format!("failed to append a newline to file: {err:?}"))?;
tmp_file
.persist(dir.as_ref().join(format!("query-{}.json", self.hash)))
.map_err(|err| format!("failed to move query file: {:?}", err))?;
.map_err(|err| format!("failed to move query file: {err:?}"))?;
Ok(())
}

View file

@ -83,7 +83,7 @@ impl Parse for QueryMacroInput {
let lit_bool = input.parse::<LitBool>()?;
checked = lit_bool.value;
} else {
let message = format!("unexpected input key: {}", key);
let message = format!("unexpected input key: {key}");
return Err(syn::Error::new_spanned(key, message));
}

View file

@ -121,7 +121,7 @@ static METADATA: Lazy<Metadata> = Lazy::new(|| {
let env_path = if env_path.exists() {
let res = dotenvy::from_path(&env_path);
if let Err(e) = res {
panic!("failed to load environment from {:?}, {}", env_path, e);
panic!("failed to load environment from {env_path:?}, {e}");
}
Some(env_path)
@ -373,16 +373,15 @@ where
Err(e) => {
if e.kind() != io::ErrorKind::NotFound {
// Can't obtain information about .sqlx
return Err(format!("{}: {}", e, dir).into());
return Err(format!("{e}: {dir}").into());
}
// .sqlx doesn't exist.
return Err(format!("sqlx offline path does not exist: {}", dir).into());
return Err(format!("sqlx offline path does not exist: {dir}").into());
}
Ok(meta) => {
if !meta.is_dir() {
return Err(format!(
"sqlx offline path exists, but is not a directory: {}",
dir
"sqlx offline path exists, but is not a directory: {dir}"
)
.into());
}

View file

@ -327,5 +327,5 @@ fn parse_ident(name: &str) -> crate::Result<Ident> {
}
}
Err(format!("{:?} is not a valid Rust identifier", name).into())
Err(format!("{name:?} is not a valid Rust identifier").into())
}

View file

@ -155,7 +155,7 @@ impl<'a> TryFrom<&'a MySqlTypeInfo> for AnyTypeInfo {
}
_ => {
return Err(sqlx_core::Error::AnyDriverError(
format!("Any driver does not support MySql type {:?}", type_info).into(),
format!("Any driver does not support MySql type {type_info:?}").into(),
))
}
},

View file

@ -190,7 +190,7 @@ impl FromStr for CharSet {
_ => {
return Err(Error::Configuration(
format!("unsupported MySQL charset: {}", char_set).into(),
format!("unsupported MySQL charset: {char_set}").into(),
));
}
})
@ -892,7 +892,7 @@ impl FromStr for Collation {
_ => {
return Err(Error::Configuration(
format!("unsupported MySQL collation: {}", collation).into(),
format!("unsupported MySQL collation: {collation}").into(),
));
}
})

View file

@ -37,7 +37,7 @@ impl MigrateDatabase for MySql {
let mut conn = options.connect().await?;
let _ = conn
.execute(&*format!("CREATE DATABASE `{}`", database))
.execute(&*format!("CREATE DATABASE `{database}`"))
.await?;
Ok(())
@ -66,7 +66,7 @@ impl MigrateDatabase for MySql {
let mut conn = options.connect().await?;
let _ = conn
.execute(&*format!("DROP DATABASE IF EXISTS `{}`", database,))
.execute(&*format!("DROP DATABASE IF EXISTS `{database}`"))
.await?;
Ok(())

View file

@ -49,7 +49,7 @@ impl FromStr for MySqlSslMode {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `ssl_mode`", s).into(),
format!("unknown value {s:?} for `ssl_mode`").into(),
));
}
})

View file

@ -43,7 +43,7 @@ impl TestSupport for MySql {
let db_id = db_id(db_name);
conn.execute(&format!("drop database if exists {};", db_name)[..])
conn.execute(&format!("drop database if exists {db_name};")[..])
.await?;
query("delete from _sqlx_test_databases where db_id = ?")
@ -152,10 +152,10 @@ async fn test_context(args: &TestArgs) -> Result<TestContext<MySql>, Error> {
let new_db_name = db_name(new_db_id);
conn.execute(&format!("create database {}", new_db_name)[..])
conn.execute(&format!("create database {new_db_name}")[..])
.await?;
eprintln!("created database {}", new_db_name);
eprintln!("created database {new_db_name}");
Ok(TestContext {
pool_opts: PoolOptions::new()
@ -197,14 +197,14 @@ async fn do_cleanup(conn: &mut MySqlConnection, created_before: Duration) -> Res
let db_name = db_name(db_id);
writeln!(command, "drop database if exists {}", db_name).ok();
writeln!(command, "drop database if exists {db_name}").ok();
match conn.execute(&*command).await {
Ok(_deleted) => {
deleted_db_ids.push(db_id);
}
// Assume a database error just means the DB is still in use.
Err(Error::Database(dbe)) => {
eprintln!("could not clean test database {:?}: {}", db_id, dbe)
eprintln!("could not clean test database {db_id:?}: {dbe}")
}
// Bubble up other errors
Err(e) => return Err(e),
@ -227,13 +227,13 @@ async fn do_cleanup(conn: &mut MySqlConnection, created_before: Duration) -> Res
}
fn db_name(id: u64) -> String {
format!("_sqlx_test_database_{}", id)
format!("_sqlx_test_database_{id}")
}
fn db_id(name: &str) -> u64 {
name.trim_start_matches("_sqlx_test_database_")
.parse()
.unwrap_or_else(|_1| panic!("failed to parse ID from database name {:?}", name))
.unwrap_or_else(|_1| panic!("failed to parse ID from database name {name:?}"))
}
#[test]

View file

@ -236,7 +236,7 @@ impl<'r> Decode<'r, MySql> for NaiveDateTime {
fn encode_date(date: &NaiveDate, buf: &mut Vec<u8>) {
// MySQL supports years from 1000 - 9999
let year = u16::try_from(date.year())
.unwrap_or_else(|_| panic!("NaiveDateTime out of range for Mysql: {}", date));
.unwrap_or_else(|_| panic!("NaiveDateTime out of range for Mysql: {date}"));
buf.extend_from_slice(&year.to_le_bytes());
buf.push(date.month() as u8);

View file

@ -223,7 +223,7 @@ impl<'r> Decode<'r, MySql> for PrimitiveDateTime {
fn encode_date(date: &Date, buf: &mut Vec<u8>) {
// MySQL supports years from 1000 - 9999
let year = u16::try_from(date.year())
.unwrap_or_else(|_| panic!("Date out of range for Mysql: {}", date));
.unwrap_or_else(|_| panic!("Date out of range for Mysql: {date}"));
buf.extend_from_slice(&year.to_le_bytes());
buf.push(date.month().into());
@ -268,5 +268,5 @@ fn decode_time(len: u8, mut buf: &[u8]) -> Result<Time, BoxDynError> {
};
Time::from_hms_micro(hour, minute, seconds, micros as u32)
.map_err(|e| format!("Time out of range for MySQL: {}", e).into())
.map_err(|e| format!("Time out of range for MySQL: {e}").into())
}

View file

@ -302,9 +302,9 @@ impl PgAdvisoryLock {
fn get_release_query(&self) -> &str {
self.release_query.get_or_init(|| match &self.key {
PgAdvisoryLockKey::BigInt(key) => format!("SELECT pg_advisory_unlock({})", key),
PgAdvisoryLockKey::BigInt(key) => format!("SELECT pg_advisory_unlock({key})"),
PgAdvisoryLockKey::IntPair(key1, key2) => {
format!("SELECT pg_advisory_unlock({}, {})", key1, key2)
format!("SELECT pg_advisory_unlock({key1}, {key2})")
}
})
}

View file

@ -143,8 +143,7 @@ impl AnyConnectionBackend for PgConnection {
AnyTypeInfo::try_from(type_info).map_err(|_| {
sqlx_core::Error::AnyDriverError(
format!(
"Any driver does not support type {} of parameter {}",
type_info, i
"Any driver does not support type {type_info} of parameter {i}"
)
.into(),
)
@ -181,11 +180,7 @@ impl<'a> TryFrom<&'a PgTypeInfo> for AnyTypeInfo {
PgType::Text => AnyTypeInfoKind::Text,
_ => {
return Err(sqlx_core::Error::AnyDriverError(
format!(
"Any driver does not support the Postgres type {:?}",
pg_type
)
.into(),
format!("Any driver does not support the Postgres type {pg_type:?}").into(),
))
}
},

View file

@ -50,7 +50,7 @@ pub(crate) async fn authenticate(
}
// channel-binding = "c=" base64
let mut channel_binding = format!("{}=", CHANNEL_ATTR);
let mut channel_binding = format!("{CHANNEL_ATTR}=");
BASE64_STANDARD.encode_string(GS2_HEADER, &mut channel_binding);
// "n=" saslname ;; Usernames are prepared using SASLprep.
@ -65,14 +65,9 @@ pub(crate) async fn authenticate(
let nonce = gen_nonce();
// client-first-message-bare = [reserved-mext ","] username "," nonce ["," extensions]
let client_first_message_bare =
format!("{username},{nonce}", username = username, nonce = nonce);
let client_first_message_bare = format!("{username},{nonce}");
let client_first_message = format!(
"{gs2_header}{client_first_message_bare}",
gs2_header = GS2_HEADER,
client_first_message_bare = client_first_message_bare
);
let client_first_message = format!("{GS2_HEADER}{client_first_message_bare}");
stream
.send(SaslInitialResponse {
@ -147,11 +142,7 @@ pub(crate) async fn authenticate(
mac.update(&auth_message.as_bytes());
// client-final-message = client-final-message-without-proof "," proof
let mut client_final_message = format!(
"{client_final_message_wo_proof},{client_proof_attr}=",
client_final_message_wo_proof = client_final_message_wo_proof,
client_proof_attr = CLIENT_PROOF_ATTR,
);
let mut client_final_message = format!("{client_final_message_wo_proof},{CLIENT_PROOF_ATTR}=");
BASE64_STANDARD.encode_string(client_proof, &mut client_final_message);
stream.send(SaslResponse(&client_final_message)).await?;
@ -194,7 +185,7 @@ fn gen_nonce() -> String {
.collect();
rng.gen_range(32..128);
format!("{}={}", NONCE_ATTR, nonce)
format!("{NONCE_ATTR}={nonce}")
}
// Hi(str, salt, i):

View file

@ -476,7 +476,7 @@ impl PgConnectOptions {
options_str.push(' ');
}
write!(options_str, "-c {}={}", k, v).expect("failed to write an option to the string");
write!(options_str, "-c {k}={v}").expect("failed to write an option to the string");
}
self
}
@ -500,7 +500,7 @@ impl PgConnectOptions {
fn default_host(port: u16) -> String {
// try to check for the existence of a unix socket and uses that
let socket = format!(".s.PGSQL.{}", port);
let socket = format!(".s.PGSQL.{port}");
let candidates = [
"/var/run/postgresql", // Debian
"/private/tmp", // OSX (homebrew)

View file

@ -55,7 +55,7 @@ fn load_password_from_file(
if mode & 0o77 != 0 {
tracing::warn!(
path = %path.to_string_lossy(),
permissions = format!("{:o}", mode),
permissions = format!("{mode:o}"),
"Ignoring path. Permissions are not strict enough",
);
return None;

View file

@ -48,7 +48,7 @@ impl FromStr for PgSslMode {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `ssl_mode`", s).into(),
format!("unknown value {s:?} for `ssl_mode`").into(),
));
}
})

View file

@ -40,7 +40,7 @@ impl TestSupport for Postgres {
.acquire()
.await?;
conn.execute(&format!("drop database if exists {0:?};", db_name)[..])
conn.execute(&format!("drop database if exists {db_name:?};")[..])
.await?;
query("delete from _sqlx_test.databases where db_name = $1")
@ -161,7 +161,7 @@ async fn test_context(args: &TestArgs) -> Result<TestContext<Postgres>, Error> {
.fetch_one(&mut *conn)
.await?;
conn.execute(&format!("create database {:?}", new_db_name)[..])
conn.execute(&format!("create database {new_db_name:?}")[..])
.await?;
Ok(TestContext {
@ -204,14 +204,14 @@ async fn do_cleanup(conn: &mut PgConnection, created_before: Duration) -> Result
for db_name in delete_db_names {
command.clear();
writeln!(command, "drop database if exists {:?};", db_name).ok();
writeln!(command, "drop database if exists {db_name:?};").ok();
match conn.execute(&*command).await {
Ok(_deleted) => {
deleted_db_names.push(db_name);
}
// Assume a database error just means the DB is still in use.
Err(Error::Database(dbe)) => {
eprintln!("could not clean test database {:?}: {}", db_name, dbe)
eprintln!("could not clean test database {db_name:?}: {dbe}")
}
// Bubble up other errors
Err(e) => return Err(e),

View file

@ -768,7 +768,7 @@ impl PgType {
unreachable!("(bug) use of unresolved type declaration [oid={}]", oid.0);
}
PgType::DeclareWithName(name) => {
unreachable!("(bug) use of unresolved type declaration [name={}]", name);
unreachable!("(bug) use of unresolved type declaration [name={name}]");
}
}
}
@ -887,7 +887,7 @@ impl PgType {
unreachable!("(bug) use of unresolved type declaration [oid={}]", oid.0);
}
PgType::DeclareWithName(name) => {
unreachable!("(bug) use of unresolved type declaration [name={}]", name);
unreachable!("(bug) use of unresolved type declaration [name={name}]");
}
}
}

View file

@ -196,7 +196,7 @@ where
}
if ndim != 1 {
return Err(format!("encountered an array of {} dimensions; only one-dimensional arrays are supported", ndim).into());
return Err(format!("encountered an array of {ndim} dimensions; only one-dimensional arrays are supported").into());
}
// appears to have been used in the past to communicate potential NULLS
@ -222,7 +222,7 @@ where
let lower = buf.get_i32();
if lower != 1 {
return Err(format!("encountered an array with a lower bound of {} in the first dimension; only arrays starting at one are supported", lower).into());
return Err(format!("encountered an array with a lower bound of {lower} in the first dimension; only arrays starting at one are supported").into());
}
let mut elements = Vec::with_capacity(len as usize);

View file

@ -34,7 +34,7 @@ impl Decode<'_, Postgres> for bool {
"f" => false,
s => {
return Err(format!("unexpected value {:?} for boolean", s).into());
return Err(format!("unexpected value {s:?} for boolean").into());
}
},
})

View file

@ -38,7 +38,7 @@ impl Encode<'_, Postgres> for NaiveDateTime {
// TIMESTAMP is encoded as the microseconds since the epoch
let us = (*self - postgres_epoch_datetime())
.num_microseconds()
.unwrap_or_else(|| panic!("NaiveDateTime out of range for Postgres: {:?}", self));
.unwrap_or_else(|| panic!("NaiveDateTime out of range for Postgres: {self:?}"));
Encode::<Postgres>::encode(&us, buf)
}

View file

@ -112,7 +112,7 @@ impl Decode<'_, Postgres> for IpNetwork {
}
_ => {
return Err(format!("unknown ip family {}", family).into());
return Err(format!("unknown ip family {family}").into());
}
}
}

View file

@ -114,9 +114,9 @@ impl Display for PgLQuery {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut iter = self.levels.iter();
if let Some(label) = iter.next() {
write!(f, "{}", label)?;
write!(f, "{label}")?;
for label in iter {
write!(f, ".{}", label)?;
write!(f, ".{label}")?;
}
}
Ok(())
@ -141,7 +141,7 @@ impl Type<Postgres> for PgLQuery {
impl Encode<'_, Postgres> for PgLQuery {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
buf.extend(1i8.to_le_bytes());
write!(buf, "{}", self)
write!(buf, "{self}")
.expect("Display implementation panicked while writing to PgArgumentBuffer");
IsNull::No
@ -288,7 +288,7 @@ fn write_variants(f: &mut Formatter<'_>, variants: &[PgLQueryVariant], not: bool
if let Some(variant) = iter.next() {
write!(f, "{}{}", if not { "!" } else { "" }, variant)?;
for variant in iter {
write!(f, ".{}", variant)?;
write!(f, ".{variant}")?;
}
}
Ok(())
@ -299,13 +299,13 @@ impl Display for PgLQueryLevel {
match self {
PgLQueryLevel::Star(Some(at_least), Some(at_most)) => {
if at_least == at_most {
write!(f, "*{{{}}}", at_least)
write!(f, "*{{{at_least}}}")
} else {
write!(f, "*{{{},{}}}", at_least, at_most)
write!(f, "*{{{at_least},{at_most}}}")
}
}
PgLQueryLevel::Star(Some(at_least), _) => write!(f, "*{{{},}}", at_least),
PgLQueryLevel::Star(_, Some(at_most)) => write!(f, "*{{,{}}}", at_most),
PgLQueryLevel::Star(Some(at_least), _) => write!(f, "*{{{at_least},}}"),
PgLQueryLevel::Star(_, Some(at_most)) => write!(f, "*{{,{at_most}}}"),
PgLQueryLevel::Star(_, _) => write!(f, "*"),
PgLQueryLevel::NonStar(variants) => write_variants(f, &variants, false),
PgLQueryLevel::NotNonStar(variants) => write_variants(f, &variants, true),

View file

@ -150,9 +150,9 @@ impl Display for PgLTree {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut iter = self.labels.iter();
if let Some(label) = iter.next() {
write!(f, "{}", label)?;
write!(f, "{label}")?;
for label in iter {
write!(f, ".{}", label)?;
write!(f, ".{label}")?;
}
}
Ok(())
@ -183,7 +183,7 @@ impl PgHasArrayType for PgLTree {
impl Encode<'_, Postgres> for PgLTree {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
buf.extend(1i8.to_le_bytes());
write!(buf, "{}", self)
write!(buf, "{self}")
.expect("Display implementation panicked while writing to PgArgumentBuffer");
IsNull::No

View file

@ -69,7 +69,7 @@ impl PgNumericSign {
SIGN_NAN => unreachable!("sign value for NaN passed to PgNumericSign"),
_ => Err(format!("invalid value for PgNumericSign: {:#04X}", val).into()),
_ => Err(format!("invalid value for PgNumericSign: {val:#04X}").into()),
}
}
}

View file

@ -480,8 +480,7 @@ fn parse_bound<T>(ch: char, value: Option<T>) -> Result<Bound<T>, BoxDynError> {
_ => {
return Err(format!(
"expected `(`, ')', '[', or `]` but found `{}` for range literal",
ch
"expected `(`, ')', '[', or `]` but found `{ch}` for range literal"
)
.into());
}
@ -498,14 +497,14 @@ where
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match &self.start {
Bound::Unbounded => f.write_str("(,")?,
Bound::Excluded(v) => write!(f, "({},", v)?,
Bound::Included(v) => write!(f, "[{},", v)?,
Bound::Excluded(v) => write!(f, "({v},")?,
Bound::Included(v) => write!(f, "[{v},")?,
}
match &self.end {
Bound::Unbounded => f.write_str(")")?,
Bound::Excluded(v) => write!(f, "{})", v)?,
Bound::Included(v) => write!(f, "{}]", v)?,
Bound::Excluded(v) => write!(f, "{v})")?,
Bound::Included(v) => write!(f, "{v}]")?,
}
Ok(())

View file

@ -62,7 +62,7 @@ impl<'r> Decode<'r, Postgres> for PrimitiveDateTime {
let s = if s.contains('.') {
Cow::Borrowed(s)
} else {
Cow::Owned(format!("{}.0", s))
Cow::Owned(format!("{s}.0"))
};
// Contains a time-zone specifier

View file

@ -148,11 +148,8 @@ impl<'a> TryFrom<&'a SqliteTypeInfo> for AnyTypeInfo {
DataType::Text => AnyTypeInfoKind::Text,
_ => {
return Err(sqlx_core::Error::AnyDriverError(
format!(
"Any driver does not support the SQLite type {:?}",
sqlite_type
)
.into(),
format!("Any driver does not support the SQLite type {sqlite_type:?}")
.into(),
))
}
},
@ -214,7 +211,7 @@ fn map_arguments(args: AnyArguments<'_>) -> SqliteArguments<'_> {
AnyValueKind::Text(t) => SqliteArgumentValue::Text(t),
AnyValueKind::Blob(b) => SqliteArgumentValue::Blob(b),
// AnyValueKind is `#[non_exhaustive]` but we should have covered everything
_ => unreachable!("BUG: missing mapping for {:?}", val),
_ => unreachable!("BUG: missing mapping for {val:?}"),
})
.collect(),
}

View file

@ -96,7 +96,7 @@ impl EstablishParams {
}
if let Some(vfs) = &options.vfs {
query_params.push(format!("vfs={}", vfs))
query_params.push(format!("vfs={vfs}"))
}
if !query_params.is_empty() {

View file

@ -430,7 +430,7 @@ pub(super) fn explain(
) -> Result<(Vec<SqliteTypeInfo>, Vec<Option<bool>>), Error> {
let root_block_cols = root_block_columns(conn)?;
let program: Vec<(i64, String, i64, i64, i64, Vec<u8>)> =
execute::iter(conn, &format!("EXPLAIN {}", query), None, false)?
execute::iter(conn, &format!("EXPLAIN {query}"), None, false)?
.filter_map(|res| res.map(|either| either.right()).transpose())
.map(|row| FromRow::from_row(&row?))
.collect::<Result<Vec<_>, Error>>()?;

View file

@ -133,7 +133,7 @@ impl Connection for SqliteConnection {
if let OptimizeOnClose::Enabled { analysis_limit } = self.optimize_on_close {
let mut pragma_string = String::new();
if let Some(limit) = analysis_limit {
write!(pragma_string, "PRAGMA analysis_limit = {}; ", limit).ok();
write!(pragma_string, "PRAGMA analysis_limit = {limit}; ").ok();
}
pragma_string.push_str("PRAGMA optimize;");
self.execute(&*pragma_string).await?;
@ -258,7 +258,7 @@ impl LockedSqliteHandle<'_> {
/// The progress handler callback must not do anything that will modify the database connection that invoked
/// the progress handler. Note that sqlite3_prepare_v2() and sqlite3_step() both modify their database connections
/// in this context.
pub fn set_progress_handler<F>(&mut self, num_ops: i32, mut callback: F)
pub fn set_progress_handler<F>(&mut self, num_ops: i32, callback: F)
where
F: FnMut() -> bool + Send + 'static,
{

View file

@ -35,7 +35,7 @@ impl FromStr for SqliteAutoVacuum {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `auto_vacuum`", s).into(),
format!("unknown value {s:?} for `auto_vacuum`").into(),
));
}
})

View file

@ -64,7 +64,7 @@ impl SqliteConnectOptions {
for (key, opt_value) in &self.pragmas {
if let Some(value) = opt_value {
write!(string, "PRAGMA {} = {}; ", key, value).ok();
write!(string, "PRAGMA {key} = {value}; ").ok();
}
}

View file

@ -47,7 +47,7 @@ impl FromStr for SqliteJournalMode {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `journal_mode`", s).into(),
format!("unknown value {s:?} for `journal_mode`").into(),
));
}
})

View file

@ -35,7 +35,7 @@ impl FromStr for SqliteLockingMode {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `locking_mode`", s).into(),
format!("unknown value {s:?} for `locking_mode`").into(),
));
}
})

View file

@ -196,7 +196,7 @@ impl SqliteConnectOptions {
extensions: Default::default(),
collations: Default::default(),
serialized: false,
thread_name: Arc::new(DebugFn(|id| format!("sqlx-sqlite-worker-{}", id))),
thread_name: Arc::new(DebugFn(|id| format!("sqlx-sqlite-worker-{id}"))),
command_channel_size: 50,
row_channel_size: 50,
optimize_on_close: OptimizeOnClose::Disabled,

View file

@ -18,7 +18,7 @@ impl SqliteConnectOptions {
options.in_memory = true;
options.shared_cache = true;
let seqno = IN_MEMORY_DB_SEQ.fetch_add(1, Ordering::Relaxed);
options.filename = Cow::Owned(PathBuf::from(format!("file:sqlx-in-memory-{}", seqno)));
options.filename = Cow::Owned(PathBuf::from(format!("file:sqlx-in-memory-{seqno}")));
} else {
// % decode to allow for `?` or `#` in the filename
options.filename = Cow::Owned(
@ -58,7 +58,7 @@ impl SqliteConnectOptions {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `mode`", value).into(),
format!("unknown value {value:?} for `mode`").into(),
));
}
}
@ -78,7 +78,7 @@ impl SqliteConnectOptions {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `cache`", value).into(),
format!("unknown value {value:?} for `cache`").into(),
));
}
},
@ -92,7 +92,7 @@ impl SqliteConnectOptions {
}
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `immutable`", value).into(),
format!("unknown value {value:?} for `immutable`").into(),
));
}
},
@ -101,11 +101,8 @@ impl SqliteConnectOptions {
_ => {
return Err(Error::Configuration(
format!(
"unknown query parameter `{}` while parsing connection URL",
key
)
.into(),
format!("unknown query parameter `{key}` while parsing connection URL")
.into(),
));
}
}

View file

@ -41,7 +41,7 @@ impl FromStr for SqliteSynchronous {
_ => {
return Err(Error::Configuration(
format!("unknown value {:?} for `synchronous`", s).into(),
format!("unknown value {s:?} for `synchronous`").into(),
));
}
})

View file

@ -157,7 +157,7 @@ unsafe fn get_text_from_arg<'a>(
match std::str::from_utf8(slice) {
Ok(result) => Some(result),
Err(e) => {
log::error!("Incoming text is not valid UTF8: {e:?}",);
log::error!("Incoming text is not valid UTF8: {e:?}");
ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_CONSTRAINT_FUNCTION);
None
}
@ -190,7 +190,7 @@ mod tests {
.unwrap();
for i in 0..10 {
sqlx::query("INSERT INTO test VALUES (?)")
.bind(format!("value {}", i))
.bind(format!("value {i}"))
.execute(&mut conn)
.await
.unwrap();

View file

@ -73,7 +73,7 @@ impl DataType {
SQLITE_TEXT => DataType::Text,
// https://sqlite.org/c3ref/c_blob.html
_ => panic!("unknown data type code {}", code),
_ => panic!("unknown data type code {code}"),
}
}
}
@ -104,7 +104,7 @@ impl FromStr for DataType {
_ if s.contains("real") || s.contains("floa") || s.contains("doub") => DataType::Float,
_ => {
return Err(format!("unknown type: `{}`", s).into());
return Err(format!("unknown type: `{s}`").into());
}
})
}

View file

@ -201,6 +201,6 @@ impl<'r> Decode<'r, Sqlite> for NaiveTime {
}
}
Err(format!("invalid time: {}", value).into())
Err(format!("invalid time: {value}").into())
}
}

View file

@ -115,7 +115,7 @@ impl<'r> Decode<'r, Sqlite> for Time {
}
}
Err(format!("invalid time: {}", value).into())
Err(format!("invalid time: {value}").into())
}
}

View file

@ -18,7 +18,7 @@
/// .await?;
///
/// // anonymous struct has `#[derive(Debug)]` for convenience
/// println!("{:?}", account);
/// println!("{account:?}");
/// println!("{}: {}", account.id, account.name);
///
/// # Ok(())
@ -86,7 +86,7 @@
/// .fetch_one(&mut conn)
/// .await?;
///
/// println!("{:?}", account);
/// println!("{account:?}");
/// println!("{}: {}", account.id, account.name);
/// # Ok(())
/// # }
@ -369,7 +369,7 @@ macro_rules! query_unchecked (
/// .fetch_one(&mut conn)
/// .await?;
///
/// println!("{:?}", account);
/// println!("{account:?}");
/// println!("{}: {}", account.id, account.name);
///
/// # Ok(())
@ -452,7 +452,7 @@ macro_rules! query_file_unchecked (
/// .fetch_one(&mut conn)
/// .await?;
///
/// println!("{:?}", account);
/// println!("{account:?}");
/// println!("{}: {}", account.id, account.name);
///
/// # Ok(())
@ -589,7 +589,7 @@ macro_rules! query_as (
/// .fetch_one(&mut conn)
/// .await?;
///
/// println!("{:?}", account);
/// println!("{account:?}");
/// println!("{}: {}", account.id, account.name);
///
/// # Ok(())

View file

@ -106,7 +106,7 @@ async fn it_can_fail_and_recover() -> anyhow::Result<()> {
// now try and use the connection
let val: i32 = conn
.fetch_one(&*format!("SELECT {}", i))
.fetch_one(&*format!("SELECT {i}"))
.await?
.get_unchecked(0);
@ -132,7 +132,7 @@ async fn it_can_fail_and_recover_with_pool() -> anyhow::Result<()> {
// now try and use the connection
let val: i32 = pool
.fetch_one(&*format!("SELECT {}", i))
.fetch_one(&*format!("SELECT {i}"))
.await?
.get_unchecked(0);

View file

@ -27,7 +27,7 @@ async fn macro_select_from_cte_bind() -> anyhow::Result<()> {
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);
println!("{account:?}");
println!("{}: {}", account.id, account.name);
Ok(())
@ -53,7 +53,7 @@ async fn test_query_as_raw() -> anyhow::Result<()> {
assert_eq!(account.name, None);
assert_eq!(account.r#type, 1);
println!("{:?}", account);
println!("{account:?}");
Ok(())
}

View file

@ -347,7 +347,7 @@ async fn test_issue_622() -> anyhow::Result<()> {
.connect(&std::env::var("DATABASE_URL").unwrap())
.await?;
println!("pool state: {:?}", pool);
println!("pool state: {pool:?}");
let mut handles = vec![];
@ -375,7 +375,7 @@ async fn test_issue_622() -> anyhow::Result<()> {
println!("{} acquire took {:?}", i, start.elapsed());
drop(conn);
}
Err(e) => panic!("{} acquire returned error: {} pool state: {:?}", i, e, pool),
Err(e) => panic!("{i} acquire returned error: {e} pool state: {pool:?}"),
}
}

View file

@ -247,7 +247,7 @@ SELECT id, mood FROM people WHERE id = $1
conn.close().await?;
let mut conn = new::<Postgres>().await?;
let stmt = format!("SELECT id, mood FROM people WHERE id = {}", people_id);
let stmt = format!("SELECT id, mood FROM people WHERE id = {people_id}");
dbg!(&stmt);
let mut cursor = conn.fetch(&*stmt);
@ -484,7 +484,7 @@ async fn test_from_row_with_keyword() -> anyhow::Result<()> {
)
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);
println!("{account:?}");
assert_eq!(1, account.r#type);
assert_eq!("foo", account.r#static);
@ -522,7 +522,7 @@ async fn test_from_row_with_rename() -> anyhow::Result<()> {
)
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);
println!("{account:?}");
assert_eq!(1, account.own_type);
assert_eq!("foo", account.my_static);
@ -551,7 +551,7 @@ async fn test_from_row_with_rename_all() -> anyhow::Result<()> {
)
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);
println!("{account:?}");
assert_eq!(1, account.user_id);
assert_eq!("foo", account.user_name);
@ -613,7 +613,7 @@ async fn test_default() -> anyhow::Result<()> {
let has_default: HasDefault = sqlx::query_as(r#"SELECT 1 AS not_default"#)
.fetch_one(&mut conn)
.await?;
println!("{:?}", has_default);
println!("{has_default:?}");
assert_eq!(has_default.not_default, 1);
assert_eq!(has_default.default, None);
@ -652,7 +652,7 @@ async fn test_flatten() -> anyhow::Result<()> {
)
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);
println!("{account:?}");
assert_eq!(1, account.id);
assert_eq!("foo", account.info.name);
@ -682,7 +682,7 @@ async fn test_skip() -> anyhow::Result<()> {
let account: AccountKeyword = sqlx::query_as(r#"SELECT * from (VALUES (1)) accounts("id")"#)
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);
println!("{account:?}");
assert_eq!(1, account.id);
assert_eq!(None, account.default.default);

View file

@ -114,7 +114,7 @@ async fn test_query_file() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
// keep trailing comma as a test
let account = sqlx::query_file!("tests/postgres/test-query.sql",)
let account = sqlx::query_file!("tests/postgres/test-query.sql")
.fetch_one(&mut conn)
.await?;
@ -146,7 +146,7 @@ async fn test_query_as() -> anyhow::Result<()> {
assert_eq!(1, account.id);
assert_eq!(None, account.name);
println!("{:?}", account);
println!("{account:?}");
Ok(())
}
@ -171,7 +171,7 @@ async fn test_query_as_raw() -> anyhow::Result<()> {
assert_eq!(None, account.name);
assert_eq!(1, account.r#type);
println!("{:?}", account);
println!("{account:?}");
Ok(())
}
@ -180,11 +180,11 @@ async fn test_query_as_raw() -> anyhow::Result<()> {
async fn test_query_file_as() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let account = sqlx::query_file_as!(Account, "tests/postgres/test-query.sql",)
let account = sqlx::query_file_as!(Account, "tests/postgres/test-query.sql")
.fetch_one(&mut conn)
.await?;
println!("{:?}", account);
println!("{account:?}");
Ok(())
}
@ -338,7 +338,7 @@ async fn test_nullable_err() -> anyhow::Result<()> {
}
}
panic!("expected `UnexpectedNullError`, got {}", err)
panic!("expected `UnexpectedNullError`, got {err}")
}
#[sqlx_macros::test]

View file

@ -305,10 +305,7 @@ async fn it_can_fail_and_recover() -> anyhow::Result<()> {
assert!(res.is_err());
// now try and use the connection
let val: i32 = conn
.fetch_one(&*format!("SELECT {}::int4", i))
.await?
.get(0);
let val: i32 = conn.fetch_one(&*format!("SELECT {i}::int4")).await?.get(0);
assert_eq!(val, i);
}
@ -329,10 +326,7 @@ async fn it_can_fail_and_recover_with_pool() -> anyhow::Result<()> {
assert!(res.is_err());
// now try and use the connection
let val: i32 = pool
.fetch_one(&*format!("SELECT {}::int4", i))
.await?
.get(0);
let val: i32 = pool.fetch_one(&*format!("SELECT {i}::int4")).await?.get(0);
assert_eq!(val, i);
}
@ -558,9 +552,9 @@ async fn pool_smoke_test() -> anyhow::Result<()> {
if let Err(e) = sqlx::query("select 1 + 1").execute(&pool).await {
// normal error at termination of the test
if matches!(e, sqlx::Error::PoolClosed) {
eprintln!("pool task {} exiting normally after {} iterations", i, j);
eprintln!("pool task {i} exiting normally after {j} iterations");
} else {
eprintln!("pool task {} dying due to {} after {} iterations", i, e, j);
eprintln!("pool task {i} dying due to {e} after {j} iterations");
}
break;
}
@ -739,7 +733,7 @@ async fn it_closes_statement_from_cache_issue_470() -> anyhow::Result<()> {
let mut conn = PgConnection::connect_with(&options).await?;
for i in 0..5 {
let row = sqlx::query(&*format!("SELECT {}::int4 AS val", i))
let row = sqlx::query(&*format!("SELECT {i}::int4 AS val"))
.fetch_one(&mut conn)
.await?;
@ -822,7 +816,7 @@ async fn test_issue_622() -> anyhow::Result<()> {
.connect(&std::env::var("DATABASE_URL").unwrap())
.await?;
println!("pool state: {:?}", pool);
println!("pool state: {pool:?}");
let mut handles = vec![];
@ -850,7 +844,7 @@ async fn test_issue_622() -> anyhow::Result<()> {
println!("{} acquire took {:?}", i, start.elapsed());
drop(conn);
}
Err(e) => panic!("{} acquire returned error: {} pool state: {:?}", i, e, pool),
Err(e) => panic!("{i} acquire returned error: {e} pool state: {pool:?}"),
}
}
@ -1782,7 +1776,7 @@ async fn test_postgres_bytea_hex_deserialization_errors() -> anyhow::Result<()>
let mut conn = new::<Postgres>().await?;
conn.execute("SET bytea_output = 'escape';").await?;
for value in ["", "DEADBEEF"] {
let query = format!("SELECT '\\x{}'::bytea", value);
let query = format!("SELECT '\\x{value}'::bytea");
let res: sqlx::Result<Vec<u8>> = conn.fetch_one(query.as_str()).await?.try_get(0usize);
// Deserialization only supports hex format so this should error and definitely not panic.
res.unwrap_err();

View file

@ -421,10 +421,10 @@ async fn it_describes_literal_subquery() -> anyhow::Result<()> {
) -> anyhow::Result<()> {
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(false), "{}", query);
assert_eq!(info.column(1).type_info().name(), "NULL", "{}", query);
assert_eq!(info.nullable(1), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(false), "{query}");
assert_eq!(info.column(1).type_info().name(), "NULL", "{query}");
assert_eq!(info.nullable(1), Some(true), "{query}");
Ok(())
}
@ -458,25 +458,25 @@ async fn assert_tweet_described(
let info = conn.describe(query).await?;
let columns = info.columns();
assert_eq!(columns[0].name(), "id", "{}", query);
assert_eq!(columns[1].name(), "text", "{}", query);
assert_eq!(columns[2].name(), "is_sent", "{}", query);
assert_eq!(columns[3].name(), "owner_id", "{}", query);
assert_eq!(columns[0].name(), "id", "{query}");
assert_eq!(columns[1].name(), "text", "{query}");
assert_eq!(columns[2].name(), "is_sent", "{query}");
assert_eq!(columns[3].name(), "owner_id", "{query}");
assert_eq!(columns[0].ordinal(), 0, "{}", query);
assert_eq!(columns[1].ordinal(), 1, "{}", query);
assert_eq!(columns[2].ordinal(), 2, "{}", query);
assert_eq!(columns[3].ordinal(), 3, "{}", query);
assert_eq!(columns[0].ordinal(), 0, "{query}");
assert_eq!(columns[1].ordinal(), 1, "{query}");
assert_eq!(columns[2].ordinal(), 2, "{query}");
assert_eq!(columns[3].ordinal(), 3, "{query}");
assert_eq!(info.nullable(0), Some(false), "{}", query);
assert_eq!(info.nullable(1), Some(false), "{}", query);
assert_eq!(info.nullable(2), Some(false), "{}", query);
assert_eq!(info.nullable(3), Some(true), "{}", query);
assert_eq!(info.nullable(0), Some(false), "{query}");
assert_eq!(info.nullable(1), Some(false), "{query}");
assert_eq!(info.nullable(2), Some(false), "{query}");
assert_eq!(info.nullable(3), Some(true), "{query}");
assert_eq!(columns[0].type_info().name(), "INTEGER", "{}", query);
assert_eq!(columns[1].type_info().name(), "TEXT", "{}", query);
assert_eq!(columns[2].type_info().name(), "BOOLEAN", "{}", query);
assert_eq!(columns[3].type_info().name(), "INTEGER", "{}", query);
assert_eq!(columns[0].type_info().name(), "INTEGER", "{query}");
assert_eq!(columns[1].type_info().name(), "TEXT", "{query}");
assert_eq!(columns[2].type_info().name(), "BOOLEAN", "{query}");
assert_eq!(columns[3].type_info().name(), "INTEGER", "{query}");
Ok(())
}
@ -517,10 +517,10 @@ async fn it_describes_table_order_by() -> anyhow::Result<()> {
) -> anyhow::Result<()> {
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(false), "{}", query);
assert_eq!(info.column(1).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(1), Some(false), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(false), "{query}");
assert_eq!(info.column(1).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(1), Some(false), "{query}");
Ok(())
}
@ -555,15 +555,15 @@ async fn it_describes_union() -> anyhow::Result<()> {
) -> anyhow::Result<()> {
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(false), "{}", query);
assert_eq!(info.column(1).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(1), Some(true), "{}", query);
assert_eq!(info.column(2).type_info().name(), "INTEGER", "{}", query);
assert_eq!(info.nullable(2), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(false), "{query}");
assert_eq!(info.column(1).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(1), Some(true), "{query}");
assert_eq!(info.column(2).type_info().name(), "INTEGER", "{query}");
assert_eq!(info.nullable(2), Some(true), "{query}");
//TODO: mixed type columns not handled correctly
//assert_eq!(info.column(3).type_info().name(), "NULL", "{}", query);
//assert_eq!(info.nullable(3), Some(false), "{}", query);
//assert_eq!(info.column(3).type_info().name(), "NULL", "{query}");
//assert_eq!(info.nullable(3), Some(false), "{query}");
Ok(())
}
@ -602,8 +602,8 @@ async fn it_describes_strange_queries() -> anyhow::Result<()> {
nullable: bool,
) -> anyhow::Result<()> {
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), typename, "{}", query);
assert_eq!(info.nullable(0), Some(nullable), "{}", query);
assert_eq!(info.column(0).type_info().name(), typename, "{query}");
assert_eq!(info.nullable(0), Some(nullable), "{query}");
Ok(())
}
@ -704,23 +704,23 @@ async fn it_describes_func_date() -> anyhow::Result<()> {
let query = "SELECT date();";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(false), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(false), "{query}");
let query = "SELECT date('now');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT date('now', 'start of month');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT date(:datebind);";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}");
Ok(())
}
@ -730,23 +730,23 @@ async fn it_describes_func_time() -> anyhow::Result<()> {
let query = "SELECT time();";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(false), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(false), "{query}");
let query = "SELECT time('now');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT time('now', 'start of month');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT time(:datebind);";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}");
Ok(())
}
@ -756,23 +756,23 @@ async fn it_describes_func_datetime() -> anyhow::Result<()> {
let query = "SELECT datetime();";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(false), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(false), "{query}");
let query = "SELECT datetime('now');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT datetime('now', 'start of month');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT datetime(:datebind);";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}");
Ok(())
}
@ -782,23 +782,23 @@ async fn it_describes_func_julianday() -> anyhow::Result<()> {
let query = "SELECT julianday();";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "REAL", "{}", query);
assert_eq!(info.nullable(0), Some(false), "{}", query);
assert_eq!(info.column(0).type_info().name(), "REAL", "{query}");
assert_eq!(info.nullable(0), Some(false), "{query}");
let query = "SELECT julianday('now');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "REAL", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "REAL", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT julianday('now', 'start of month');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "REAL", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "REAL", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT julianday(:datebind);";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "REAL", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "REAL", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}");
Ok(())
}
@ -808,18 +808,18 @@ async fn it_describes_func_strftime() -> anyhow::Result<()> {
let query = "SELECT strftime('%s','now');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT strftime('%s', 'now', 'start of month');";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query); //can't prove that it's not-null yet
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}"); //can't prove that it's not-null yet
let query = "SELECT strftime('%s',:datebind);";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}");
Ok(())
}
@ -842,8 +842,8 @@ async fn it_describes_with_recursive() -> anyhow::Result<()> {
GROUP BY begin_date
";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}");
let query = "
WITH RECURSIVE schedule(begin_date) AS MATERIALIZED (
@ -860,8 +860,8 @@ async fn it_describes_with_recursive() -> anyhow::Result<()> {
GROUP BY begin_date
";
let info = conn.describe(query).await?;
assert_eq!(info.column(0).type_info().name(), "TEXT", "{}", query);
assert_eq!(info.nullable(0), Some(true), "{}", query);
assert_eq!(info.column(0).type_info().name(), "TEXT", "{query}");
assert_eq!(info.nullable(0), Some(true), "{query}");
Ok(())
}

View file

@ -651,7 +651,7 @@ async fn issue_1467() -> anyhow::Result<()> {
for i in 0..1_000_000 {
if i % 1_000 == 0 {
println!("{}", i);
println!("{i}");
}
let key = rng.gen_range(0..1_000);
let value = rng.gen_range(0..1_000);
@ -759,21 +759,21 @@ async fn test_multiple_set_progress_handler_calls_drop_old_handler() -> anyhow::
let o = ref_counted_object.clone();
conn.lock_handle().await?.set_progress_handler(1, move || {
println!("{:?}", o);
println!("{o:?}");
false
});
assert_eq!(2, Arc::strong_count(&ref_counted_object));
let o = ref_counted_object.clone();
conn.lock_handle().await?.set_progress_handler(1, move || {
println!("{:?}", o);
println!("{o:?}");
false
});
assert_eq!(2, Arc::strong_count(&ref_counted_object));
let o = ref_counted_object.clone();
conn.lock_handle().await?.set_progress_handler(1, move || {
println!("{:?}", o);
println!("{o:?}");
false
});
assert_eq!(2, Arc::strong_count(&ref_counted_object));