Skip to main content

mago_database/
lib.rs

1#![allow(clippy::exhaustive_enums)]
2
3//! High-performance file database for PHP projects.
4//!
5//! This crate provides an efficient in-memory database for managing collections of PHP source files.
6//! It offers two complementary database types optimized for different access patterns:
7//!
8//! - [`Database`]: Mutable builder optimized for modifications (add, update, delete)
9//! - [`ReadDatabase`]: Immutable snapshot optimized for high-performance reads
10//!
11//! # Architecture
12//!
13//! The database uses a two-phase approach:
14//!
15//! 1. **Build Phase**: Use [`Database`] to load files, make modifications, and track changes
16//! 2. **Query Phase**: Convert to [`ReadDatabase`] via [`Database::read_only`] for fast lookups
17//!
18//! # Key Features
19//!
20//! - **Fast Lookups**: O(1) average-time access by ID, name, or filesystem path
21//! - **Change Tracking**: Record and batch apply file modifications via [`ChangeLog`]
22//! - **Deterministic Iteration**: [`ReadDatabase`] guarantees consistent iteration order
23//! - **Parallel Operations**: Concurrent file I/O and processing support
24//! - **Type Safety**: Strong typing with stable [`FileId`] handles
25//!
26//! # Common Workflow
27//!
28//! ## Loading Files
29//!
30//! Use [`loader::DatabaseLoader`] to scan a project directory:
31//!
32//! The loader handles file discovery, exclusion patterns, and parallel loading.
33//!
34//! ## Querying Files
35//!
36//! Both database types implement [`DatabaseReader`] for uniform access:
37//!
38//! ## Modifying Files
39//!
40//! Use [`ChangeLog`] to batch modifications:
41//!
42//! Changes can be applied to the database and optionally written to disk in parallel.
43//!
44//! # Performance Characteristics
45//!
46//! ## Database (Mutable)
47//!
48//! - Add/Update/Delete: O(1) average
49//! - Lookup by ID/name: O(1) average
50//! - Iteration: Unordered
51//! - Memory: ~2x file count (maps for bidirectional lookup)
52//!
53//! ## `ReadDatabase` (Immutable)
54//!
55//! - Creation: O(n log n) for sorting
56//! - Lookup by ID/name/path: O(1) average; first name or path lookup builds its index in O(n)
57//! - Iteration: Deterministic, sorted by `FileId`
58//! - Memory: ~3x file count (vector + 3 index maps)
59//!
60//! # Thread Safety
61//!
62//! [`Database`] is not thread-safe and should be used from a single thread during construction.
63//! [`ReadDatabase`] can be freely shared across threads for concurrent read access.
64
65use std::borrow::Cow;
66use std::path::Path;
67use std::path::PathBuf;
68use std::sync::Arc;
69use std::sync::OnceLock;
70
71use foldhash::HashMap;
72use foldhash::HashMapExt;
73use rayon::iter::IntoParallelIterator;
74use rayon::iter::ParallelIterator;
75
76use crate::change::Change;
77use crate::change::ChangeLog;
78use crate::error::DatabaseError;
79use crate::exclusion::Exclusion;
80use crate::file::File;
81use crate::file::FileId;
82use crate::file::FileType;
83use crate::file::line_starts;
84use crate::operation::FilesystemOperation;
85
86mod utils;
87
88pub mod change;
89pub mod error;
90pub mod exclusion;
91pub mod file;
92pub mod loader;
93pub mod matcher;
94pub mod membership;
95pub mod watcher;
96
97mod operation;
98
99/// Configuration for database loading and watching.
100#[derive(Debug, Clone)]
101#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
102pub struct DatabaseConfiguration<'config> {
103    pub workspace: Cow<'config, Path>,
104    /// Paths or glob patterns for source files.
105    /// Can be directory paths (e.g., "src") or glob patterns (e.g., "src/**/*.php")
106    pub paths: Vec<Cow<'config, [u8]>>,
107    /// Paths or glob patterns for included files.
108    /// Can be directory paths (e.g., "vendor") or glob patterns (e.g., "vendor/**/*.php")
109    pub includes: Vec<Cow<'config, [u8]>>,
110    pub patches: Vec<Cow<'config, [u8]>>,
111    pub excludes: Vec<Exclusion<'config>>,
112    pub extensions: Vec<Cow<'config, [u8]>>,
113    /// Settings for glob pattern matching behavior.
114    pub glob: GlobSettings,
115}
116
117/// Settings for glob pattern matching behavior.
118///
119/// All defaults match the `globset` crate defaults for backwards compatibility.
120#[derive(Debug, Clone, Copy)]
121#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
122pub struct GlobSettings {
123    /// Match patterns case-insensitively.
124    ///
125    /// Default: `false`.
126    pub case_insensitive: bool,
127    /// When `true`, a single `*` does not match path separators (`/`).
128    /// This makes `src/*/Test` match only `src/foo/Test`, not `src/foo/bar/Test`.
129    /// Use `**` for recursive matching.
130    ///
131    /// Default: `false`.
132    pub literal_separator: bool,
133    /// Whether `\` escapes special characters in patterns.
134    ///
135    /// Default: `true`.
136    pub backslash_escape: bool,
137    /// Whether an empty case in alternates is allowed (e.g., `{,a}` matches `""` and `"a"`).
138    ///
139    /// Default: `false`.
140    pub empty_alternates: bool,
141}
142
143impl Default for GlobSettings {
144    #[inline]
145    fn default() -> Self {
146        Self {
147            case_insensitive: false,
148            literal_separator: false,
149            backslash_escape: !std::path::is_separator('\\'),
150            empty_alternates: false,
151        }
152    }
153}
154
155impl<'config> DatabaseConfiguration<'config> {
156    #[inline]
157    #[must_use]
158    pub fn new(
159        workspace: &'config Path,
160        paths: Vec<&'config [u8]>,
161        includes: Vec<&'config [u8]>,
162        excludes: Vec<Exclusion<'config>>,
163        extensions: Vec<&'config [u8]>,
164    ) -> Self {
165        let paths = paths.into_iter().map(Cow::Borrowed).collect();
166        let includes = includes.into_iter().map(Cow::Borrowed).collect();
167
168        let excludes = excludes
169            .into_iter()
170            .filter_map(|exclusion| match exclusion {
171                Exclusion::Path(p) => Some(if p.is_absolute() {
172                    Exclusion::Path(p)
173                } else {
174                    workspace.join(p).canonicalize().ok().map(Cow::Owned).map(Exclusion::Path)?
175                }),
176                Exclusion::Pattern(pat) => Some(Exclusion::Pattern(pat)),
177            })
178            .collect();
179
180        let extensions = extensions.into_iter().map(Cow::Borrowed).collect();
181
182        Self {
183            workspace: Cow::Borrowed(workspace),
184            paths,
185            includes,
186            patches: Vec::new(),
187            excludes,
188            extensions,
189            glob: GlobSettings::default(),
190        }
191    }
192
193    #[inline]
194    #[must_use]
195    pub fn into_static(self) -> DatabaseConfiguration<'static> {
196        DatabaseConfiguration {
197            workspace: Cow::Owned(self.workspace.into_owned()),
198            paths: self.paths.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
199            includes: self.includes.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
200            patches: self.patches.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
201            excludes: self
202                .excludes
203                .into_iter()
204                .map(|e| match e {
205                    Exclusion::Path(p) => Exclusion::Path(Cow::Owned(p.into_owned())),
206                    Exclusion::Pattern(pat) => Exclusion::Pattern(Cow::Owned(pat.into_owned())),
207                })
208                .collect(),
209            extensions: self.extensions.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
210            glob: self.glob,
211        }
212    }
213}
214
215/// Mutable database for managing project files with add/update/delete operations.
216#[derive(Debug, Clone)]
217#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
218#[allow(clippy::field_scoped_visibility_modifiers)]
219pub struct Database<'config> {
220    files: HashMap<Cow<'static, [u8]>, Arc<File>>,
221    id_to_name: HashMap<FileId, Cow<'static, [u8]>>,
222    pub(crate) configuration: DatabaseConfiguration<'config>,
223}
224
225/// Immutable, read-optimized snapshot of the database.
226#[derive(Debug)]
227pub struct ReadDatabase {
228    files: Vec<Arc<File>>,
229    id_to_index: HashMap<FileId, usize>,
230    name_to_index: OnceLock<HashMap<Cow<'static, [u8]>, usize>>,
231    path_to_index: OnceLock<HashMap<PathBuf, usize>>,
232}
233
234impl<'config> Database<'config> {
235    #[inline]
236    #[must_use]
237    pub fn new(configuration: DatabaseConfiguration<'config>) -> Self {
238        Self { files: HashMap::default(), id_to_name: HashMap::default(), configuration }
239    }
240
241    #[inline]
242    #[must_use]
243    pub fn single(file: File, configuration: DatabaseConfiguration<'config>) -> Self {
244        let mut db = Self::new(configuration);
245        db.add(file);
246        db
247    }
248
249    /// Reserves capacity for at least `additional` more files.
250    #[inline]
251    pub fn reserve(&mut self, additional: usize) {
252        self.files.reserve(additional);
253        self.id_to_name.reserve(additional);
254    }
255
256    /// Adds files from a base database without replacing files already present in this database.
257    ///
258    /// This is useful when project files and a built-in prelude are loaded independently: project
259    /// files retain precedence while missing built-in files are moved into the project database.
260    #[inline]
261    pub fn merge_base(&mut self, base: Database<'_>) {
262        let Database { files, mut id_to_name, configuration: _ } = base;
263        self.reserve(files.len());
264
265        for (name, file) in files {
266            if self.files.contains_key(name.as_ref()) {
267                continue;
268            }
269
270            let id = file.id;
271            let id_name = id_to_name.remove(&id).unwrap_or_else(|| name.clone());
272            self.files.insert(name, file);
273            self.id_to_name.insert(id, id_name);
274        }
275    }
276
277    #[inline]
278    pub fn add(&mut self, file: File) -> FileId {
279        let name = file.name.clone();
280        let id = file.id;
281
282        if let Some(old_file) = self.files.insert(name.clone(), Arc::new(file)) {
283            self.id_to_name.remove(&old_file.id);
284        }
285
286        self.id_to_name.insert(id, name);
287
288        id
289    }
290
291    /// Updates a file's content using its stable `FileId`.
292    ///
293    /// This recalculates derived data like file size, line endings, and `FileRevision`.
294    /// If another `ReadDatabase` snapshot holds a reference to the file (preventing in-place
295    /// mutation), a new `Arc<File>` is created with the updated contents.
296    ///
297    /// Returns `true` if a file with the given ID was found and updated.
298    #[inline]
299    pub fn update(&mut self, id: FileId, new_contents: Cow<'static, [u8]>) -> bool {
300        let Some(name) = self.id_to_name.get(&id) else {
301            return false;
302        };
303
304        let Some(arc) = self.files.get_mut(name) else {
305            return false;
306        };
307
308        if let Some(file) = Arc::get_mut(arc) {
309            file.contents = new_contents;
310            file.size = file.contents.len() as u32;
311            file.lines = line_starts(file.contents.as_ref());
312        } else {
313            // other Arc clones exist (e.g., from a ReadDatabase snapshot).
314            // Create a new File with updated contents and replace the Arc.
315            let old = &**arc;
316            *arc = Arc::new(File::new(old.name.clone(), old.file_type, old.path.clone(), new_contents));
317        }
318
319        true
320    }
321
322    /// Deletes a file from the database using its stable `FileId`.
323    ///
324    /// Returns `true` if a file with the given ID was found and removed.
325    #[inline]
326    pub fn delete(&mut self, id: FileId) -> bool {
327        if let Some(name) = self.id_to_name.remove(&id) { self.files.remove(&name).is_some() } else { false }
328    }
329
330    /// Commits a [`ChangeLog`], applying all its recorded operations to the database
331    /// and optionally writing them to the filesystem.
332    ///
333    /// # Arguments
334    ///
335    /// * `change_log`: The log of changes to apply.
336    /// * `write_to_disk`: If `true`, changes for files that have a filesystem
337    ///   path will be written to disk in parallel.
338    ///
339    /// # Errors
340    ///
341    /// Returns a [`DatabaseError`] if the log cannot be consumed or if any
342    /// filesystem operation fails.
343    #[inline]
344    pub fn commit(&mut self, change_log: ChangeLog, write_to_disk: bool) -> Result<(), DatabaseError> {
345        let changes = change_log.into_inner()?;
346        let mut fs_operations = Vec::new();
347
348        for change in changes {
349            match change {
350                Change::Add(file) => {
351                    if write_to_disk && let Some(path) = &file.path {
352                        fs_operations.push(FilesystemOperation::Write(path.clone(), file.contents.clone()));
353                    }
354
355                    self.add(file);
356                }
357                Change::Update(id, contents) => {
358                    if write_to_disk
359                        && let Ok(file) = self.get(&id)
360                        && let Some(path) = &file.path
361                    {
362                        fs_operations.push(FilesystemOperation::Write(path.clone(), contents.clone()));
363                    }
364
365                    self.update(id, contents);
366                }
367                Change::Delete(id) => {
368                    if write_to_disk
369                        && let Ok(file) = self.get(&id)
370                        && let Some(path) = &file.path
371                    {
372                        fs_operations.push(FilesystemOperation::Delete(path.clone()));
373                    }
374
375                    self.delete(id);
376                }
377            }
378        }
379
380        if write_to_disk {
381            fs_operations.into_par_iter().try_for_each(|op| -> Result<(), DatabaseError> { op.execute() })?;
382        }
383
384        Ok(())
385    }
386
387    /// Creates an independent, immutable snapshot of the database.
388    ///
389    /// Shares file data and sorts it by ID. Name and path lookups build their indexes on first use.
390    /// The snapshot stays unchanged when the original database changes.
391    #[inline]
392    #[must_use]
393    pub fn read_only(&self) -> ReadDatabase {
394        let mut files_vec: Vec<Arc<File>> = self.files.values().cloned().collect();
395        files_vec.sort_unstable_by_key(|f| f.id);
396
397        let mut id_to_index = HashMap::with_capacity(files_vec.len());
398        for (index, file) in files_vec.iter().enumerate() {
399            id_to_index.insert(file.id, index);
400        }
401
402        ReadDatabase { files: files_vec, id_to_index, name_to_index: OnceLock::new(), path_to_index: OnceLock::new() }
403    }
404}
405
406impl ReadDatabase {
407    #[inline]
408    #[must_use]
409    pub fn empty() -> Self {
410        Self {
411            files: Vec::new(),
412            id_to_index: HashMap::new(),
413            name_to_index: OnceLock::new(),
414            path_to_index: OnceLock::new(),
415        }
416    }
417
418    /// Creates a new `ReadDatabase` containing only a single file.
419    ///
420    /// This is a convenience constructor for situations, such as testing or
421    /// single-file tools, where an operation requires a [`DatabaseReader`]
422    /// implementation but only needs to be aware of one file.
423    ///
424    /// # Arguments
425    ///
426    /// * `file`: The single `File` to include in the database.
427    #[inline]
428    #[must_use]
429    pub fn single(file: File) -> Self {
430        let mut id_to_index = HashMap::with_capacity(1);
431        id_to_index.insert(file.id, 0);
432
433        Self {
434            files: vec![Arc::new(file)],
435            id_to_index,
436            name_to_index: OnceLock::new(),
437            path_to_index: OnceLock::new(),
438        }
439    }
440
441    fn name_index(&self) -> &HashMap<Cow<'static, [u8]>, usize> {
442        self.name_to_index
443            .get_or_init(|| self.files.iter().enumerate().map(|(index, file)| (file.name.clone(), index)).collect())
444    }
445
446    fn path_index(&self) -> &HashMap<PathBuf, usize> {
447        self.path_to_index.get_or_init(|| {
448            self.files
449                .iter()
450                .enumerate()
451                .filter_map(|(index, file)| file.path.as_ref().map(|path| (path.clone(), index)))
452                .collect()
453        })
454    }
455}
456
457/// A universal interface for reading data from any database implementation.
458///
459/// This trait provides a common API for querying file data, abstracting over
460/// whether the underlying source is the mutable [`Database`] or the read-optimized
461/// [`ReadDatabase`]. This allows for writing generic code that can operate on either.
462pub trait DatabaseReader {
463    /// Retrieves a file's stable ID using its logical name.
464    fn get_id(&self, name: &[u8]) -> Option<FileId>;
465
466    /// Retrieves a reference to a file using its stable `FileId`.
467    ///
468    /// # Errors
469    ///
470    /// Returns `DatabaseError::FileNotFound` if no file with the given ID exists.
471    fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError>;
472
473    /// Retrieves a reference to a file using its stable `FileId`.
474    ///
475    /// # Errors
476    ///
477    /// Returns `DatabaseError::FileNotFound` if no file with the given ID exists.
478    fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError>;
479
480    /// Retrieves a reference to a file using its logical name.
481    ///
482    /// # Errors
483    ///
484    /// Returns `DatabaseError::FileNotFound` if no file with the given name exists.
485    fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError>;
486
487    /// Retrieves a reference to a file by its absolute filesystem path.
488    ///
489    /// # Errors
490    ///
491    /// Returns `DatabaseError::FileNotFound` if no file with the given path exists.
492    fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError>;
493
494    /// Returns an iterator over all files in the database.
495    ///
496    /// The order is not guaranteed for `Database`, but is sorted by `FileId`
497    /// for `ReadDatabase`, providing deterministic iteration.
498    fn files(&self) -> impl Iterator<Item = Arc<File>>;
499
500    /// Returns an iterator over all files of a specific `FileType`.
501    #[inline]
502    fn files_with_type(&self, file_type: FileType) -> impl Iterator<Item = Arc<File>> {
503        self.files().filter(move |file| file.file_type == file_type)
504    }
505
506    /// Returns an iterator over all files that do not match a specific `FileType`.
507    #[inline]
508    fn files_without_type(&self, file_type: FileType) -> impl Iterator<Item = Arc<File>> {
509        self.files().filter(move |file| file.file_type != file_type)
510    }
511
512    /// Returns an iterator over the stable IDs of all files in the database.
513    #[inline]
514    fn file_ids(&self) -> impl Iterator<Item = FileId> {
515        self.files().map(|file| file.id)
516    }
517
518    /// Returns an iterator over the stable IDs of all files of a specific `FileType`.
519    #[inline]
520    fn file_ids_with_type(&self, file_type: FileType) -> impl Iterator<Item = FileId> {
521        self.files_with_type(file_type).map(|file| file.id)
522    }
523
524    /// Returns an iterator over the stable IDs of all files that do not match a specific `FileType`.
525    #[inline]
526    fn file_ids_without_type(&self, file_type: FileType) -> impl Iterator<Item = FileId> {
527        self.files_without_type(file_type).map(|file| file.id)
528    }
529
530    /// Returns the total number of files in the database.
531    fn len(&self) -> usize;
532
533    /// Returns `true` if the database contains no files.
534    #[inline]
535    fn is_empty(&self) -> bool {
536        self.len() == 0
537    }
538}
539
540impl DatabaseReader for Database<'_> {
541    #[inline]
542    fn get_id(&self, name: &[u8]) -> Option<FileId> {
543        self.files.get(name).map(|f| f.id)
544    }
545
546    #[inline]
547    fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError> {
548        let name = self.id_to_name.get(id).ok_or(DatabaseError::FileNotFound)?;
549        let file = self.files.get(name).ok_or(DatabaseError::FileNotFound)?;
550
551        Ok(Arc::clone(file))
552    }
553
554    #[inline]
555    fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError> {
556        let name = self.id_to_name.get(id).ok_or(DatabaseError::FileNotFound)?;
557        self.files.get(name).map(std::convert::AsRef::as_ref).ok_or(DatabaseError::FileNotFound)
558    }
559
560    #[inline]
561    fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError> {
562        self.files.get(name).cloned().ok_or(DatabaseError::FileNotFound)
563    }
564
565    #[inline]
566    fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError> {
567        self.files.values().find(|file| file.path.as_deref() == Some(path)).cloned().ok_or(DatabaseError::FileNotFound)
568    }
569
570    #[inline]
571    fn files(&self) -> impl Iterator<Item = Arc<File>> {
572        self.files.values().cloned()
573    }
574
575    #[inline]
576    fn len(&self) -> usize {
577        self.files.len()
578    }
579}
580
581impl DatabaseReader for ReadDatabase {
582    #[inline]
583    fn get_id(&self, name: &[u8]) -> Option<FileId> {
584        self.name_index().get(name).and_then(|&i| self.files.get(i)).map(|f| f.id)
585    }
586
587    #[inline]
588    fn get(&self, id: &FileId) -> Result<Arc<File>, DatabaseError> {
589        let index = self.id_to_index.get(id).ok_or(DatabaseError::FileNotFound)?;
590
591        self.files.get(*index).cloned().ok_or(DatabaseError::FileNotFound)
592    }
593
594    #[inline]
595    fn get_ref(&self, id: &FileId) -> Result<&File, DatabaseError> {
596        let index = self.id_to_index.get(id).ok_or(DatabaseError::FileNotFound)?;
597
598        self.files.get(*index).map(std::convert::AsRef::as_ref).ok_or(DatabaseError::FileNotFound)
599    }
600
601    #[inline]
602    fn get_by_name(&self, name: &[u8]) -> Result<Arc<File>, DatabaseError> {
603        self.name_index().get(name).and_then(|&i| self.files.get(i)).cloned().ok_or(DatabaseError::FileNotFound)
604    }
605
606    #[inline]
607    fn get_by_path(&self, path: &Path) -> Result<Arc<File>, DatabaseError> {
608        self.path_index().get(path).and_then(|&i| self.files.get(i)).cloned().ok_or(DatabaseError::FileNotFound)
609    }
610
611    #[inline]
612    fn files(&self) -> impl Iterator<Item = Arc<File>> {
613        self.files.iter().cloned()
614    }
615
616    #[inline]
617    fn len(&self) -> usize {
618        self.files.len()
619    }
620}
621
622#[cfg(test)]
623#[allow(clippy::unwrap_used)]
624mod tests {
625    use super::*;
626
627    fn configuration() -> DatabaseConfiguration<'static> {
628        DatabaseConfiguration::new(Path::new("/"), vec![], vec![], vec![], vec![]).into_static()
629    }
630
631    #[test]
632    fn merge_base_adds_missing_files_without_replacing_project_files() {
633        let mut base = Database::new(configuration());
634        base.add(File::new(Cow::Borrowed(b"shared.php"), FileType::Builtin, None, Cow::Borrowed(b"base")));
635        base.add(File::new(Cow::Borrowed(b"builtin.php"), FileType::Builtin, None, Cow::Borrowed(b"builtin")));
636
637        let mut project = Database::new(configuration());
638        project.add(File::new(Cow::Borrowed(b"shared.php"), FileType::Host, None, Cow::Borrowed(b"project")));
639        project.add(File::new(Cow::Borrowed(b"project.php"), FileType::Host, None, Cow::Borrowed(b"project-only")));
640
641        project.merge_base(base);
642
643        assert_eq!(project.len(), 3);
644        let shared = project.get_by_name(b"shared.php").unwrap();
645        assert_eq!(shared.file_type, FileType::Host);
646        assert_eq!(shared.contents.as_ref(), b"project");
647
648        let builtin = project.get_by_name(b"builtin.php").unwrap();
649        assert_eq!(builtin.file_type, FileType::Builtin);
650        assert_eq!(project.get(&builtin.id).unwrap().name.as_ref(), b"builtin.php");
651    }
652}