Skip to content

Commit 42e651c

Browse files
committed
Customize the macro error message based on the metadata
1 parent 35ba8e2 commit 42e651c

File tree

1 file changed

+35
-23
lines changed
  • sqlx-macros-core/src/query

1 file changed

+35
-23
lines changed

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

+35-23
Original file line numberDiff line numberDiff line change
@@ -160,34 +160,46 @@ pub fn expand_input<'a>(
160160
..
161161
} => QueryDataSource::live(db_url)?,
162162

163-
_ => {
163+
Metadata {
164+
offline,
165+
database_url,
166+
..
167+
} => {
164168
// Try load the cached query metadata file.
165169
let filename = format!("query-{}.json", hash_string(&input.sql));
166170

167171
// Check SQLX_OFFLINE_DIR, then local .sqlx, then workspace .sqlx.
168-
let data_file_path = if let Some(sqlx_offline_dir_path) = env("SQLX_OFFLINE_DIR")
169-
.ok()
170-
.map(PathBuf::from)
172+
let dirs = [
173+
env("SQLX_OFFLINE_DIR").ok().map(PathBuf::from),
174+
Some(METADATA.manifest_dir.join(".sqlx")),
175+
Some(METADATA.workspace_root().join(".sqlx")),
176+
];
177+
let Some(data_file_path) = dirs
178+
.iter()
179+
.filter_map(|path| path.as_ref())
171180
.map(|path| path.join(&filename))
172-
.filter(|path| path.exists())
173-
{
174-
sqlx_offline_dir_path
175-
} else if let Some(local_path) =
176-
Some(METADATA.manifest_dir.join(".sqlx").join(&filename))
177-
.filter(|path| path.exists())
178-
{
179-
local_path
180-
} else if let Some(workspace_path) =
181-
Some(METADATA.workspace_root().join(".sqlx").join(&filename))
182-
.filter(|path| path.exists())
183-
{
184-
workspace_path
185-
} else {
186-
return Err(
187-
"`DATABASE_URL` must be set, or `cargo sqlx prepare` must have been run \
188-
and .sqlx must exist, to use query macros"
189-
.into(),
190-
);
181+
.find(|path| path.exists())
182+
else {
183+
let any_dir_exists = dirs
184+
.iter()
185+
.filter_map(|path| path.as_ref())
186+
.any(|path| path.exists());
187+
return Err([
188+
match (database_url, offline) {
189+
(None, false) => {
190+
"`DATABASE_URL` must be set to use query macros online, or "
191+
}
192+
(Some(_), true) => {
193+
"`SQLX_OFFLINE=true` must be disabled to use query macros online, or "
194+
}
195+
_ => "",
196+
},
197+
if any_dir_exists {
198+
"`cargo sqlx prepare` must be run to update the prepared files"
199+
} else {
200+
"`cargo sqlx prepare` must be run and .sqlx to exist to use query macros offline"
201+
},
202+
].join("").into());
191203
};
192204

193205
QueryDataSource::Cached(DynQueryData::from_data_file(&data_file_path, &input.sql)?)

0 commit comments

Comments
 (0)