Skip to content

Commit

Permalink
chore: replace once_cell OnceCell/Lazy with std OnceLock/`LazyL…
Browse files Browse the repository at this point in the history
…ock`
  • Loading branch information
paolobarbolini committed Feb 1, 2025
1 parent 5b26369 commit 40e264e
Show file tree
Hide file tree
Showing 15 changed files with 42 additions and 38 deletions.
5 changes: 0 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion examples/postgres/axum-social-with-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ validator = { version = "0.16.0", features = ["derive"] }
# Auxilliary crates
anyhow = "1.0.58"
dotenvy = "0.15.1"
once_cell = "1.13.0"
thiserror = "2.0.0"
tracing = "0.1.35"

Expand Down
1 change: 0 additions & 1 deletion sqlx-bench/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ sqlite = ["sqlx/sqlite"]
[dependencies]
criterion = "0.5.1"
dotenvy = "0.15.0"
once_cell = "1.4"
sqlx = { workspace = true, default-features = false, features = ["macros"] }

chrono = "0.4.19"
Expand Down
1 change: 0 additions & 1 deletion sqlx-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ futures-intrusive = "0.5.0"
futures-util = { version = "0.3.19", default-features = false, features = ["alloc", "sink", "io"] }
log = { version = "0.4.18", default-features = false }
memchr = { version = "2.4.1", default-features = false }
once_cell = "1.9.0"
percent-encoding = "2.1.0"
regex = { version = "1.5.5", optional = true }
serde = { version = "1.0.132", features = ["derive", "rc"], optional = true }
Expand Down
4 changes: 2 additions & 2 deletions sqlx-core/src/any/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ use crate::connection::Connection;
use crate::database::Database;
use crate::Error;
use futures_core::future::BoxFuture;
use once_cell::sync::OnceCell;
use std::fmt::{Debug, Formatter};
use std::sync::OnceLock;
use url::Url;

static DRIVERS: OnceCell<&'static [AnyDriver]> = OnceCell::new();
static DRIVERS: OnceLock<&'static [AnyDriver]> = OnceLock::new();

