Skip to content

Commit b6b09f3

Browse files
committed
chore(config): remove use of once_cell (to match main)
1 parent fc206e1 commit b6b09f3

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
@@ -66,10 +66,10 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
6666
} => {
6767
let config = config.load_config().await?;
6868

69-
connect_opts.populate_db_url(config)?;
69+
connect_opts.populate_db_url(&config)?;
7070

7171
migrate::run(
72-
config,
72+
&config,
7373
&source,
7474
&connect_opts,
7575
dry_run,
@@ -88,10 +88,10 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
8888
} => {
8989
let config = config.load_config().await?;
9090

91-
connect_opts.populate_db_url(config)?;
91+
connect_opts.populate_db_url(&config)?;
9292

9393
migrate::revert(
94-
config,
94+
&config,
9595
&source,
9696
&connect_opts,
9797
dry_run,
@@ -107,9 +107,9 @@ async fn do_run(opt: Opt) -> anyhow::Result<()> {
107107
} => {
108108
let config = config.load_config().await?;
109109

110-
connect_opts.populate_db_url(config)?;
110+
connect_opts.populate_db_url(&config)?;
111111

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

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

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

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

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

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

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

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

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
@@ -27,7 +27,7 @@ mod output;
2727
pub struct QueryDriver {
2828
db_name: &'static str,
2929
url_schemes: &'static [&'static str],
30-
expand: fn(QueryMacroInput, QueryDataSource) -> crate::Result<TokenStream>,
30+
expand: fn(&Config, QueryMacroInput, QueryDataSource) -> crate::Result<TokenStream>,
3131
}
3232

3333
impl QueryDriver {
@@ -75,6 +75,7 @@ struct Metadata {
7575
offline: bool,
7676
database_url: Option<String>,
7777
offline_dir: Option<String>,
78+
config: Config,
7879
workspace_root: Arc<Mutex<Option<PathBuf>>>,
7980
}
8081

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

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

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

132131
Ok(Metadata {
133132
manifest_dir,
134133
offline,
135134
database_url,
136135
offline_dir,
136+
config,
137137
workspace_root: Arc::new(Mutex::new(None)),
138138
})
139139
}
@@ -197,7 +197,7 @@ pub fn expand_input<'a>(
197197

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

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

221221
fn expand_with<DB: DatabaseExt>(
222+
config: &Config,
222223
input: QueryMacroInput,
223224
data_source: QueryDataSource,
224225
) -> crate::Result<TokenStream>
@@ -233,7 +234,7 @@ where
233234
}
234235
};
235236

236-
expand_with_data(input, query_data, offline)
237+
expand_with_data(config, input, query_data, offline)
237238
}
238239

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

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

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

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

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

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

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

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)