Skip to content

Commit 75db4df

Browse files
committed
chore(config): remove use of once_cell (to match main)
1 parent a98496d commit 75db4df

File tree

7 files changed

+47
-78
lines changed

7 files changed

+47
-78
lines changed

sqlx-cli/src/lib.rs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,10 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
6565
} => {
6666
let config = config.load_config().await?;
6767

68-
connect_opts.populate_db_url(config)?;
68+
connect_opts.populate_db_url(&config)?;
6969

7070
migrate::run(
71-
config,
71+
&config,
7272
&source,
7373
&connect_opts,
7474
dry_run,
@@ -87,10 +87,10 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
8787
} => {
8888
let config = config.load_config().await?;
8989

90-
connect_opts.populate_db_url(config)?;
90+
connect_opts.populate_db_url(&config)?;
9191

9292
migrate::revert(
93-
config,
93+
&config,
9494
&source,
9595
&connect_opts,
9696
dry_run,
@@ -106,9 +106,9 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
106106
} => {
107107
let config = config.load_config().await?;
108108

109-
connect_opts.populate_db_url(config)?;
109+
connect_opts.populate_db_url(&config)?;
110110

111-
migrate::info(config, &source, &connect_opts).await?
111+
migrate::info(&config, &source, &connect_opts).await?
112112
}
113113
MigrateCommand::BuildScript {
114114
source,
@@ -117,7 +117,7 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
117117
} => {
118118
let config = config.load_config().await?;
119119

120-
migrate::build_script(config, &source, force)?
120+
migrate::build_script(&config, &source, force)?
121121
}
122122
},
123123

@@ -128,7 +128,7 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
128128
} => {
129129
let config = config.load_config().await?;
130130

131-
connect_opts.populate_db_url(config)?;
131+
connect_opts.populate_db_url(&config)?;
132132
database::create(&connect_opts).await?
133133
}
134134
DatabaseCommand::Drop {
@@ -139,7 +139,7 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
139139
} => {
140140
let config = config.load_config().await?;
141141

142-
connect_opts.populate_db_url(config)?;
142+
connect_opts.populate_db_url(&config)?;
143143
database::drop(&connect_opts, !confirmation.yes, force).await?
144144
}
145145
DatabaseCommand::Reset {
@@ -151,8 +151,8 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
151151
} => {
152152
let config = config.load_config().await?;
153153

154-
connect_opts.populate_db_url(config)?;
155-
database::reset(config, &source, &connect_opts, !confirmation.yes, force).await?
154+
connect_opts.populate_db_url(&config)?;
155+
database::reset(&config, &source, &connect_opts, !confirmation.yes, force).await?
156156
}
157157
DatabaseCommand::Setup {
158158
source,
@@ -161,8 +161,8 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
161161
} => {
162162
let config = config.load_config().await?;
163163

164-
connect_opts.populate_db_url(config)?;
165-
database::setup(config, &source, &connect_opts).await?
164+
connect_opts.populate_db_url(&config)?;
165+
database::setup(&config, &source, &connect_opts).await?
166166
}
167167
},
168168

@@ -175,7 +175,7 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
175175
config,
176176
} => {
177177
let config = config.load_config().await?;
178-
connect_opts.populate_db_url(config)?;
178+
connect_opts.populate_db_url(&config)?;
179179
prepare::run(check, all, workspace, connect_opts, args).await?
180180
}
181181

