Skip to main content

waratah_api/
query_library.rs

1//! Per-repository query library: the read-only, curated list of SPARQL
2//! queries a compute publishes to the console's Query library
3//! (`GET /waratah/repositories/{id}/queries`).
4//!
5//! Only the HTTP contract is fixed (see `docs/query-library-api.md`); the
6//! storage shape is this engine's choice, mirroring the ingest-directory
7//! precedent. Two sources resolve through one [`QueryLibrary::load`]:
8//!
9//! - [`QueryLibrary::Directory`] re-reads `{queries_dir}/{repository}/*.rq`
10//!   on every request (`--queries-dir`). Each filename stem is the entry
11//!   `id`; an optional sibling `<stem>.toml` sidecar carries `name`,
12//!   `description`, and `order`. Per-entry problems (oversized, empty,
13//!   non-UTF-8 file or filename, orphan sidecar, non-regular file) skip
14//!   that entry with a once-per-file-and-reason warning; a malformed
15//!   sidecar or an unreadable real file fails the request.
16//! - [`QueryLibrary::Inline`] serves fixed entries (the `--load-demo`
17//!   samples) for any known repository, in declaration order.
18//!
19//! Response order is deterministic by construction: directory entries are
20//! collected into a `Vec` and sorted by `(order, id)` — never hashmap
21//! iteration order, which would leak into the API contract — and inline
22//! entries keep their declared order.
23
24use std::collections::HashSet;
25use std::fs::{self, File};
26use std::io::Read;
27use std::path::{Path, PathBuf};
28use std::sync::{Arc, Mutex, OnceLock};
29
30use serde::Serialize;
31use waratah_storage::queries_repo_dir;
32
33/// Skip guard for a single entry: a query text over this size is dropped
34/// with a warning instead of failing the whole endpoint (expected scale is
35/// tens of small queries; one huge file must not dominate the response).
36const MAX_QUERY_BYTES: usize = 64 * 1024;
37
38/// Extension of a published query file: `<id>.rq`.
39const QUERY_EXTENSION: &str = "rq";
40
41/// Extension of the optional metadata sidecar: `<id>.toml`.
42const SIDECAR_EXTENSION: &str = "toml";
43
44/// One published query, exactly the wire shape of
45/// `GET /waratah/repositories/{id}/queries` entries.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
47pub struct ServerQuery {
48    /// Stable identity: the filename stem (`cities.rq` → `"cities"`), or the
49    /// inline id. Doubles as the Vue list key, so it never changes between
50    /// requests or restarts.
51    pub id: String,
52    /// Display name (sidecar `name`, else derived from the stem).
53    pub name: String,
54    /// Optional one-line description (sidecar `description`).
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub description: Option<String>,
57    /// Complete SPARQL 1.1 query text: prologue + `SELECT` / `ASK` /
58    /// `CONSTRUCT` / `DESCRIBE`. Served after BOM-strip and CRLF→LF
59    /// normalization, otherwise verbatim.
60    pub query: String,
61}
62
63/// Where a repository's query library comes from.
64#[derive(Debug, Clone)]
65pub enum QueryLibrary {
66    /// Read `{root}/{repository}/*.rq` fresh on every request. `root` is the
67    /// `--queries-dir` value; there is no data-dir-derived default.
68    Directory(PathBuf),
69    /// Fixed entries served for any known repository, in declaration order
70    /// (the `--load-demo` built-in samples).
71    Inline(Arc<[ServerQuery]>),
72}
73
74/// Failure resolving a *configured* library. "Not configured at all" is a
75/// separate [`crate::error::ApiError::QueryLibraryNotConfigured`] and maps
76/// to `501`; these two map to `404` / `500`.
77#[derive(Debug, thiserror::Error)]
78pub enum QueryLibraryError {
79    /// The library feature is on, but this repository has no directory:
80    /// nothing is published for it.
81    #[error("no query library is published for repository {0}")]
82    Missing(String),
83    /// The directory or a sidecar could not be read/parsed. Loud on purpose:
84    /// a silent skip would make an operator's typo look like a missing
85    /// query in the UI.
86    #[error("{message}: {path}")]
87    Invalid {
88        /// File or directory the failure is about.
89        path: PathBuf,
90        /// Human-readable cause, printed verbatim by the HTTP layer.
91        message: String,
92    },
93}
94
95impl QueryLibrary {
96    /// Resolve the library for `repository_id`. Directory sources re-read
97    /// the filesystem on every call — the contract wants fresh data and the
98    /// expected scale is tens of small files, so there is no cache to stale.
99    pub fn load(&self, repository_id: &str) -> Result<Vec<ServerQuery>, QueryLibraryError> {
100        match self {
101            Self::Inline(entries) => Ok(entries.to_vec()),
102            Self::Directory(root) => {
103                load_directory(repository_id, &queries_repo_dir(root, repository_id))
104            }
105        }
106    }
107}
108
109/// List, read, and order every published query in `dir`.
110fn load_directory(repository_id: &str, dir: &Path) -> Result<Vec<ServerQuery>, QueryLibraryError> {
111    let mut paths: Vec<PathBuf> = Vec::new();
112    let entries = match fs::read_dir(dir) {
113        Ok(entries) => entries,
114        // Raced with a delete after the `is_dir` probe (or a mount went
115        // away): semantically the repository has no library, not a broken
116        // one.
117        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
118            return Err(QueryLibraryError::Missing(repository_id.to_owned()));
119        }
120        Err(error) => {
121            return Err(invalid(
122                dir,
123                format!("cannot read query library directory ({error})"),
124            ));
125        }
126    };
127    for entry in entries {
128        let entry = entry.map_err(|error| {
129            invalid(
130                dir,
131                format!("cannot read query library directory ({error})"),
132            )
133        })?;
134        paths.push(entry.path());
135    }
136    paths.sort();
137
138    // Stems of the published `*.rq` files, so a stray `*.toml` can be
139    // flagged as an orphan instead of silently ignored. Files only: a
140    // *directory* named `meta.rq` is not a published query and must not
141    // make its `meta.toml` look matched.
142    let query_stems: HashSet<String> = paths
143        .iter()
144        .filter(|path| has_extension(path, QUERY_EXTENSION))
145        .filter(|path| path.is_file())
146        .filter_map(|path| utf8_stem(path))
147        .collect();
148
149    let mut loaded: Vec<(i64, ServerQuery)> = Vec::new();
150    for path in &paths {
151        // `to_str`, not `to_string_lossy`: lossy replacement chars can fold
152        // two distinct filenames into one id, which would break the
153        // contract's per-list id uniqueness (and the UI's list keys).
154        let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
155            continue;
156        };
157        if file_name.starts_with('.') || path.is_dir() {
158            continue;
159        }
160        if has_extension(path, QUERY_EXTENSION) {
161            let Some(stem) = utf8_stem(path) else {
162                warn_once(path, "query filename is not valid UTF-8");
163                continue;
164            };
165            if let Some(entry) = load_query_file(path, &stem)? {
166                loaded.push(entry);
167            }
168        } else if has_extension(path, SIDECAR_EXTENSION) {
169            let Some(stem) = utf8_stem(path) else {
170                continue;
171            };
172            if !query_stems.contains(&stem) {
173                warn_once(path, "sidecar without a matching .rq file");
174            }
175        } else if has_extension_case_insensitive(path, QUERY_EXTENSION)
176            || has_extension_case_insensitive(path, SIDECAR_EXTENSION)
177        {
178            // `UPPER.RQ` is exactly the file the operator meant to publish;
179            // silently vanishing is the worst outcome, so point at the fix.
180            warn_once(
181                path,
182                "query library extensions must be lowercase (.rq / .toml)",
183            );
184        }
185        // Anything else (README.md, editor droppings) is not a published
186        // query and is ignored silently, like the ingest listing.
187    }
188
189    // Deterministic total order: explicit `order` first, ties on the unique
190    // `id`. No HashMap is ever iterated into the response.
191    loaded.sort_by(|left, right| (left.0, &left.1.id).cmp(&(right.0, &right.1.id)));
192    Ok(loaded.into_iter().map(|(_, query)| query).collect())
193}
194
195/// Read one `<id>.rq` (plus its optional sidecar) into a library entry.
196/// `id` is the validated UTF-8 filename stem. `Ok(None)` skips the file
197/// after a warning — content problems and per-entry filesystem oddities
198/// (dangling symlink, non-regular file) must not fail the whole endpoint.
199/// `Err` fails the request: unreadable real files and malformed sidecars
200/// are operator errors worth surfacing.
201fn load_query_file(path: &Path, id: &str) -> Result<Option<(i64, ServerQuery)>, QueryLibraryError> {
202    // Regular files only: a FIFO (size 0, blocks forever on read) or a
203    // broken device node would otherwise stall a request handler.
204    match fs::metadata(path) {
205        Ok(metadata) if metadata.is_file() => {}
206        Ok(_) => {
207            warn_once(path, "query is not a regular file");
208            return Ok(None);
209        }
210        // Dangling symlink and friends: the entry is gone, not broken.
211        Err(_) => {
212            warn_once(path, "query file is not readable (stat failed)");
213            return Ok(None);
214        }
215    }
216
217    // Read through a `take` window one byte past the guard so the size
218    // limit holds even if the file grows between the stat above and this
219    // read, and so a huge file never enters memory whole.
220    let file = File::open(path)
221        .map_err(|error| invalid(path, format!("cannot open query file ({error})")))?;
222    let mut bytes = Vec::new();
223    file.take(MAX_QUERY_BYTES as u64 + 1)
224        .read_to_end(&mut bytes)
225        .map_err(|error| invalid(path, format!("cannot read query file ({error})")))?;
226    if bytes.len() > MAX_QUERY_BYTES {
227        warn_once(path, "query file exceeds the 64 KiB size limit");
228        return Ok(None);
229    }
230    let query = match String::from_utf8(bytes) {
231        Ok(text) => normalize_query_text(text),
232        Err(_) => {
233            warn_once(path, "query file is not valid UTF-8");
234            return Ok(None);
235        }
236    };
237    if query.trim().is_empty() {
238        warn_once(path, "query file is empty");
239        return Ok(None);
240    }
241
242    let sidecar = load_sidecar(path)?;
243    let (name, description, order) = match sidecar {
244        Some(sidecar) => (
245            non_blank(sidecar.name),
246            non_blank(sidecar.description),
247            sidecar.order.unwrap_or(0),
248        ),
249        None => (None, None, 0),
250    };
251    let name = name.unwrap_or_else(|| humanize_stem(id));
252
253    Ok(Some((
254        order,
255        ServerQuery {
256            id: id.to_owned(),
257            name,
258            description,
259            query,
260        },
261    )))
262}
263
264/// Read and parse the optional `<id>.toml` sidecar. Strict by design
265/// (`deny_unknown_fields`): a misspelled key would otherwise silently
266/// degrade the entry to a derived name, which reads as a missing query.
267fn load_sidecar(query_path: &Path) -> Result<Option<QuerySidecar>, QueryLibraryError> {
268    let sidecar_path = query_path.with_extension(SIDECAR_EXTENSION);
269    if !sidecar_path.is_file() {
270        return Ok(None);
271    }
272    let text = fs::read_to_string(&sidecar_path).map_err(|error| {
273        invalid(
274            &sidecar_path,
275            format!("cannot read query sidecar ({error})"),
276        )
277    })?;
278    toml::from_str(&text)
279        .map(Some)
280        .map_err(|error| invalid(&sidecar_path, format!("invalid query sidecar ({error})")))
281}
282
283/// Optional `<id>.toml` display metadata for one query file.
284#[derive(Debug, Default, serde::Deserialize)]
285#[serde(deny_unknown_fields)]
286struct QuerySidecar {
287    /// Display name; blank or absent derives from the filename stem.
288    name: Option<String>,
289    /// Optional one-line description; blank is treated as absent.
290    description: Option<String>,
291    /// Ascending sort key; ties and defaults order alphabetically by id.
292    order: Option<i64>,
293}
294
295/// Derive a display name from a filename stem: `_` and `-` become spaces and
296/// only the first character is uppercased. Title-casing the rest would
297/// mangle acronyms and mixed-case ids (`rdf4j_stats` → "Rdf4j stats", not
298/// "Rdf4J Stats").
299fn humanize_stem(stem: &str) -> String {
300    let mut name = stem.replace(['_', '-'], " ");
301    // `get_mut(..1)` is `None` for a multibyte first character, which leaves
302    // non-ASCII stems untouched.
303    if let Some(first) = name.get_mut(..1) {
304        first.make_ascii_uppercase();
305    }
306    name
307}
308
309/// Strip a UTF-8 BOM and normalize CRLF/CR to LF. Editors add BOMs and
310/// Windows line endings; both would otherwise ride into the workbench and
311/// break the first `PREFIX` parse. LF files round-trip byte-for-byte.
312fn normalize_query_text(mut text: String) -> String {
313    if text.starts_with('\u{feff}') {
314        text.replace_range(..'\u{feff}'.len_utf8(), "");
315    }
316    text.replace("\r\n", "\n").replace('\r', "\n")
317}
318
319/// Drop a sidecar string that is absent or whitespace-only.
320fn non_blank(value: Option<String>) -> Option<String> {
321    value.filter(|text| !text.trim().is_empty())
322}
323
324/// The filename stem, only when the filename is valid UTF-8. Lossy stems
325/// are refused: replacement characters can fold distinct filenames into
326/// one id, and ids must be unique per list.
327fn utf8_stem(path: &Path) -> Option<String> {
328    path.file_stem()
329        .and_then(|stem| stem.to_str())
330        .map(str::to_owned)
331}
332
333fn invalid(path: &Path, message: String) -> QueryLibraryError {
334    QueryLibraryError::Invalid {
335        path: path.to_path_buf(),
336        message,
337    }
338}
339
340fn has_extension(path: &Path, extension: &str) -> bool {
341    path.extension()
342        .is_some_and(|ext| ext.to_str() == Some(extension))
343}
344
345/// Whether the extension names `extension` modulo ASCII case. Used only to
346/// warn about `UPPER.RQ`-style near misses; matching itself stays
347/// case-sensitive and lowercase-only.
348fn has_extension_case_insensitive(path: &Path, extension: &str) -> bool {
349    path.extension().is_some_and(|ext| {
350        ext.to_str()
351            .is_some_and(|ext| ext.eq_ignore_ascii_case(extension))
352    })
353}
354
355/// Emit each distinct skip warning at most once per process, keyed on the
356/// file *and* the reason: one bad file should not print a line on every
357/// panel refresh, but a file that becomes bad in a new way (or after being
358/// fixed once) is worth a fresh line. The set stays bounded by the number
359/// of distinct library files.
360fn warn_once(path: &Path, reason: &'static str) {
361    static WARNED: OnceLock<Mutex<HashSet<(PathBuf, &'static str)>>> = OnceLock::new();
362    let warned = WARNED.get_or_init(|| Mutex::new(HashSet::new()));
363    if warned
364        .lock()
365        .expect("query library warn-dedupe lock poisoned")
366        .insert((path.to_path_buf(), reason))
367    {
368        eprintln!("warning: query library skips {}: {reason}", path.display());
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375    use tempfile::tempdir;
376
377    fn write(dir: &Path, name: &str, contents: &[u8]) {
378        std::fs::write(dir.join(name), contents).unwrap();
379    }
380
381    #[test]
382    fn humanizes_stems() {
383        assert_eq!(humanize_stem("cities"), "Cities");
384        assert_eq!(humanize_stem("cities_by_country"), "Cities by country");
385        assert_eq!(humanize_stem("rdf4j_stats"), "Rdf4j stats");
386        assert_eq!(humanize_stem("2024_cities"), "2024 cities");
387        assert_eq!(humanize_stem("already-Cased"), "Already Cased");
388        // Multibyte first character: no uppercase mapping, preserved as-is.
389        assert_eq!(humanize_stem("城市"), "城市");
390    }
391
392    #[test]
393    fn normalizes_bom_and_line_endings() {
394        assert_eq!(
395            normalize_query_text("\u{feff}SELECT 1".to_owned()),
396            "SELECT 1"
397        );
398        assert_eq!(normalize_query_text("a\r\nb\rc".to_owned()), "a\nb\nc");
399        assert_eq!(normalize_query_text("a\nb".to_owned()), "a\nb");
400    }
401
402    #[test]
403    fn directory_sorts_by_order_then_id_and_derives_names() {
404        let dir = tempdir().unwrap();
405        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
406        fs::create_dir_all(&repo).unwrap();
407        write(&repo, "alpha.rq", b"SELECT ?s WHERE { ?s ?p ?o }");
408        write(&repo, "beta.rq", b"SELECT 1");
409        write(
410            &repo,
411            "beta.toml",
412            b"name = \"Beta cities\"\ndescription = \"Two-word description\"\norder = 10\n",
413        );
414        write(&repo, "gamma.rq", b"SELECT 2");
415        write(&repo, "README.md", b"not a query\n");
416        write(&repo, ".hidden.rq", b"SELECT 3");
417        // No `delta.rq`: orphan sidecar is warned about and yields nothing.
418        write(&repo, "delta.toml", b"name = \"Orphan\"\n");
419
420        let library = QueryLibrary::Directory(dir.path().to_path_buf());
421        let queries = library.load("main").unwrap();
422        assert_eq!(
423            queries,
424            vec![
425                ServerQuery {
426                    id: "alpha".into(),
427                    name: "Alpha".into(),
428                    description: None,
429                    query: "SELECT ?s WHERE { ?s ?p ?o }".into(),
430                },
431                ServerQuery {
432                    id: "gamma".into(),
433                    name: "Gamma".into(),
434                    description: None,
435                    query: "SELECT 2".into(),
436                },
437                ServerQuery {
438                    id: "beta".into(),
439                    name: "Beta cities".into(),
440                    description: Some("Two-word description".into()),
441                    query: "SELECT 1".into(),
442                },
443            ]
444        );
445    }
446
447    #[test]
448    fn blank_sidecar_fields_fall_back_to_derived_name() {
449        let dir = tempdir().unwrap();
450        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
451        fs::create_dir_all(&repo).unwrap();
452        write(&repo, "delta.rq", b"SELECT 4");
453        write(&repo, "delta.toml", b"name = \"\"\ndescription = \"   \"\n");
454
455        let library = QueryLibrary::Directory(dir.path().to_path_buf());
456        let queries = library.load("main").unwrap();
457        assert_eq!(queries.len(), 1);
458        assert_eq!(queries[0].name, "Delta");
459        assert_eq!(queries[0].description, None);
460    }
461
462    #[test]
463    fn missing_repository_directory_is_missing() {
464        let dir = tempdir().unwrap();
465        let library = QueryLibrary::Directory(dir.path().to_path_buf());
466        assert!(matches!(
467            library.load("main"),
468            Err(QueryLibraryError::Missing(repo)) if repo == "main"
469        ));
470    }
471
472    #[test]
473    fn skips_oversized_empty_and_non_utf8_entries() {
474        let dir = tempdir().unwrap();
475        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
476        fs::create_dir_all(&repo).unwrap();
477        let oversized = vec![b'#'; MAX_QUERY_BYTES + 1];
478        write(&repo, "big.rq", &oversized);
479        write(&repo, "empty.rq", b"   \n");
480        write(&repo, "binary.rq", b"\xff\xfe\xfd");
481        write(&repo, "good.rq", b"SELECT 5");
482        write(
483            &repo,
484            "orphan.toml",
485            b"description = \"nothing points here\"\n",
486        );
487
488        let library = QueryLibrary::Directory(dir.path().to_path_buf());
489        let queries = library.load("main").unwrap();
490        assert_eq!(queries.len(), 1);
491        assert_eq!(queries[0].id, "good");
492    }
493
494    #[test]
495    fn strict_sidecar_rejects_unknown_keys() {
496        let dir = tempdir().unwrap();
497        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
498        fs::create_dir_all(&repo).unwrap();
499        write(&repo, "typo.rq", b"SELECT 6");
500        write(&repo, "typo.toml", b"nam = \"misspelled\"\n");
501
502        let library = QueryLibrary::Directory(dir.path().to_path_buf());
503        match library.load("main") {
504            Err(QueryLibraryError::Invalid { path, message }) => {
505                assert!(path.ends_with("typo.toml"));
506                assert!(message.contains("invalid query sidecar"));
507            }
508            other => panic!("expected Invalid, got {other:?}"),
509        }
510    }
511
512    #[test]
513    fn bom_and_crlf_round_trip_through_the_loader() {
514        let dir = tempdir().unwrap();
515        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
516        fs::create_dir_all(&repo).unwrap();
517        write(
518            &repo,
519            "weather.rq",
520            "\u{feff}PREFIX ex: <http://ex/>\r\nSELECT ?w WHERE { ?c ex:hasWeather ?w . }\r\n"
521                .as_bytes(),
522        );
523
524        let library = QueryLibrary::Directory(dir.path().to_path_buf());
525        let queries = library.load("main").unwrap();
526        assert_eq!(
527            queries[0].query,
528            "PREFIX ex: <http://ex/>\nSELECT ?w WHERE { ?c ex:hasWeather ?w . }\n"
529        );
530    }
531
532    #[test]
533    fn inline_entries_keep_declaration_order() {
534        let entries = vec![
535            ServerQuery {
536                id: "z_last".into(),
537                name: "Z last".into(),
538                description: None,
539                query: "SELECT 1".into(),
540            },
541            ServerQuery {
542                id: "a_first".into(),
543                name: "A first".into(),
544                description: None,
545                query: "SELECT 2".into(),
546            },
547        ];
548        let library = QueryLibrary::Inline(entries.clone().into());
549        // Declared order, not the `(order, id)` sort the directory applies.
550        assert_eq!(library.load("main").unwrap(), entries);
551    }
552
553    #[test]
554    fn repeated_loads_are_deterministic() {
555        let dir = tempdir().unwrap();
556        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
557        fs::create_dir_all(&repo).unwrap();
558        for stem in ["one", "two", "three", "four"] {
559            write(&repo, &format!("{stem}.rq"), b"SELECT 1");
560        }
561        let library = QueryLibrary::Directory(dir.path().to_path_buf());
562        let first = library.load("main").unwrap();
563        let second = library.load("main").unwrap();
564        assert_eq!(first, second);
565        assert_eq!(
566            first.iter().map(|q| q.id.as_str()).collect::<Vec<_>>(),
567            vec!["four", "one", "three", "two"]
568        );
569    }
570
571    #[test]
572    #[cfg(unix)]
573    fn non_utf8_filenames_are_skipped_not_lossy_folded() {
574        use std::os::unix::ffi::OsStrExt;
575        // Regression: `to_string_lossy` folded `a\xFF.rq` and `a\xFE.rq`
576        // into the same id, emitting two entries with one id and breaking
577        // the contract's per-list uniqueness (and the UI's list keys).
578        let dir = tempdir().unwrap();
579        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
580        fs::create_dir_all(&repo).unwrap();
581        let unsafe_name = |bytes: &[u8]| std::ffi::OsStr::from_bytes(bytes).to_os_string();
582        std::fs::write(repo.join(unsafe_name(b"a\xff")), b"SELECT 6").unwrap();
583        std::fs::write(repo.join(unsafe_name(b"a\xfe")), b"SELECT 7").unwrap();
584        write(&repo, "good.rq", b"SELECT 1");
585
586        let library = QueryLibrary::Directory(dir.path().to_path_buf());
587        let queries = library.load("main").unwrap();
588        assert_eq!(queries.len(), 1);
589        assert_eq!(queries[0].id, "good");
590    }
591
592    #[cfg(unix)]
593    #[test]
594    fn dangling_symlink_is_skipped_not_a_server_error() {
595        let dir = tempdir().unwrap();
596        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
597        fs::create_dir_all(&repo).unwrap();
598        std::os::unix::fs::symlink(repo.join("missing.rq"), repo.join("gone.rq")).unwrap();
599        write(&repo, "real.rq", b"SELECT 1");
600
601        let library = QueryLibrary::Directory(dir.path().to_path_buf());
602        let queries = library.load("main").unwrap();
603        assert_eq!(queries.len(), 1);
604        assert_eq!(queries[0].id, "real");
605    }
606
607    #[test]
608    fn directory_named_like_a_query_does_not_match_its_sidecar() {
609        // A directory `meta.rq` is not a published query, so `meta.toml`
610        // must still be flagged as an orphan (and a broken `meta.toml` next
611        // to it must stay invisible — the entry does not exist to parse).
612        let dir = tempdir().unwrap();
613        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
614        fs::create_dir_all(repo.join("meta.rq")).unwrap();
615        write(&repo, "meta.toml", b"name = \"Orphan\"\n");
616        write(&repo, "real.rq", b"SELECT 1");
617
618        let library = QueryLibrary::Directory(dir.path().to_path_buf());
619        let queries = library.load("main").unwrap();
620        assert_eq!(queries.len(), 1);
621        assert_eq!(queries[0].id, "real");
622    }
623
624    #[test]
625    fn uppercase_extension_is_skipped() {
626        let dir = tempdir().unwrap();
627        let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
628        fs::create_dir_all(&repo).unwrap();
629        write(&repo, "LOUD.RQ", b"SELECT 1");
630        write(&repo, "quiet.rq", b"SELECT 2");
631
632        let library = QueryLibrary::Directory(dir.path().to_path_buf());
633        let queries = library.load("main").unwrap();
634        assert_eq!(
635            queries.iter().map(|q| q.id.as_str()).collect::<Vec<_>>(),
636            vec!["quiet"]
637        );
638    }
639}