Skip to main content

alpm_db/db/
database.rs

1//! Management of the [alpm-db] directory structure.
2//!
3//! [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
4
5use std::{
6    fs::{create_dir_all, set_permissions, symlink_metadata},
7    os::unix::fs::{MetadataExt, PermissionsExt, chown},
8    path::{Path, PathBuf},
9};
10
11use alpm_common::FileFormatSchema;
12use alpm_mtree::Mtree;
13use alpm_types::InstalledPackage;
14use fluent_i18n::t;
15use log::{debug, trace, warn};
16use nix::unistd::{getegid, geteuid};
17
18use crate::{
19    db::{Action, DIR_MODE, DbSchema, Entry, Error, Transaction, permissions_world_writable},
20    desc::DbDescFile,
21    files::DbFiles,
22};
23
24/// A configuration for transactions and the various locations that they rely on.
25#[derive(Clone, Debug)]
26pub struct DatabaseConfig {
27    /// The path to the alpm-db root directory.
28    database_dir: PathBuf,
29
30    /// The path of the lock file for the transaction/database.
31    lock_file: PathBuf,
32
33    /// The data directory for current and past transactions.
34    ///
35    /// Below this directory the following data is kept:
36    ///
37    /// - current transaction plan
38    /// - past transaction plans
39    /// - temporary data for current transaction plan
40    transaction_data_dir: PathBuf,
41}
42
43impl DatabaseConfig {
44    /// The default pacman database location.
45    pub const PACMAN_DATABASE_DIR: &str = "/var/lib/pacman/local";
46
47    /// The default pacman database lock file location.
48    pub const PACMAN_DATABASE_LOCK_FILE: &str = "/var/lib/pacman/db.lck";
49
50    /// The default location for transaction plans and temporary data for transactions.
51    pub const TRANSACTION_DATA_DIR: &str = "/var/lib/alpm/alpm-db";
52
53    /// Creates a new [`DatabaseConfig`].
54    pub fn new(
55        database_dir: PathBuf,
56        lock_file: PathBuf,
57        transaction_data_dir: PathBuf,
58    ) -> Result<Self, crate::Error> {
59        Ok(Self {
60            database_dir,
61            lock_file,
62            transaction_data_dir,
63        })
64    }
65
66    /// Returns the path of the database directory.
67    pub fn database_dir(&self) -> &Path {
68        &self.database_dir
69    }
70
71    /// Returns the path of the lock file.
72    pub fn lock_file(&self) -> &Path {
73        &self.lock_file
74    }
75
76    /// Returns the path of the transaction data directory.
77    pub fn transaction_data_dir(&self) -> &Path {
78        &self.transaction_data_dir
79    }
80
81    /// Fails if the `lock_file` path of [`Self`] exists.
82    ///
83    /// # Errors
84    ///
85    /// Returns an error, if `self.lock_file` exists.
86    fn fail_if_lock_exists(&self) -> Result<(), crate::Error> {
87        if self.lock_file.exists() {
88            return Err(Error::DatabaseIsLocked {
89                path: self.database_dir.clone(),
90                lock_file: self.lock_file.clone(),
91            }
92            .into());
93        }
94
95        Ok(())
96    }
97}
98
99impl Default for DatabaseConfig {
100    /// Returns a default [`DatabaseConfig`].
101    ///
102    /// Uses [`Self::PACMAN_DATABASE_DIR`] database directory, [`Self::PACMAN_DATABASE_LOCK_FILE`]
103    /// as lock file location and [`Self::TRANSACTION_DATA_DIR`] as transaction data directory.
104    fn default() -> Self {
105        Self {
106            database_dir: PathBuf::from(Self::PACMAN_DATABASE_DIR),
107            lock_file: PathBuf::from(Self::PACMAN_DATABASE_LOCK_FILE),
108            transaction_data_dir: PathBuf::from(Self::TRANSACTION_DATA_DIR),
109        }
110    }
111}
112
113/// The representation of an [alpm-db].
114///
115/// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
116#[derive(Debug)]
117pub struct Database {
118    /// The configuration for the interaction with this database.
119    config: DatabaseConfig,
120
121    /// The schema of the database.
122    ///
123    /// See [`DbSchema`] variants for available schema versions.
124    schema: DbSchema,
125
126    /// All available entries, serving as the the view onto the database's state.
127    entries: Vec<Entry>,
128
129    /// A single, optional transaction for write operations.
130    transaction: Option<Transaction>,
131}
132
133impl Database {
134    /// Creates a new [`Database`], accessing an existing [alpm-db].
135    ///
136    /// Relies on a [`DatabaseConfig`] for relevant paths to the database root directory, lock file
137    /// location and transaction data directory.
138    ///
139    /// # Note
140    ///
141    /// This reads each [`Entry`] available in the database.
142    /// References to the entries can later be retrieved using [`Self::entries`].
143    ///
144    /// # Errors
145    ///
146    /// Returns an error, if
147    ///
148    /// - the database directory cannot be canonicalized
149    /// - the write lock configured in the `config` already exists
150    /// - the metadata for the database directory cannot be retrieved
151    /// - the database directory is not a directory
152    /// - the database schema cannot be read
153    /// - an [`Entry`] in the database is not valid
154    ///
155    /// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
156    pub fn open(mut config: DatabaseConfig) -> Result<Self, crate::Error> {
157        debug!("Open alpm-db: {:?}", config.database_dir);
158
159        let config = {
160            let path =
161                config
162                    .database_dir
163                    .canonicalize()
164                    .map_err(|source| crate::Error::IoPath {
165                        path: config.database_dir.clone(),
166                        context: t!("error-io-path-db-base-canonicalize"),
167                        source,
168                    })?;
169            config.database_dir = path;
170            config
171        };
172
173        config.fail_if_lock_exists()?;
174
175        // Fail, if the targeted path is not a directory.
176        let metadata =
177            symlink_metadata(&config.database_dir).map_err(|source| crate::Error::IoPath {
178                path: config.database_dir.clone(),
179                context: t!("error-io-path-metadata"),
180                source,
181            })?;
182        if !metadata.is_dir() {
183            return Err(Error::DatabaseIsNotADirectory {
184                path: config.database_dir.clone(),
185            }
186            .into());
187        }
188
189        // Emit a warning if the directory is world-writable.
190        if permissions_world_writable(metadata.permissions().mode()) {
191            warn!(
192                "{}",
193                t!("warn-database-root-world-writable", { "path" => config.database_dir.display().to_string() })
194            );
195        }
196
197        let schema =
198            DbSchema::derive_from_file(config.database_dir.join(DbSchema::VERSION_FILE_NAME))?;
199
200        let database = {
201            let mut database = Self {
202                config,
203                schema,
204                entries: Vec::new(),
205                transaction: None,
206            };
207
208            for path in database.paths()? {
209                database.entries.push(Entry::new(path)?)
210            }
211
212            database
213        };
214
215        Ok(database)
216    }
217
218    /// Creates a new [`Database`] by creating a new, empty [alpm-db] structure.
219    ///
220    /// Relies on a [`DatabaseConfig`] for relevant paths to the database root directory, lock file
221    /// location and transaction data directory.
222    ///
223    /// # Note
224    ///
225    /// If the targeted database root directory exists already, it must be empty!
226    ///
227    /// # Errors
228    ///
229    /// Returns an error, if
230    ///
231    /// - the database root directory exists, but
232    ///   - it cannot be canonicalized
233    ///   - it is not a directory
234    ///   - it is not empty
235    ///   - permissions for it cannot be adjusted
236    /// - the database root directory does not exist yet and
237    ///   - the directory or any of its parents cannot be created
238    /// - setting the default file permissions for the newly created directory fails
239    /// - writing the database version file fails
240    ///
241    /// [alpm-db]: https://alpm.archlinux.page/specifications/alpm-db.7.html
242    pub fn create(mut config: DatabaseConfig, schema: DbSchema) -> Result<Self, crate::Error> {
243        debug!(
244            "Create new alpm-db with schema {}: {:?}",
245            schema, config.database_dir
246        );
247
248        let path = if config.database_dir.exists() {
249            // If the path exists already, canonicalize it and ensure, that it is valid.
250            // The path must be an empty directory with default permissions, owned by the
251            // UID/GID of the calling process.
252
253            let path =
254                config
255                    .database_dir
256                    .canonicalize()
257                    .map_err(|source| crate::Error::IoPath {
258                        path: config.database_dir,
259                        context: t!("error-io-path-db-base-canonicalize"),
260                        source,
261                    })?;
262
263            // Fail, if the targeted path is not a directory.
264            if !&path.is_dir() {
265                return Err(Error::DatabaseIsNotADirectory { path }.into());
266            }
267
268            // Fail, if the targeted directory exists and is not empty.
269            if path
270                .read_dir()
271                .map_err(|source| crate::Error::IoPath {
272                    path: path.clone(),
273                    context: t!("error-io-database-read-dir"),
274                    source,
275                })?
276                .count()
277                != 0
278            {
279                return Err(Error::DatabaseCreationNotEmpty { path }.into());
280            }
281
282            let euid = geteuid().as_raw();
283            let egid = getegid().as_raw();
284            let metadata = path
285                .symlink_metadata()
286                .map_err(|source| crate::Error::IoPath {
287                    path: path.clone(),
288                    context: t!("error-io-path-metadata"),
289                    source,
290                })?;
291
292            // Change ownership if it doesn't match the calling UID/GID.
293            if !(metadata.uid() == euid && metadata.gid() == egid) {
294                chown(&path, Some(euid), Some(egid)).map_err(|source| crate::Error::IoPath {
295                    path: path.clone(),
296                    context: t!("error-io-path-chown"),
297                    source,
298                })?;
299            }
300
301            // Change permissions if they don't match the defaults.
302            if metadata.permissions().mode() != DIR_MODE {
303                set_permissions(&path, PermissionsExt::from_mode(DIR_MODE)).map_err(|source| {
304                    crate::Error::IoPath {
305                        path: path.clone(),
306                        context: t!("error-io-path-db-base-create"),
307                        source,
308                    }
309                })?;
310            }
311
312            path
313        } else {
314            // If the path does not yet exist, create it, canonicalize it and set default
315            // permissions.
316
317            create_dir_all(&config.database_dir).map_err(|source| crate::Error::IoPath {
318                path: config.database_dir.clone(),
319                context: t!("error-io-path-db-base-create"),
320                source,
321            })?;
322            let path =
323                config
324                    .database_dir
325                    .canonicalize()
326                    .map_err(|source| crate::Error::IoPath {
327                        path: config.database_dir,
328                        context: t!("error-io-path-db-base-canonicalize"),
329                        source,
330                    })?;
331
332            set_permissions(&path, PermissionsExt::from_mode(DIR_MODE)).map_err(|source| {
333                crate::Error::IoPath {
334                    path: path.clone(),
335                    context: t!("error-io-path-db-base-create"),
336                    source,
337                }
338            })?;
339
340            path
341        };
342
343        config.database_dir = path;
344
345        schema.write_version_file_to_db_root(&config.database_dir)?;
346
347        Ok(Self {
348            config,
349            schema,
350            entries: Vec::new(),
351            transaction: None,
352        })
353    }
354
355    /// Returns a reference to the path of the database root directory.
356    pub fn path(&self) -> &Path {
357        &self.config.database_dir
358    }
359
360    /// Returns a reference to the [`DbSchema`] of the database.
361    pub fn schema(&self) -> &DbSchema {
362        &self.schema
363    }
364
365    /// Initializes a transaction for this database.
366    ///
367    /// Transactions are required for adding and removing entries.
368    /// After initializing a transaction, actions can be added to it with [`Self::add_action`].
369    /// Finally, the transaction can be committed using [`Self::commit_transaction`].
370    ///
371    /// Several steps are taken upon initialization of a transaction:
372    ///
373    /// - the write lock for the database is created
374    /// - the transaction is created, which in turn ensures that the transaction data directory is
375    ///   created and can be used
376    ///
377    /// # Warning
378    ///
379    /// This functionality is still considered **experimental**.
380    /// Use at your own risk!
381    ///
382    /// # Errors
383    ///
384    /// Returns an error, if
385    ///
386    /// - a lock (file) exists in the location configured by the [`DatabaseConfig`]
387    /// - the database already has a transaction
388    /// - the write lock file cannot be created
389    /// - the transaction data directory cannot be created
390    pub fn init_transaction(&mut self) -> Result<(), crate::Error> {
391        if let Some(transaction) = self.transaction.as_ref() {
392            return Err(Error::DatabaseHasLockedTransactionAlready {
393                path: self.config.database_dir.clone(),
394                lock_file: self.config.lock_file.to_path_buf(),
395                uuid: *transaction.uuid(),
396            }
397            .into());
398        }
399
400        let transaction = Transaction::new(&self.config)?;
401        // The transaction creation canonicalizes the data dir and lock file paths.
402        self.config.transaction_data_dir = transaction.data_dir().to_path_buf();
403        self.config.lock_file = transaction.lock_file().to_path_buf();
404        self.transaction = Some(transaction);
405
406        Ok(())
407    }
408
409    /// Adds an [`Action`] to the current transaction of the [`Database`].
410    ///
411    /// # Warning
412    ///
413    /// This functionality is still considered **experimental**.
414    /// Use at your own risk!
415    ///
416    /// # Errors
417    ///
418    /// Returns an error, if
419    ///
420    /// - the database is locked but has no transaction
421    /// - the database has a transaction but no lock
422    /// - the database has no transaction
423    pub fn add_action(&mut self, action: Action) -> Result<(), crate::Error> {
424        debug!("Add action: {action}");
425
426        let Some(transaction) = self.transaction.as_mut() else {
427            return Err(Error::DatabaseHasNoTransaction {
428                path: self.config.database_dir.to_path_buf(),
429            }
430            .into());
431        };
432
433        transaction.add_action(action);
434
435        Ok(())
436    }
437
438    /// Commits a transaction against the data of this database and consumes `Self`.
439    ///
440    /// Committing a transaction entails several steps:
441    ///
442    /// - creating a plan for the transaction and persisting it in the directory for current
443    ///   transactions
444    /// - creation of a temporary directory for the transaction
445    /// - collection of the data of all additions in the temporary directory
446    /// - removal of all entries marked for removal from the [alpm-db]
447    /// - move/copy of all additions from the temporary directory to the [alpm-db]
448    /// - removal of the temporary directory
449    /// - moving the transaction plan from the directory for current transactions to that for past
450    ///   ones
451    /// - removing the write lock for the database
452    ///
453    /// # Warning
454    ///
455    /// This functionality is still considered **experimental**.
456    /// Use at your own risk!
457    ///
458    /// # Note
459    ///
460    /// This method returns early (and removes the lock file), if the transaction describes no
461    /// operations.
462    ///
463    /// # Errors
464    ///
465    /// Returns an error, if
466    ///
467    /// - the database is locked but has no transaction
468    /// - the database has a transaction but is not locked
469    /// - the database has no transaction
470    /// - committing one of the action items of the transaction fails
471    pub fn commit_transaction(mut self) -> Result<(), crate::Error> {
472        let Some(transaction) = self.transaction.take() else {
473            return Err(Error::DatabaseHasNoTransaction {
474                path: self.config.database_dir.to_path_buf(),
475            }
476            .into());
477        };
478
479        // Commit the data changes.
480        transaction.commit()?;
481
482        Ok(())
483    }
484
485    /// Returns the sorted list of all directory paths in the [`Database`].
486    ///
487    /// # Errors
488    ///
489    /// Returns an error, if
490    ///
491    /// - an entry of the alpm-db cannot be read
492    /// - the metadata of an entry in the alpm-db cannot be retrieved
493    fn paths(&self) -> Result<Vec<PathBuf>, crate::Error> {
494        debug!(
495            "Collect the list of directory paths in the alpm-db: {:?}",
496            self.config.database_dir
497        );
498
499        let mut paths = Vec::new();
500        for entry in self
501            .config
502            .database_dir
503            .read_dir()
504            .map_err(|source| crate::Error::IoPath {
505                path: self.config.database_dir.clone(),
506                context: t!("error-io-database-read-dir"),
507                source,
508            })?
509        {
510            let dir_entry = entry.map_err(|source| crate::Error::IoPath {
511                path: self.config.database_dir.clone(),
512                context: t!("error-io-database-read-dir-entry"),
513                source,
514            })?;
515
516            // Ignore non-directory paths.
517            let metadata = dir_entry
518                .metadata()
519                .map_err(|source| crate::Error::IoPath {
520                    path: self.config.database_dir.clone(),
521                    context: t!("error-io-path-metadata"),
522                    source,
523                })?;
524            if !metadata.is_dir() {
525                trace!("Skip non-directory path in alpm-db: {:?}", dir_entry.path());
526                continue;
527            }
528
529            paths.push(dir_entry.path());
530        }
531        paths.sort();
532
533        Ok(paths)
534    }
535
536    /// Returns a reference to the sorted list of each [`Entry`] in the database.
537    pub fn entries(&self) -> &[Entry] {
538        self.entries.as_slice()
539    }
540
541    /// Returns the list of all [`DbDescFile`]s found in the database.
542    ///
543    /// # Errors
544    ///
545    /// Returns an error, if reading the [alpm-db-desc] component of an entry fails (see
546    /// [`Entry::db_desc`]).
547    ///
548    /// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
549    pub fn db_descs(&mut self) -> Result<Vec<DbDescFile>, crate::Error> {
550        let mut output = Vec::new();
551        for entry in self.entries.iter_mut() {
552            let data = entry.db_desc()?;
553            output.push(data);
554        }
555
556        Ok(output)
557    }
558
559    /// Returns the list of all [`DbFiles`] found in the database.
560    ///
561    /// # Errors
562    ///
563    /// Returns an error, if reading the [alpm-db-files] component of an entry fails (see
564    /// [`Entry::db_files`]).
565    ///
566    /// [alpm-db-files]: https://alpm.archlinux.page/specifications/alpm-db-files.5.html
567    pub fn db_files(&mut self) -> Result<Vec<DbFiles>, crate::Error> {
568        let mut output = Vec::new();
569        for entry in self.entries.iter_mut() {
570            let data = entry.db_files()?;
571            output.push(data);
572        }
573
574        Ok(output)
575    }
576
577    /// Returns the list of all [`Mtree`] found in the database.
578    ///
579    /// # Errors
580    ///
581    /// Returns an error, if reading the [ALPM-MTREE] component of an entry fails (see
582    /// [`Entry::mtree`]).
583    ///
584    /// [ALPM-MTREE]: https://alpm.archlinux.page/specifications/ALPM-MTREE.5.html
585    pub fn mtrees(&mut self) -> Result<Vec<Mtree>, crate::Error> {
586        let mut output = Vec::new();
587        for entry in self.entries.iter_mut() {
588            let data = entry.mtree()?;
589            output.push(data);
590        }
591
592        Ok(output)
593    }
594
595    /// Returns the list of all installed packages.
596    ///
597    /// # Errors
598    ///
599    /// Returns an error, if reading the [alpm-db-desc] component of an entry fails (see
600    /// [`Entry::db_desc`]).
601    ///
602    /// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
603    pub fn installed_packages(&mut self) -> Result<Vec<InstalledPackage>, crate::Error> {
604        let mut output = Vec::new();
605        for entry in self.entries.iter_mut() {
606            let data = entry.db_desc()?;
607            output.push(data.installed_package());
608        }
609
610        Ok(output)
611    }
612}
613
614#[cfg(test)]
615mod tests {
616    use std::fs::File;
617
618    use log::LevelFilter;
619    use simplelog::{ColorChoice, Config, TermLogger, TerminalMode};
620    use tempfile::TempDir;
621    use testresult::TestResult;
622
623    use super::*;
624
625    /// Initialize a logger that shows trace messages on stderr.
626    fn init_logger() {
627        if TermLogger::init(
628            LevelFilter::Trace,
629            Config::default(),
630            TerminalMode::Stderr,
631            ColorChoice::Auto,
632        )
633        .is_err()
634        {
635            debug!("Not initializing another logger, as one is initialized already.");
636        }
637    }
638
639    /// Ensures, that [`Database::create`] succeeds on a new directory.
640    #[test]
641    fn database_create_succeeds_with_new_dir() -> TestResult {
642        init_logger();
643        let temp_dir = TempDir::new()?;
644        let temp_path = temp_dir.path();
645        let database_dir = temp_path.join("db/local");
646        let lock_file = temp_path.join("db/db.lck");
647        let transaction_data_dir = temp_path.join("alpm-db");
648        let database_config =
649            DatabaseConfig::new(database_dir.clone(), lock_file, transaction_data_dir)?;
650
651        let database = Database::create(database_config, DbSchema::default())?;
652
653        let entries = database.entries();
654        assert!(entries.is_empty());
655        let database_metadata = database_dir.symlink_metadata()?;
656        assert_eq!(database_metadata.permissions().mode(), DIR_MODE);
657
658        Ok(())
659    }
660
661    /// Ensures, that [`Database::create`] succeeds on an existing, empty directory.
662    #[test]
663    fn database_create_succeeds_with_empty_dir() -> TestResult {
664        init_logger();
665        let temp_dir = TempDir::new()?;
666        let temp_path = temp_dir.path();
667        let database_dir = temp_path.join("db/local");
668        let lock_file = temp_path.join("db/db.lck");
669        let transaction_data_dir = temp_path.join("alpm-db");
670        let database_config =
671            DatabaseConfig::new(database_dir.clone(), lock_file, transaction_data_dir)?;
672
673        create_dir_all(&database_dir)?;
674        set_permissions(&database_dir, PermissionsExt::from_mode(0o777))?;
675
676        let database = Database::create(database_config, DbSchema::default())?;
677
678        let entries = database.entries();
679        assert!(entries.is_empty());
680        let database_metadata = database_dir.symlink_metadata()?;
681        assert_eq!(database_metadata.permissions().mode(), DIR_MODE);
682
683        Ok(())
684    }
685
686    /// Ensures, that [`Database::new`] succeeds to open an existing, empty database.
687    #[test]
688    fn database_new_succeeds_with_empty_database() -> TestResult {
689        init_logger();
690        let temp_dir = TempDir::new()?;
691        let temp_path = temp_dir.path();
692        let database_dir = temp_path.join("db/local");
693        let lock_file = temp_path.join("db/db.lck");
694        let transaction_data_dir = temp_path.join("alpm-db");
695        let database_config =
696            DatabaseConfig::new(database_dir.clone(), lock_file, transaction_data_dir)?;
697
698        create_dir_all(&database_dir)?;
699        let schema = DbSchema::default();
700        schema.write_version_file_to_db_root(&database_dir)?;
701
702        let database = Database::open(database_config)?;
703
704        let entries = database.entries();
705        assert!(entries.is_empty());
706        let database_metadata = database_dir.symlink_metadata()?;
707        assert_eq!(database_metadata.permissions().mode(), DIR_MODE);
708
709        Ok(())
710    }
711
712    /// Ensures, that [`Database::create`] fails on target dir being a file.
713    #[test]
714    fn database_create_fails_on_file_as_base_dir() -> TestResult {
715        init_logger();
716        let temp_dir = TempDir::new()?;
717        let temp_path = temp_dir.path();
718        let database_dir = temp_path.join("db/local");
719        let lock_file = temp_path.join("db/db.lck");
720        let transaction_data_dir = temp_path.join("alpm-db");
721        let database_config =
722            DatabaseConfig::new(database_dir.clone(), lock_file, transaction_data_dir)?;
723
724        create_dir_all(temp_path.join("db"))?;
725        File::create(&database_dir)?;
726
727        let Err(error) = Database::create(database_config, DbSchema::default()) else {
728            panic!("Expected to fail with Error::DatabaseCreationNotEmpty");
729        };
730
731        debug!("{error}");
732        assert!(matches!(
733            error,
734            crate::Error::Database(Error::DatabaseIsNotADirectory { .. })
735        ));
736
737        Ok(())
738    }
739
740    /// Ensures, that [`Database::create`] fails on an existing, non-empty directory.
741    #[test]
742    fn database_create_fails_with_non_empty_dir() -> TestResult {
743        init_logger();
744        let temp_dir = TempDir::new()?;
745        let temp_path = temp_dir.path();
746        let database_dir = temp_path.join("db/local");
747        let lock_file = temp_path.join("db/db.lck");
748        let transaction_data_dir = temp_path.join("alpm-db");
749        let database_config =
750            DatabaseConfig::new(database_dir.clone(), lock_file, transaction_data_dir)?;
751
752        create_dir_all(database_dir.join("example-1.0.0-1"))?;
753
754        let Err(error) = Database::create(database_config, DbSchema::default()) else {
755            panic!("Expected to fail with Error::DatabaseCreationNotEmpty");
756        };
757
758        debug!("{error}");
759        assert!(matches!(
760            error,
761            crate::Error::Database(Error::DatabaseCreationNotEmpty { .. })
762        ));
763
764        Ok(())
765    }
766
767    /// Ensures, that [`Database::new`] fails on non-directory path.
768    #[test]
769    fn database_new_fails_on_not_a_directory() -> TestResult {
770        init_logger();
771        let temp_dir = TempDir::new()?;
772        let temp_path = temp_dir.path();
773        let database_dir = temp_path.join("db/local");
774        let lock_file = temp_path.join("db/db.lck");
775        let transaction_data_dir = temp_path.join("alpm-db");
776        let database_config =
777            DatabaseConfig::new(database_dir.clone(), lock_file, transaction_data_dir)?;
778
779        create_dir_all(temp_path.join("db"))?;
780        File::create_new(&database_dir)?;
781
782        let Err(error) = Database::open(database_config) else {
783            panic!("Expected to fail with Error::DatabaseIsNotADirectory");
784        };
785
786        debug!("{error}");
787        assert!(matches!(
788            error,
789            crate::Error::Database(Error::DatabaseIsNotADirectory { .. })
790        ));
791
792        Ok(())
793    }
794
795    /// Ensures, that [`Database::new`] fails, if a write lock exists in a default location.
796    #[test]
797    fn database_new_fails_on_default_write_lock() -> TestResult {
798        init_logger();
799        let temp_dir = TempDir::new()?;
800        let temp_path = temp_dir.path();
801        let database_dir = temp_path.join("db/local");
802        let lock_file = temp_path.join("db/db.lck");
803        let transaction_data_dir = temp_path.join("alpm-db");
804        let database_config = DatabaseConfig::new(
805            database_dir.clone(),
806            lock_file.clone(),
807            transaction_data_dir,
808        )?;
809
810        create_dir_all(&database_dir)?;
811        let schema = DbSchema::default();
812        schema.write_version_file_to_db_root(&database_dir)?;
813        File::create_new(&lock_file)?;
814
815        let Err(error) = Database::open(database_config) else {
816            panic!("Expected to fail with Error::DatabaseIsLocked");
817        };
818
819        debug!("{error}");
820        assert!(matches!(
821            error,
822            crate::Error::Database(Error::DatabaseIsLocked { .. })
823        ));
824
825        Ok(())
826    }
827
828    /// Tests with transactions.
829    mod transactions {
830
831        use std::{io::Write, str::FromStr};
832
833        use alpm_common::MetadataFile;
834        use alpm_mtree::mtree::MtreeTransfer;
835        use alpm_types::{
836            Architecture,
837            EntryName,
838            ExtraData,
839            ExtraDataEntry,
840            PackageInstallReason,
841            PackageValidation,
842            RelativeFilePath,
843            SystemArchitecture,
844        };
845        use flate2::{Compression, GzBuilder};
846
847        use super::*;
848        use crate::{
849            db::{Action, EntrySource},
850            desc::DbDescFileV2,
851            files::{BackupEntry, DbFilesV1},
852        };
853
854        /// Returns an example [`DbDescFile`].
855        fn db_desc_file() -> Result<DbDescFile, crate::Error> {
856            Ok(DbDescFile::V2(DbDescFileV2 {
857                name: "example".parse()?,
858                version: "1.0.0-1".parse()?,
859                base: "example".parse()?,
860                description: "An example package".into(),
861                url: Some("https://example.org".parse()?),
862                arch: Architecture::Some(SystemArchitecture::X86_64),
863                builddate: 1,
864                installdate: 2,
865                packager: "Foobar McFooface <foobar@mcfooface.org>".parse()?,
866                size: 10,
867                groups: Vec::new(),
868                reason: PackageInstallReason::Explicit,
869                license: vec!["0BSD".parse()?],
870                validation: vec![PackageValidation::None],
871                replaces: Vec::new(),
872                depends: Vec::new(),
873                optdepends: Vec::new(),
874                conflicts: Vec::new(),
875                provides: Vec::new(),
876                xdata: ExtraData::try_from(ExtraDataEntry::new(
877                    "pkgtype".to_string(),
878                    "pkg".to_string(),
879                ))?,
880            }))
881        }
882
883        /// Returns an example [`DbFiles`].
884        fn db_files_file() -> Result<DbFiles, crate::Error> {
885            Ok(DbFiles::V1(DbFilesV1::try_from((
886                vec![
887                    PathBuf::from("etc/"),
888                    PathBuf::from("etc/example"),
889                    PathBuf::from("etc/example/conf"),
890                    PathBuf::from("usr"),
891                    PathBuf::from("usr/bin"),
892                    PathBuf::from("usr/bin/foo"),
893                ],
894                vec![BackupEntry {
895                    path: RelativeFilePath::new(PathBuf::from("etc/example/conf"))?,
896                    md5: "d3b07384d113edec49eaa6238ad5ff00".parse()?,
897                }],
898            ))?))
899        }
900
901        /// Returns an example [`MtreeTransfer`].
902        fn mtree_transfer() -> Result<MtreeTransfer, crate::Error> {
903            let data = {
904                let data = r#"#mtree
905/set mode=644 uid=0 gid=0 type=file
906./etc mode=755 type=dir time=1700000000.0
907./etc/example mode=755 type=dir time=1700000000.0
908./etc/example/conf time=1700000000.0 size=1337 sha256digest=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
909./some_dir type=dir time=1700000000.0
910./usr mode=755 type=dir time=1700000000.0
911./usr/bin mode=755 type=dir time=1700000000.0
912./usr/bin/foo time=1700000000.0 size=1337 sha256digest=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
913"#.to_string();
914
915                let mut gzip = GzBuilder::new()
916                    .filename("mtree")
917                    .write(Vec::new(), Compression::default());
918                gzip.write_all(&data.into_bytes())
919                    .map_err(|source| crate::Error::Io {
920                        context: "writing data to a gzip encoder".to_string(),
921                        source,
922                    })?;
923                gzip.finish().map_err(|source| crate::Error::Io {
924                    context: "retrieving gzip compressed data".to_string(),
925                    source,
926                })?
927            };
928
929            Ok(MtreeTransfer::from_reader_with_schema(
930                data.as_slice(),
931                None,
932            )?)
933        }
934
935        /// A single example transaction data.
936        #[derive(Debug)]
937        struct ExampleTransactionData {
938            entry_name: EntryName,
939        }
940
941        impl EntrySource for ExampleTransactionData {
942            fn entry_name(&self) -> EntryName {
943                self.entry_name.clone()
944            }
945
946            fn alpm_db_desc(&self) -> Result<DbDescFile, crate::Error> {
947                db_desc_file()
948            }
949
950            fn alpm_db_files(&self) -> Result<DbFiles, crate::Error> {
951                db_files_file()
952            }
953
954            fn alpm_mtree(&self) -> Result<MtreeTransfer, crate::Error> {
955                mtree_transfer()
956            }
957
958            fn alpm_install_scriptlet(&self) -> Result<Option<String>, crate::Error> {
959                let script = r#"!/usr/bin/env bash
960
961post_install() {
962    printf 'YOLO\n'
963}
964"#;
965                Ok(Some(script.to_string()))
966            }
967        }
968
969        /// Ensures, that [`Database::commit_transaction`] succeeds to write an example entry to a
970        /// newly created database.
971        #[test]
972        fn database_commit_transaction_succeeds() -> TestResult {
973            init_logger();
974            let temp_dir = TempDir::new()?;
975            let temp_path = temp_dir.path();
976            let database_dir = temp_path.join("db/local");
977            let lock_file = temp_path.join("db/db.lck");
978            let transaction_data_dir = temp_path.join("alpm-db");
979            let database_config = DatabaseConfig::new(
980                database_dir.clone(),
981                lock_file.clone(),
982                transaction_data_dir.clone(),
983            )?;
984
985            // Creates a new, empty database.
986            let mut database = Database::create(database_config, DbSchema::default())?;
987            let entries = database.entries();
988            assert!(entries.is_empty());
989
990            // Executes example transaction to add a single entry.
991            database.init_transaction()?;
992            assert!(lock_file.exists());
993            database.add_action(Action::Add(Box::new(ExampleTransactionData {
994                entry_name: "example-1.0.0-1".parse()?,
995            })))?;
996            database.commit_transaction()?;
997            assert!(!lock_file.exists());
998
999            let database_config = DatabaseConfig::new(
1000                database_dir.clone(),
1001                lock_file.clone(),
1002                transaction_data_dir.clone(),
1003            )?;
1004            let mut database = Database::open(database_config)?;
1005            let entries = database.entries();
1006            assert_eq!(entries.len(), 1);
1007            let entries = database.db_descs()?;
1008            assert_eq!(entries.len(), 1);
1009            let entries = database.db_files()?;
1010            assert_eq!(entries.len(), 1);
1011            let entries = database.installed_packages()?;
1012            assert_eq!(
1013                entries.first(),
1014                Some(&InstalledPackage::from_str("example-1.0.0-1-x86_64")?)
1015            );
1016            let entries = database.mtrees()?;
1017            assert_eq!(entries.len(), 1);
1018
1019            Ok(())
1020        }
1021    }
1022}