Skip to main content

alpm_db/db/
schema.rs

1//! Schema handling for [alpm-db] database files.
2//!
3//! [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
4
5use std::{
6    fmt::{Display, Formatter},
7    fs::{File, write},
8    io::Read,
9    path::{Path, PathBuf},
10    str::FromStr,
11};
12
13use alpm_common::FileFormatSchema;
14use alpm_types::{SchemaVersion, semver_version::Version};
15use fluent_i18n::t;
16
17use crate::Error;
18
19/// The current major version supported by this library.
20const VERSION_9: u64 = 9;
21
22/// Describes supported schema versions of the ALPM databases.
23#[derive(Clone, Debug, Eq, PartialEq)]
24pub enum DbSchema {
25    /// Schema version 9 as introduced with pacman 4.2.0 on 2014-12-19.
26    V9(SchemaVersion),
27}
28
29impl DbSchema {
30    /// The name of the schema version file in an [alpm-db] database.
31    ///
32    /// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
33    pub const VERSION_FILE_NAME: &str = "ALPM_DB_VERSION";
34
35    /// Writes the schema version to the default version file in the database root `path`.
36    ///
37    /// # Errors
38    ///
39    /// Returns an error if the version file cannot be written.
40    pub(crate) fn write_version_file_to_db_root(
41        &self,
42        base_path: impl AsRef<Path>,
43    ) -> Result<(), Error> {
44        let base_path = base_path.as_ref();
45        let file = base_path.join(Self::VERSION_FILE_NAME);
46        write(&file, format!("{}\n", self.as_ref().as_ref().major)).map_err(|source| {
47            Error::IoPath {
48                path: file,
49                context: t!("error-io-path-write-db-version"),
50                source,
51            }
52        })
53    }
54}
55
56impl AsRef<SchemaVersion> for DbSchema {
57    fn as_ref(&self) -> &SchemaVersion {
58        match self {
59            Self::V9(v) => v,
60        }
61    }
62}
63
64impl Default for DbSchema {
65    /// Returns the latest supported schema version.
66    fn default() -> Self {
67        Self::V9(SchemaVersion::new(Version::new(VERSION_9, 0, 0)))
68    }
69}
70
71impl Display for DbSchema {
72    /// Formats the schema version as a string.
73    ///
74    /// Uses only the major version number of the underlying [`SchemaVersion`].
75    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
76        write!(
77            f,
78            "{}",
79            match self {
80                Self::V9(version) => version.as_ref().major,
81            }
82        )
83    }
84}
85
86impl FileFormatSchema for DbSchema {
87    type Err = Error;
88
89    /// Derives a [`DbSchema`] from a version file.
90    ///
91    /// Opens the `file` and defers to [`DbSchema::derive_from_reader`].
92    ///
93    /// # Errors
94    ///
95    /// Returns an error if:
96    ///
97    /// - the file cannot be opened for reading,
98    /// - or deriving a [`DbSchema`] from its contents fails.
99    fn derive_from_file(file: impl AsRef<Path>) -> Result<Self, Self::Err>
100    where
101        Self: Sized,
102    {
103        let file = file.as_ref();
104        let mut handle = File::open(file).map_err(|source| Error::IoPath {
105            path: PathBuf::from(file),
106            context: t!("error-io-path-open-read-only"),
107            source,
108        })?;
109        Self::derive_from_reader(&mut handle)
110    }
111
112    /// Derives a [`DbSchema`] from a reader.
113    ///
114    /// Reads the `reader` to a string and defers to [`DbSchema::derive_from_str`].
115    ///
116    /// # Errors
117    ///
118    /// Returns an error if:
119    ///
120    /// - reading from `reader` fails,
121    /// - or deriving a [`DbSchema`] from its contents fails.
122    fn derive_from_reader(mut reader: impl Read) -> Result<Self, Self::Err>
123    where
124        Self: Sized,
125    {
126        let mut buf = String::new();
127        reader
128            .read_to_string(&mut buf)
129            .map_err(|source| Error::Io {
130                context: t!("error-io-read-db-version"),
131                source,
132            })?;
133        Self::derive_from_str(buf.trim())
134    }
135
136    /// Derives a [`DbSchema`] from a string containing the schema version.
137    ///
138    /// # Errors
139    ///
140    /// Returns an error if deriving a [`DbSchema`] from the string fails.
141    fn derive_from_str(s: &str) -> Result<Self, Self::Err>
142    where
143        Self: Sized,
144    {
145        Self::from_str(s)
146    }
147}
148
149impl FromStr for DbSchema {
150    type Err = Error;
151
152    /// Parses a [`DbSchema`] from a string containing the schema version.
153    ///
154    /// # Errors
155    ///
156    /// Returns an error if deriving a [`DbSchema`] from the string fails.
157    fn from_str(s: &str) -> Result<Self, Self::Err> {
158        if s.is_empty() || s != VERSION_9.to_string() {
159            return Err(Error::UnsupportedSchemaVersion(s.to_string()));
160        }
161
162        Ok(Self::V9(SchemaVersion::new(Version::new(VERSION_9, 0, 0))))
163    }
164}
165
166impl TryFrom<SchemaVersion> for DbSchema {
167    type Error = Error;
168
169    /// Tries to convert a [`SchemaVersion`] into a [`DbSchema`].
170    ///
171    /// # Errors
172    ///
173    /// Returns an error if the given schema version is not supported.
174    fn try_from(value: SchemaVersion) -> Result<Self, Self::Error> {
175        match value.as_ref().major {
176            VERSION_9 => Ok(Self::V9(value)),
177            _ => Err(Error::UnsupportedSchemaVersion(value.to_string())),
178        }
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use std::{fs::write, io::Cursor, str::FromStr};
185
186    use tempfile::TempDir;
187    use testresult::TestResult;
188
189    use super::*;
190
191    /// Ensures, that [`DbSchema::from_str`] succeeds on a valid version string.
192    #[test]
193    fn db_schema_from_str_succeeds() -> TestResult {
194        assert_eq!(DbSchema::default(), DbSchema::from_str("9")?);
195        Ok(())
196    }
197
198    /// Ensures, that [`DbSchema::from_str`] fails on empty string.
199    #[test]
200    fn db_schema_from_str_fails_on_empty_string() {
201        let Err(Error::UnsupportedSchemaVersion(_)) = DbSchema::from_str("") else {
202            panic!("Expected to fail but succeeded instead");
203        };
204    }
205
206    /// Ensures, that [`DbSchema::from_str`] fails on an unsupported version string.
207    #[test]
208    fn db_schema_from_str_fails_on_unsupported_version() {
209        let Err(Error::UnsupportedSchemaVersion(_)) = DbSchema::from_str("8") else {
210            panic!("Expected to fail but succeeded instead");
211        };
212    }
213
214    /// Ensures, that [`DbSchema::derive_from_file`] succeeds on a valid version file.
215    #[test]
216    fn db_schema_derive_from_file() -> TestResult {
217        let test_dir = TempDir::new()?;
218        let version_file_path = test_dir.path().join(DbSchema::VERSION_FILE_NAME);
219        write(&version_file_path, "9\n")?;
220        let schema = DbSchema::derive_from_file(&version_file_path)?;
221        assert_eq!(DbSchema::default(), schema);
222        Ok(())
223    }
224
225    /// Ensures, that [`DbSchema::derive_from_reader`] succeeds on a [`Read`] impl with valid data.
226    #[test]
227    fn db_schema_derive_from_file_reader_succeeds() -> TestResult {
228        let schema = DbSchema::derive_from_reader(Cursor::new("9\n"))?;
229        assert_eq!(DbSchema::default(), schema);
230        Ok(())
231    }
232}