#[macro_export]
macro_rules! declare_driver_with_optional_migrate {
Expand Down
1 change: 0 additions & 1 deletion sqlx-macros-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ dotenvy = { workspace = true }
hex = { version = "0.4.3" }
heck = { version = "0.5" }
either = "1.6.1"
once_cell = "1.9.0"
proc-macro2 = { version = "1.0.79", default-features = false }
serde = { version = "1.0.132", features = ["derive"] }
serde_json = { version = "1.0.73" }
Expand Down
8 changes: 3 additions & 5 deletions sqlx-macros-core/src/database/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::collections::hash_map;
use std::collections::HashMap;
use std::sync::Mutex;

use once_cell::sync::Lazy;
use std::sync::{LazyLock, Mutex};

use sqlx_core::connection::Connection;
use sqlx_core::database::Database;
Expand Down Expand Up @@ -30,14 +28,14 @@ pub trait DatabaseExt: Database + TypeChecking {

#[allow(dead_code)]
pub struct CachingDescribeBlocking<DB: DatabaseExt> {
connections: Lazy<Mutex<HashMap<String, DB::Connection>>>,
connections: LazyLock<Mutex<HashMap<String, DB::Connection>>>,
}

#[allow(dead_code)]
impl<DB: DatabaseExt> CachingDescribeBlocking<DB> {
pub const fn new() -> Self {
CachingDescribeBlocking {
connections: Lazy::new(|| Mutex::new(HashMap::new())),
connections: LazyLock::new(|| Mutex::new(HashMap::new())),
}
}

Expand Down
5 changes: 3 additions & 2 deletions sqlx-macros-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,13 @@ where
{
#[cfg(feature = "_rt-tokio")]
{
use once_cell::sync::Lazy;
use std::sync::LazyLock;

use tokio::runtime::{self, Runtime};

// We need a single, persistent Tokio runtime since we're caching connections,
// otherwise we'll get "IO driver has terminated" errors.
static TOKIO_RT: Lazy<Runtime> = Lazy::new(|| {
static TOKIO_RT: LazyLock<Runtime> = LazyLock::new(|| {
runtime::Builder::new_current_thread()
.enable_all()
.build()
Expand Down
7 changes: 3 additions & 4 deletions sqlx-macros-core/src/query/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ use std::fs;
use std::io::Write as _;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::{LazyLock, Mutex};

use once_cell::sync::Lazy;
use serde::{Serialize, Serializer};

use sqlx_core::database::Database;
Expand Down Expand Up @@ -65,8 +64,8 @@ impl<DB: Database> Serialize for SerializeDbName<DB> {
}
}

static OFFLINE_DATA_CACHE: Lazy<Mutex<HashMap<PathBuf, DynQueryData>>> =
Lazy::new(Default::default);
static OFFLINE_DATA_CACHE: LazyLock<Mutex<HashMap<PathBuf, DynQueryData>>> =
LazyLock::new(Default::default);

/// Offline query data
#[derive(Clone, serde::Deserialize)]
Expand Down
5 changes: 2 additions & 3 deletions sqlx-macros-core/src/query/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, LazyLock, Mutex};
use std::{fs, io};

use once_cell::sync::Lazy;
use proc_macro2::TokenStream;
use syn::Type;

Expand Down Expand Up @@ -108,7 +107,7 @@ impl Metadata {

// If we are in a workspace, lookup `workspace_root` since `CARGO_MANIFEST_DIR` won't
// reflect the workspace dir: https://github.com/rust-lang/cargo/issues/3946
static METADATA: Lazy<Metadata> = Lazy::new(|| {
static METADATA: LazyLock<Metadata> = LazyLock::new(|| {
let manifest_dir: PathBuf = env("CARGO_MANIFEST_DIR")
.expect("`CARGO_MANIFEST_DIR` must be set")
.into();
Expand Down
1 change: 0 additions & 1 deletion sqlx-mysql/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ hex = "0.4.3"
itoa = "1.0.1"
log = "0.4.18"
memchr = { version = "2.4.1", default-features = false }
once_cell = "1.9.0"
percent-encoding = "2.1.0"
smallvec = "1.7.0"
stringprep = "0.1.2"
Expand Down
17 changes: 13 additions & 4 deletions sqlx-mysql/src/testing/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::ops::Deref;
use std::str::FromStr;
use std::sync::OnceLock;
use std::time::Duration;

use futures_core::future::BoxFuture;

use once_cell::sync::OnceCell;
use sqlx_core::connection::Connection;
use sqlx_core::query_builder::QueryBuilder;
use sqlx_core::query_scalar::query_scalar;
Expand All @@ -18,8 +18,8 @@ use crate::{MySql, MySqlConnectOptions, MySqlConnection};

pub(crate) use sqlx_core::testing::*;

// Using a blocking `OnceCell` here because the critical sections are short.
static MASTER_POOL: OnceCell<Pool<MySql>> = OnceCell::new();
// Using a blocking `OnceLock` here because the critical sections are short.
static MASTER_POOL: OnceLock<Pool<MySql>> = OnceLock::new();

impl TestSupport for MySql {
fn test_context(args: &TestArgs) -> BoxFuture<'_, Result<TestContext<Self>, Error>> {
Expand Down Expand Up @@ -119,7 +119,7 @@ async fn test_context(args: &TestArgs) -> Result<TestContext<MySql>, Error> {
.after_release(|_conn, _| Box::pin(async move { Ok(false) }))
.connect_lazy_with(master_opts);

let master_pool = match MASTER_POOL.try_insert(pool) {
let master_pool = match once_lock_try_insert_polyfill(&MASTER_POOL, pool) {
Ok(inserted) => inserted,
Err((existing, pool)) => {
// Sanity checks.
Expand Down Expand Up @@ -195,3 +195,12 @@ async fn do_cleanup(conn: &mut MySqlConnection, db_name: &str) -> Result<(), Err

Ok(())
}

fn once_lock_try_insert_polyfill<T>(this: &OnceLock<T>, value: T) -> Result<&T, (&T, T)> {
let mut value = Some(value);
let res = this.get_or_init(|| value.take().unwrap());
match value {
None => Ok(res),
Some(value) => Err((res, value)),
}
}
1 change: 0 additions & 1 deletion sqlx-postgres/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ itoa = "1.0.1"
log = "0.4.18"
memchr = { version = "2.4.1", default-features = false }
num-bigint = { version = "0.4.3", optional = true }
once_cell = "1.9.0"
smallvec = { version = "1.7.0", features = ["serde"] }
stringprep = "0.1.2"
thiserror = "2.0.0"
Expand Down
6 changes: 3 additions & 3 deletions sqlx-postgres/src/advisory_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use crate::error::Result;
use crate::Either;
use crate::PgConnection;
use hkdf::Hkdf;
use once_cell::sync::OnceCell;
use sha2::Sha256;
use std::ops::{Deref, DerefMut};
use std::sync::OnceLock;

/// A mutex-like type utilizing [Postgres advisory locks].
///
Expand Down Expand Up @@ -37,7 +37,7 @@ use std::ops::{Deref, DerefMut};
pub struct PgAdvisoryLock {
key: PgAdvisoryLockKey,
/// The query to execute to release this lock.
release_query: OnceCell<String>,
release_query: OnceLock<String>,
}

/// A key type natively used by Postgres advisory locks.
Expand Down Expand Up @@ -163,7 +163,7 @@ impl PgAdvisoryLock {
pub fn with_key(key: PgAdvisoryLockKey) -> Self {
Self {
key,
release_query: OnceCell::new(),
release_query: OnceLock::new(),
}
}

Expand Down
17 changes: 13 additions & 4 deletions sqlx-postgres/src/testing/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::fmt::Write;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::OnceLock;
use std::time::Duration;

use futures_core::future::BoxFuture;

use once_cell::sync::OnceCell;
use sqlx_core::connection::Connection;
use sqlx_core::query_scalar::query_scalar;

Expand All @@ -17,8 +17,8 @@ use crate::{PgConnectOptions, PgConnection, Postgres};

pub(crate) use sqlx_core::testing::*;

// Using a blocking `OnceCell` here because the critical sections are short.
static MASTER_POOL: OnceCell<Pool<Postgres>> = OnceCell::new();
// Using a blocking `OnceLock` here because the critical sections are short.
static MASTER_POOL: OnceLock<Pool<Postgres>> = OnceLock::new();
// Automatically delete any databases created before the start of the test binary.

impl TestSupport for Postgres {
Expand Down Expand Up @@ -106,7 +106,7 @@ async fn test_context(args: &TestArgs) -> Result<TestContext<Postgres>, Error> {
.after_release(|_conn, _| Box::pin(async move { Ok(false) }))
.connect_lazy_with(master_opts);

let master_pool = match MASTER_POOL.try_insert(pool) {
let master_pool = match once_lock_try_insert_polyfill(&MASTER_POOL, pool) {
Ok(inserted) => inserted,
Err((existing, pool)) => {
// Sanity checks.
Expand Down Expand Up @@ -198,3 +198,12 @@ async fn do_cleanup(conn: &mut PgConnection, db_name: &str) -> Result<(), Error>

Ok(())
}

fn once_lock_try_insert_polyfill<T>(this: &OnceLock<T>, value: T) -> Result<&T, (&T, T)> {
let mut value = Some(value);
let res = this.get_or_init(|| value.take().unwrap());
match value {
None => Ok(res),
Some(value) => Err((res, value)),
}
}

0 comments on commit 40e264e

Please sign in to comment.