sqlx-cli/src/migrate.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,15 @@ use std::time::Duration;
1414
pub async fn add(opts: AddMigrationOpts) -> anyhow::Result<()> {
1515
let config = opts.config.load_config().await?;
1616

17-
let source = opts.source.resolve_path(config);
17+
let source = opts.source.resolve_path(&config);
1818

1919
fs::create_dir_all(source).context("Unable to create migrations directory")?;
2020

21-
let migrator = opts.source.resolve(config).await?;
21+
let migrator = opts.source.resolve(&config).await?;
2222

23-
let version_prefix = opts.version_prefix(config, &migrator);
23+
let version_prefix = opts.version_prefix(&config, &migrator);
2424

25-
if opts.reversible(config, &migrator) {
25+
if opts.reversible(&config, &migrator) {
2626
create_file(
2727
source,
2828
&version_prefix,

sqlx-cli/src/opt.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ impl ConnectOpts {
455455
}
456456

457457
impl ConfigOpt {
458-
pub async fn load_config(&self) -> anyhow::Result<&'static Config> {
458+
pub async fn load_config(&self) -> anyhow::Result<Config> {
459459
let path = self.config.clone();
460460

461461
// Tokio does file I/O on a background task anyway
@@ -470,7 +470,7 @@ impl ConfigOpt {
470470
eprintln!("Found `sqlx.toml` in current directory; reading...");
471471
Ok(Config::try_from_path(path)?)
472472
} else {
473-
Ok(Config::get_or_default())
473+
Ok(Config::default())
474474
}
475475
}
476476
})

sqlx-core/src/config/mod.rs

Lines changed: 11 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,6 @@ use std::fmt::Debug;
1616
use std::io;
1717
use std::path::{Path, PathBuf};
1818

19-
// `std::sync::OnceLock` doesn't have a stable `.get_or_try_init()`
20-
// because it's blocked on a stable `Try` trait.
21-
use once_cell::sync::OnceCell;
22-
2319
/// Configuration shared by multiple components.
2420
///
2521
/// See [`common::Config`] for details.
@@ -145,8 +141,6 @@ impl ConfigError {
145141
}
146142
}
147143

148-
static CACHE: OnceCell<Config> = OnceCell::new();
149-
150144
/// Internal methods for loading a `Config`.
151145
#[allow(clippy::result_large_err)]
152146
impl Config {
@@ -157,34 +151,13 @@ impl Config {
157151
/// Errors if `CARGO_MANIFEST_DIR` is not set, or if the config file could not be read.
158152
///
159153
/// If the file does not exist, the cache is populated with `Config::default()`.
160-
pub fn try_from_crate_or_default() -> Result<&'static Self, ConfigError> {
161-
CACHE.get_or_try_init(|| {
162-
Self::read_from(get_crate_path()?).or_else(|e| {
163-
if let ConfigError::NotFound { .. } = e {
164-
Ok(Config::default())
165-
} else {
166-
Err(e)
167-
}
168-
})
169-
})
170-
}
171-
172-
/// Get the cached config, or read `$CARGO_MANIFEST_DIR/sqlx.toml`.
173-
///
174-
/// On success, the config is cached in a `static` and returned by future calls.
175-
///
176-
/// Errors if `CARGO_MANIFEST_DIR` is not set, or if the config file could not be read.
177-
///
178-
/// If the file does not exist, the cache is populated with `Config::default()`.
179-
pub fn try_from_crate_or_default() -> Result<&'static Self, ConfigError> {
180-
CACHE.get_or_try_init(|| {
181-
Self::read_from(get_crate_path()?).or_else(|e| {
182-
if let ConfigError::NotFound { .. } = e {
183-
Ok(Config::default())
184-
} else {
185-
Err(e)
186-
}
187-
})
154+
pub fn try_from_crate_or_default() -> Result<Self, ConfigError> {
155+
Self::read_from(get_crate_path()?).or_else(|e| {
156+
if let ConfigError::NotFound { .. } = e {
157+
Ok(Config::default())
158+
} else {
159+
Err(e)
160+
}
188161
})
189162
}
190163

@@ -193,13 +166,8 @@ impl Config {
193166
/// On success, the config is cached in a `static` and returned by future calls.
194167
///
195168
/// Errors if the config file does not exist, or could not be read.
196-
pub fn try_from_path(path: PathBuf) -> Result<&'static Self, ConfigError> {
197-
CACHE.get_or_try_init(|| Self::read_from(path))
198-
}
199-
200-
/// Get the cached config, or return the default.
201-
pub fn get_or_default() -> &'static Self {
202-
CACHE.get_or_init(Config::default)
169+
pub fn try_from_path(path: PathBuf) -> Result<Self, ConfigError> {
170+
Self::read_from(path)
203171
}
204172

205173
#[cfg(feature = "sqlx-toml")]
@@ -225,8 +193,8 @@ impl Config {
225193
#[cfg(not(feature = "sqlx-toml"))]
226194
fn read_from(path: PathBuf) -> Result<Self, ConfigError> {
227195
match path.try_exists() {
228-
Ok(true) => Err(ConfigError::ParseDisabled { path: path.into() }),
229-
Ok(false) => Err(ConfigError::NotFound { path: path.into() }),
196+
Ok(true) => Err(ConfigError::ParseDisabled { path }),
197+
Ok(false) => Err(ConfigError::NotFound { path }),
230198
Err(e) => Err(ConfigError::from_io(path, e)),
231199
}
232200
}

sqlx-macros-core/src/migrate.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,10 +96,10 @@ pub fn expand(path_arg: Option<LitStr>) -> crate::Result<TokenStream> {
9696

9797
let path = match path_arg {
9898
Some(path_arg) => crate::common::resolve_path(path_arg.value(), path_arg.span())?,
99-
None => { crate::common::resolve_path(default_path(config), Span::call_site()) }?,
99+
None => { crate::common::resolve_path(default_path(&config), Span::call_site()) }?,
100100
};
101101

102-
expand_with_path(config, &path)
102+
expand_with_path(&config, &path)
103103
}
104104

105105
pub fn expand_with_path(config: &Config, path: &Path) -> crate::Result<TokenStream> {

sqlx-macros-core/src/query/mod.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ mod output;
2828
pub struct QueryDriver {
2929
db_name: &'static str,
3030
url_schemes: &'static [&'static str],
31-
expand: fn(QueryMacroInput, QueryDataSource) -> crate::Result<TokenStream>,
31+
expand: fn(&Config, QueryMacroInput, QueryDataSource) -> crate::Result<TokenStream>,
3232
}
3333

3434
impl QueryDriver {
@@ -76,6 +76,7 @@ struct Metadata {
7676
offline: bool,
7777
database_url: Option<String>,
7878
offline_dir: Option<String>,
79+
config: Config,
7980
workspace_root: Arc<Mutex<Option<PathBuf>>>,
8081
}
8182

@@ -124,17 +125,16 @@ fn init_metadata(manifest_dir: &String) -> crate::Result<Metadata> {
124125
.map(|s| s.eq_ignore_ascii_case("true") || s == "1")
125126
.unwrap_or(false);
126127

127-
let var_name = Config::try_from_crate_or_default()?
128-
.common
129-
.database_url_var();
128+
let config = Config::try_from_crate_or_default()?;
130129

131-
let database_url = env(var_name).ok().or(database_url);
130+
let database_url = env(config.common.database_url_var()).ok().or(database_url);
132131

133132
Ok(Metadata {
134133
manifest_dir,
135134
offline,
136135
database_url,
137136
offline_dir,
137+
config,
138138
workspace_root: Arc::new(Mutex::new(None)),
139139
})
140140
}
@@ -198,7 +198,7 @@ pub fn expand_input<'a>(
198198

199199
for driver in drivers {
200200
if data_source.matches_driver(driver) {
201-
return (driver.expand)(input, data_source);
201+
return (driver.expand)(&metadata.config, input, data_source);
202202
}
203203
}
204204

@@ -220,6 +220,7 @@ pub fn expand_input<'a>(
220220
}
221221

222222
fn expand_with<DB: DatabaseExt>(
223+
config: &Config,
223224
input: QueryMacroInput,
224225
data_source: QueryDataSource,
225226
) -> crate::Result<TokenStream>
@@ -234,7 +235,7 @@ where
234235
}
235236
};
236237

237-
expand_with_data(input, query_data, offline)
238+
expand_with_data(config, input, query_data, offline)
238239
}
239240

240241
// marker trait for `Describe` that lets us conditionally require it to be `Serialize + Deserialize`
@@ -252,15 +253,14 @@ struct Warnings {
252253
}
253254

254255
fn expand_with_data<DB: DatabaseExt>(
256+
config: &Config,
255257
input: QueryMacroInput,
256258
data: QueryData<DB>,
257259
offline: bool,
258260
) -> crate::Result<TokenStream>
259261
where
260262
Describe<DB>: DescribeExt,
261263
{
262-
let config = Config::try_from_crate_or_default()?;
263-
264264
// validate at the minimum that our args match the query's input parameters
265265
let num_parameters = match data.describe.parameters() {
266266
Some(Either::Left(params)) => Some(params.len()),
@@ -279,7 +279,7 @@ where
279279

280280
let mut warnings = Warnings::default();
281281

282-
let args_tokens = args::quote_args(&input, config, &mut warnings, &data.describe)?;
282+
let args_tokens = args::quote_args(&input, &config, &mut warnings, &data.describe)?;
283283

284284
let query_args = format_ident!("query_args");
285285

@@ -298,7 +298,8 @@ where
298298
} else {
299299
match input.record_type {
300300
RecordType::Generated => {
301-
let columns = output::columns_to_rust::<DB>(&data.describe, config, &mut warnings)?;
301+
let columns =
302+
output::columns_to_rust::<DB>(&data.describe, &config, &mut warnings)?;
302303

303304
let record_name: Type = syn::parse_str("Record").unwrap();
304305

sqlx-macros-core/src/test_attr.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,12 @@ fn expand_advanced(args: AttributeArgs, input: syn::ItemFn) -> crate::Result<Tok
149149
quote! { args.migrator(&#migrator); }
150150
}
151151
MigrationsOpt::InferredPath if !inputs.is_empty() => {
152-
let path = crate::migrate::default_path(config);
152+
let path = crate::migrate::default_path(&config);
153153

154154
let resolved_path = crate::common::resolve_path(path, proc_macro2::Span::call_site())?;
155155

156156
if resolved_path.is_dir() {
157-
let migrator = crate::migrate::expand_with_path(config, &resolved_path)?;
157+
let migrator = crate::migrate::expand_with_path(&config, &resolved_path)?;
158158
quote! { args.migrator(&#migrator); }
159159
} else {
160160
quote! {}

0 commit comments

Comments
 (0)