diesel_migrations-2.0.0/.cargo_vcs_info.json0000644000000001570000000000100145370ustar { "git": { "sha1": "269e8b242eb2664c6fc98972de092a060d96be28" }, "path_in_vcs": "diesel_migrations" }diesel_migrations-2.0.0/Cargo.toml0000644000000021170000000000100125330ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.56.0" name = "diesel_migrations" version = "2.0.0" description = "Migration management for diesel" homepage = "https://diesel.rs" documentation = "https://docs.rs/crate/diesel_migrations" license = "MIT OR Apache-2.0" [dependencies.diesel] version = "~2.0.0" default-features = false [dependencies.migrations_internals] version = "~2.0.0" [dependencies.migrations_macros] version = "~2.0.0" [dev-dependencies.cfg-if] version = "1.0.0" [dev-dependencies.dotenvy] version = "0.15" [dev-dependencies.tempfile] version = "3.2" [features] default = [] mysql = [] postgres = [] sqlite = [] diesel_migrations-2.0.0/Cargo.toml.orig000064400000000000000000000012101046102023000162050ustar 00000000000000[package] name = "diesel_migrations" version = "2.0.0" license = "MIT OR Apache-2.0" description = "Migration management for diesel" documentation = "https://docs.rs/crate/diesel_migrations" homepage = "https://diesel.rs" edition = "2018" rust-version = "1.56.0" [dependencies.migrations_internals] version = "~2.0.0" path = "migrations_internals" [dependencies.migrations_macros] version = "~2.0.0" path = "migrations_macros" [dev-dependencies] dotenvy = "0.15" cfg-if = "1.0.0" tempfile = "3.2" [dependencies.diesel] version = "~2.0.0" path = "../diesel" default-features = false [features] default = [] sqlite = [] postgres = [] mysql = [] diesel_migrations-2.0.0/LICENSE-APACHE000064400000000000000000000250461046102023000152570ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2015-2021 Sean Griffin, 2018-2021 Diesel Core Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diesel_migrations-2.0.0/LICENSE-MIT000064400000000000000000000021121046102023000147540ustar 00000000000000The MIT License (MIT) 2015-2021 Sean Griffin, 2018-2021 Diesel Core Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diesel_migrations-2.0.0/src/embedded_migrations.rs000064400000000000000000000064371046102023000204600ustar 00000000000000use std::fmt::Display; use crate::errors::RunMigrationsError; use crate::file_based_migrations::{DieselMigrationName, TomlMetadataWrapper}; use crate::MigrationError; use diesel::backend::Backend; use diesel::migration::{Migration, MigrationName, MigrationSource, MigrationVersion, Result}; /// A migration source that embeds migrations into the final binary /// /// This source can be create via the [`embed_migrations!`](crate::embed_migrations!) /// at compile time. #[allow(missing_copy_implementations)] pub struct EmbeddedMigrations { migrations: &'static [EmbeddedMigration], } impl EmbeddedMigrations { #[doc(hidden)] pub const fn new(migrations: &'static [EmbeddedMigration]) -> Self { Self { migrations } } } impl MigrationSource for EmbeddedMigrations { fn migrations(&self) -> Result>>> { Ok(self .migrations .iter() .map(|m| Box::new(m) as Box>) .collect()) } } #[doc(hidden)] pub struct EmbeddedMigration { up: &'static str, down: Option<&'static str>, name: EmbeddedName, metadata: TomlMetadataWrapper, } impl EmbeddedMigration { #[doc(hidden)] pub const fn new( up: &'static str, down: Option<&'static str>, name: EmbeddedName, metadata: TomlMetadataWrapper, ) -> Self { Self { up, down, name, metadata, } } } #[derive(Clone, Copy)] #[doc(hidden)] pub struct EmbeddedName { name: &'static str, } impl EmbeddedName { #[doc(hidden)] pub const fn new(name: &'static str) -> Self { Self { name } } } impl MigrationName for EmbeddedName { fn version(&self) -> MigrationVersion { migrations_internals::version_from_string(self.name) .expect( "This name contains a valid version. We checked this at compile time by our macro", ) .into() } } impl Display for EmbeddedName { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.name) } } impl<'a, DB: Backend> Migration for &'a EmbeddedMigration { fn run(&self, conn: &mut dyn diesel::connection::BoxableConnection) -> Result<()> { Ok(conn.batch_execute(self.up).map_err(|e| { let name = DieselMigrationName::from_name(self.name.name) .expect("We have a vaild name here, we checked this in `embed_migration!`"); RunMigrationsError::QueryError(name, e) })?) } fn revert(&self, conn: &mut dyn diesel::connection::BoxableConnection) -> Result<()> { match self.down { Some(down) => Ok(conn.batch_execute(down).map_err(|e| { let name = DieselMigrationName::from_name(self.name.name) .expect("We have a vaild name here, we checked this in `embed_migration!`"); RunMigrationsError::QueryError(name, e) })?), None => Err(MigrationError::NoMigrationRevertFile.into()), } } fn metadata(&self) -> &dyn diesel::migration::MigrationMetadata { &self.metadata as &dyn diesel::migration::MigrationMetadata } fn name(&self) -> &dyn MigrationName { &self.name } } diesel_migrations-2.0.0/src/errors.rs000064400000000000000000000077061046102023000160070ustar 00000000000000//! Error types that represent migration errors. //! These are split into multiple segments, depending on //! where in the migration process an error occurs. use std::convert::From; use std::error::Error; use std::path::PathBuf; use std::{fmt, io}; use diesel::migration::MigrationVersion; use crate::file_based_migrations::DieselMigrationName; /// Errors that occur while preparing to run migrations #[derive(Debug)] #[non_exhaustive] pub enum MigrationError { /// The migration directory wasn't found MigrationDirectoryNotFound(PathBuf), /// Provided migration was in an unknown format UnknownMigrationFormat(PathBuf), /// General system IO error IoError(io::Error), /// Provided migration had an incompatible version number UnknownMigrationVersion(MigrationVersion<'static>), /// No migrations had to be/ could be run NoMigrationRun, /// `down.sql` file is missing, and you're asking for a `revert` /// or `redo` NoMigrationRevertFile, } impl Error for MigrationError {} impl fmt::Display for MigrationError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { MigrationError::MigrationDirectoryNotFound(ref p) => write!( f, "Unable to find migrations directory in {:?} or any parent directories.", p ), MigrationError::UnknownMigrationFormat(_) => write!( f, "Invalid migration directory: the directory's name should be \ _, and it should contain up.sql and \ optionally down.sql." ), MigrationError::IoError(ref error) => write!(f, "{}", error), MigrationError::UnknownMigrationVersion(ref version) => write!( f, "Unable to find migration version {} to revert in the migrations directory.", version ), MigrationError::NoMigrationRun => write!( f, "No migrations have been run. Did you forget `diesel migration run`?" ), MigrationError::NoMigrationRevertFile => { write!(f, "Missing `down.sql` file to revert migration") } } } } impl PartialEq for MigrationError { fn eq(&self, other: &Self) -> bool { match (self, other) { ( &MigrationError::MigrationDirectoryNotFound(_), &MigrationError::MigrationDirectoryNotFound(_), ) => true, ( &MigrationError::UnknownMigrationFormat(ref p1), &MigrationError::UnknownMigrationFormat(ref p2), ) => p1 == p2, _ => false, } } } impl From for MigrationError { fn from(e: io::Error) -> Self { MigrationError::IoError(e) } } /// Errors that occur while running migrations #[derive(Debug, PartialEq)] #[allow(clippy::enum_variant_names)] #[non_exhaustive] pub enum RunMigrationsError { /// A general migration error occured MigrationError(DieselMigrationName, MigrationError), /// The provided migration included an invalid query QueryError(DieselMigrationName, diesel::result::Error), /// The provided migration was empty EmptyMigration(DieselMigrationName), } impl Error for RunMigrationsError {} impl fmt::Display for RunMigrationsError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { RunMigrationsError::MigrationError(v, err) => { write!(f, "Failed to run {} with: {}", v, err) } RunMigrationsError::QueryError(v, err) => { write!(f, "Failed to run {} with: {}", v, err) } RunMigrationsError::EmptyMigration(v) => write!( f, "Failed to run {} with: Attempted to run an empty migration.", v ), } } } diesel_migrations-2.0.0/src/file_based_migrations.rs000064400000000000000000000267271046102023000210100ustar 00000000000000use std::fmt::Display; use std::fs::{DirEntry, File}; use std::io::Read; use std::path::{Path, PathBuf}; use diesel::backend::Backend; use diesel::connection::BoxableConnection; use diesel::migration::{ self, Migration, MigrationMetadata, MigrationName, MigrationSource, MigrationVersion, }; use migrations_internals::TomlMetadata; use crate::errors::{MigrationError, RunMigrationsError}; /// A migration source based on a migration directory in the file system /// /// A valid migration directroy contains a sub folder per migration. /// Each migration folder contains a `up.sql` file containing the migration itself /// and a `down.sql` file containing the nessesary SQL to revert the migration. /// Additionaly each folder can contain a `metadata.toml` file controling how the /// individual migration should be handled by the migration harness. /// /// To embed an existing migration folder into the final binary see /// [`embed_migrations!`](crate::embed_migrations!). /// /// ## Example /// /// ```text /// # Directory Structure /// - 20151219180527_create_users /// - up.sql /// - down.sql /// - 20160107082941_create_posts /// - up.sql /// - down.sql /// ``` /// /// ```sql /// -- 20151219180527_create_users/up.sql /// CREATE TABLE users ( /// id SERIAL PRIMARY KEY, /// name VARCHAR NOT NULL, /// hair_color VARCHAR /// ); /// ``` /// /// ```sql /// -- 20151219180527_create_users/down.sql /// DROP TABLE users; /// ``` /// /// ```sql /// -- 20160107082941_create_posts/up.sql /// CREATE TABLE posts ( /// id SERIAL PRIMARY KEY, /// user_id INTEGER NOT NULL, /// title VARCHAR NOT NULL, /// body TEXT /// ); /// ``` /// /// ```sql /// -- 20160107082941_create_posts/down.sql /// DROP TABLE posts; /// ``` /// /// ```toml /// # 20160107082941_create_posts/metadata.toml /// /// # specifices if a migration is executed inside a /// # transaction or not. This configuration is optional /// # by default all migrations are run in transactions. /// # /// # For certain types of migrations, like creating an /// # index onto a existing column, it is required /// # to set this to false /// run_in_transaction = true /// ``` #[derive(Clone)] pub struct FileBasedMigrations { base_path: PathBuf, } impl FileBasedMigrations { /// Create a new file based migration source based on a specific path /// /// This methods fails if the path passed as argument is no valid migration directory pub fn from_path(path: impl AsRef) -> Result { for dir in migrations_directories(path.as_ref())? { let path = dir?.path(); if !migrations_internals::valid_sql_migration_directory(&path) { return Err(MigrationError::UnknownMigrationFormat(path)); } } Ok(Self { base_path: path.as_ref().to_path_buf(), }) } /// Create a new file based migration source by searching the migration diretcory /// /// This method looks in the current and all parent directories for a folder named /// `migrations` /// /// This method fails if no valid migration directory is found pub fn find_migrations_directory() -> Result { Self::find_migrations_directory_in_path(&std::env::current_dir()?) } /// Create a new file based migration source by searching a give path for the migration /// directory /// /// This method looks in the passed directory and all parent directories for a folder /// named `migrations` /// /// This method fails if no valid migration directory is found pub fn find_migrations_directory_in_path( path: impl AsRef, ) -> Result { let migrations_directory = search_for_migrations_directory(path.as_ref())?; Self::from_path(&migrations_directory) } #[doc(hidden)] pub fn path(&self) -> &Path { &self.base_path } } fn search_for_migrations_directory(path: &Path) -> Result { migrations_internals::search_for_migrations_directory(path) .ok_or_else(|| MigrationError::MigrationDirectoryNotFound(path.to_path_buf())) } fn migrations_directories( path: &'_ Path, ) -> Result> + '_, MigrationError> { Ok(migrations_internals::migrations_directories(path)?.map(move |e| e.map_err(Into::into))) } fn migrations_in_directory( path: &'_ Path, ) -> Result> + '_, MigrationError> { Ok(migrations_directories(path)?.map(|entry| SqlFileMigration::from_path(&entry?.path()))) } impl MigrationSource for FileBasedMigrations { fn migrations(&self) -> migration::Result>>> { migrations_in_directory::(&self.base_path)? .map(|r| Ok(Box::new(r?) as Box>)) .collect() } } struct SqlFileMigration { base_path: PathBuf, metadata: TomlMetadataWrapper, name: DieselMigrationName, } impl SqlFileMigration { fn from_path(path: &Path) -> Result { if migrations_internals::valid_sql_migration_directory(path) { let metadata = TomlMetadataWrapper( TomlMetadata::read_from_file(&path.join("metadata.toml")).unwrap_or_default(), ); Ok(Self { base_path: path.to_path_buf(), metadata, name: DieselMigrationName::from_path(path)?, }) } else { Err(MigrationError::UnknownMigrationFormat(path.to_path_buf())) } } } impl Migration for SqlFileMigration { fn run(&self, conn: &mut dyn BoxableConnection) -> migration::Result<()> { Ok(run_sql_from_file( conn, &self.base_path.join("up.sql"), &self.name, )?) } fn revert(&self, conn: &mut dyn BoxableConnection) -> migration::Result<()> { let down_path = self.base_path.join("down.sql"); if matches!(down_path.metadata(), Err(e) if e.kind() == std::io::ErrorKind::NotFound) { Err(MigrationError::NoMigrationRevertFile.into()) } else { Ok(run_sql_from_file(conn, &down_path, &self.name)?) } } fn metadata(&self) -> &dyn MigrationMetadata { &self.metadata } fn name(&self) -> &dyn MigrationName { &self.name } } #[derive(Debug, PartialEq, Eq)] pub struct DieselMigrationName { name: String, version: MigrationVersion<'static>, } impl Clone for DieselMigrationName { fn clone(&self) -> Self { Self { name: self.name.clone(), version: self.version.as_owned(), } } } impl DieselMigrationName { fn from_path(path: &Path) -> Result { let name = path .file_name() .ok_or_else(|| MigrationError::UnknownMigrationFormat(path.to_path_buf()))? .to_string_lossy(); Self::from_name(&name) } pub(crate) fn from_name(name: &str) -> Result { let version = migrations_internals::version_from_string(name) .ok_or_else(|| MigrationError::UnknownMigrationFormat(PathBuf::from(name)))?; Ok(Self { name: name.to_owned(), version: MigrationVersion::from(version), }) } } impl MigrationName for DieselMigrationName { fn version(&self) -> MigrationVersion { self.version.as_owned() } } impl Display for DieselMigrationName { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.name) } } #[derive(Default)] #[doc(hidden)] pub struct TomlMetadataWrapper(TomlMetadata); impl TomlMetadataWrapper { #[doc(hidden)] pub const fn new(run_in_transaction: bool) -> Self { Self(TomlMetadata::new(run_in_transaction)) } } impl MigrationMetadata for TomlMetadataWrapper { fn run_in_transaction(&self) -> bool { self.0.run_in_transaction } } fn run_sql_from_file( conn: &mut dyn BoxableConnection, path: &Path, name: &DieselMigrationName, ) -> Result<(), RunMigrationsError> { let map_io_err = |e| RunMigrationsError::MigrationError(name.clone(), MigrationError::from(e)); let mut sql = String::new(); let mut file = File::open(path).map_err(map_io_err)?; file.read_to_string(&mut sql).map_err(map_io_err)?; if sql.is_empty() { return Err(RunMigrationsError::EmptyMigration(name.clone())); } conn.batch_execute(&sql) .map_err(|e| RunMigrationsError::QueryError(name.clone(), e))?; Ok(()) } #[cfg(test)] mod tests { extern crate tempfile; use super::*; use self::tempfile::Builder; use std::fs; #[test] fn migration_directory_not_found_if_no_migration_dir_exists() { let dir = Builder::new().prefix("diesel").tempdir().unwrap(); assert_eq!( Err(MigrationError::MigrationDirectoryNotFound( dir.path().into() )), search_for_migrations_directory(dir.path()) ); } #[test] fn migration_directory_defaults_to_pwd_slash_migrations() { let dir = Builder::new().prefix("diesel").tempdir().unwrap(); let temp_path = dir.path().canonicalize().unwrap(); let migrations_path = temp_path.join("migrations"); fs::create_dir(&migrations_path).unwrap(); assert_eq!( Ok(migrations_path), search_for_migrations_directory(&temp_path) ); } #[test] fn migration_directory_checks_parents() { let dir = Builder::new().prefix("diesel").tempdir().unwrap(); let temp_path = dir.path().canonicalize().unwrap(); let migrations_path = temp_path.join("migrations"); let child_path = temp_path.join("child"); fs::create_dir(&child_path).unwrap(); fs::create_dir(&migrations_path).unwrap(); assert_eq!( Ok(migrations_path), search_for_migrations_directory(&child_path) ); } #[cfg(feature = "sqlite")] type Backend = diesel::sqlite::Sqlite; #[cfg(feature = "postgres")] type Backend = diesel::pg::Pg; #[cfg(feature = "mysql")] type Backend = diesel::mysql::Mysql; #[test] fn migration_paths_in_directory_ignores_files() { let dir = Builder::new().prefix("diesel").tempdir().unwrap(); let temp_path = dir.path().canonicalize().unwrap(); let migrations_path = temp_path.join("migrations"); let file_path = migrations_path.join("README.md"); fs::create_dir(&migrations_path).unwrap(); fs::File::create(&file_path).unwrap(); let migrations = migrations_in_directory::(&migrations_path) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(0, migrations.len()); } #[test] fn migration_paths_in_directory_ignores_dot_directories() { let dir = Builder::new().prefix("diesel").tempdir().unwrap(); let temp_path = dir.path().canonicalize().unwrap(); let migrations_path = temp_path.join("migrations"); let dot_path = migrations_path.join(".hidden_dir"); fs::create_dir(&migrations_path).unwrap(); fs::create_dir(&dot_path).unwrap(); let migrations = migrations_in_directory::(&migrations_path) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(0, migrations.len()); } } diesel_migrations-2.0.0/src/lib.rs000064400000000000000000000043431046102023000152330ustar 00000000000000// Built-in Lints // Clippy lints #![allow(clippy::needless_pass_by_value, clippy::map_unwrap_or)] #![warn( missing_docs, clippy::mut_mut, clippy::non_ascii_literal, clippy::similar_names, clippy::unicode_not_nfc, clippy::if_not_else, clippy::items_after_statements, clippy::used_underscore_binding, missing_copy_implementations )] //! Provides functions for maintaining database schema. //! //! A database migration always provides procedures to update the schema, as well as to revert //! itself. Diesel's migrations are versioned, and run in order. Diesel also takes care of tracking //! which migrations have already been run automatically. Your migrations don't need to be //! idempotent, as Diesel will ensure no migration is run twice unless it has been reverted. //! //! Migrations should be placed in a `/migrations` directory at the root of your project (the same //! directory as `Cargo.toml`). When any of these functions are run, Diesel will search for the //! migrations directory in the current directory and its parents, stopping when it finds the //! directory containing `Cargo.toml`. //! //! Individual migrations should be a folder containing two files, `up.sql` and `down.sql`. //! `up.sql` will be used to run the migration, while `down.sql` will be used for reverting it. The //! folder itself should have the structure `{version}_{migration_name}`. It is recommended that //! you use the timestamp of creation for the version. //! //! Migrations can either be run with the CLI or embedded into the compiled application //! and executed with code, for example right after establishing a database connection. //! For more information, consult the [`embed_migrations!`] macro. //! mod embedded_migrations; mod errors; mod file_based_migrations; mod migration_harness; pub use crate::embedded_migrations::EmbeddedMigrations; pub use crate::file_based_migrations::FileBasedMigrations; pub use crate::migration_harness::{HarnessWithOutput, MigrationHarness}; pub use migrations_macros::embed_migrations; #[doc(hidden)] pub use crate::embedded_migrations::{EmbeddedMigration, EmbeddedName}; #[doc(hidden)] pub use crate::errors::MigrationError; #[doc(hidden)] pub use crate::file_based_migrations::TomlMetadataWrapper; diesel_migrations-2.0.0/src/migration_harness.rs000064400000000000000000000240451046102023000202020ustar 00000000000000use diesel::associations::HasTable; use diesel::backend::Backend; use diesel::dsl; use diesel::migration::{ Migration, MigrationConnection, MigrationSource, MigrationVersion, Result, }; use diesel::prelude::*; use diesel::query_builder::{DeleteStatement, InsertStatement, IntoUpdateTarget}; use diesel::query_dsl::methods::ExecuteDsl; use diesel::query_dsl::LoadQuery; use diesel::serialize::ToSql; use diesel::sql_types::Text; use std::cell::RefCell; use std::collections::HashMap; use std::io::Write; use crate::errors::MigrationError; diesel::table! { __diesel_schema_migrations (version) { version -> VarChar, run_on -> Timestamp, } } /// A migration harness is an entity which applies migration to an existing database pub trait MigrationHarness { /// Checks if the database represented by the current harness has unapplied migrations fn has_pending_migration>(&mut self, source: S) -> Result { self.pending_migrations(source).map(|p| !p.is_empty()) } /// Execute all unapplied migrations for a given migration source fn run_pending_migrations>( &mut self, source: S, ) -> Result> { let pending = self.pending_migrations(source)?; self.run_migrations(&pending) } /// Execute all migrations in the given list /// /// This method does not check if a certain migration was already applied or not #[doc(hidden)] fn run_migrations( &mut self, migrations: &[Box>], ) -> Result> { migrations.iter().map(|m| self.run_migration(m)).collect() } /// Execute the next migration from the given migration source fn run_next_migration>( &mut self, source: S, ) -> Result { let pending_migrations = self.pending_migrations(source)?; let next_migration = pending_migrations .first() .ok_or(MigrationError::NoMigrationRun)?; self.run_migration(next_migration) } /// Revert all applied migrations from a given migration source fn revert_all_migrations>( &mut self, source: S, ) -> Result> { let applied_versions = self.applied_migrations()?; let mut migrations = source .migrations()? .into_iter() .map(|m| (m.name().version().as_owned(), m)) .collect::>(); applied_versions .into_iter() .map(|version| { let migration_to_revert = migrations .remove(&version) .ok_or(MigrationError::UnknownMigrationVersion(version))?; self.revert_migration(&migration_to_revert) }) .collect() } /// Revert the last migration from a given migration source /// /// This method returns a error if the given migration source does not /// contain the last applied migration fn revert_last_migration>( &mut self, source: S, ) -> Result> { let applied_versions = self.applied_migrations()?; let migrations = source.migrations()?; let last_migration_version = applied_versions .first() .ok_or(MigrationError::NoMigrationRun)?; let migration_to_revert = migrations .iter() .find(|m| m.name().version() == *last_migration_version) .ok_or_else(|| { MigrationError::UnknownMigrationVersion(last_migration_version.as_owned()) })?; self.revert_migration(migration_to_revert) } /// Get a list of non applied migrations for a specific migration source /// /// The returned migration list is sorted in ascending order by the individual version /// of each migration fn pending_migrations>( &mut self, source: S, ) -> Result>>> { let applied_versions = self.applied_migrations()?; let mut migrations = source .migrations()? .into_iter() .map(|m| (m.name().version().as_owned(), m)) .collect::>(); for applied_version in applied_versions { migrations.remove(&applied_version); } let mut migrations = migrations.into_iter().map(|(_, m)| m).collect::>(); migrations.sort_unstable_by(|a, b| a.name().version().cmp(&b.name().version())); Ok(migrations) } /// Apply a single migration /// /// Types implementing this trait should call [`Migration::run`] internally and record /// that a specific migration version was executed afterwards. fn run_migration(&mut self, migration: &dyn Migration) -> Result>; /// Revert a single migration /// /// Types implementing this trait should call [`Migration::revert`] internally /// and record that a specific migration version was reverted afterwards. fn revert_migration( &mut self, migration: &dyn Migration, ) -> Result>; /// Get a list of already applied migration versions fn applied_migrations(&mut self) -> Result>>; } impl<'b, C, DB> MigrationHarness for C where DB: Backend, C: Connection + MigrationConnection + 'static, dsl::Order< dsl::Select<__diesel_schema_migrations::table, __diesel_schema_migrations::version>, dsl::Desc<__diesel_schema_migrations::version>, >: LoadQuery<'b, C, MigrationVersion<'static>>, for<'a> InsertStatement< __diesel_schema_migrations::table, > as Insertable< __diesel_schema_migrations::table, >>::Values, >: diesel::query_builder::QueryFragment + ExecuteDsl, DeleteStatement< , > as HasTable>::Table, , > as IntoUpdateTarget>::WhereClause, >: ExecuteDsl, str: ToSql, { fn run_migration( &mut self, migration: &dyn Migration, ) -> Result> { let apply_migration = |conn: &mut C| -> Result<()> { migration.run(conn)?; diesel::insert_into(__diesel_schema_migrations::table) .values(__diesel_schema_migrations::version.eq(migration.name().version().as_owned())).execute(conn)?; Ok(()) }; if migration.metadata().run_in_transaction() { self.transaction(apply_migration)?; } else { apply_migration(self)?; } Ok(migration.name().version().as_owned()) } fn revert_migration( &mut self, migration: &dyn Migration, ) -> Result> { let revert_migration = |conn: &mut C| -> Result<()> { migration.revert(conn)?; diesel::delete(__diesel_schema_migrations::table.find(migration.name().version().as_owned())) .execute(conn)?; Ok(()) }; if migration.metadata().run_in_transaction() { self.transaction(revert_migration)?; } else { revert_migration(self)?; } Ok(migration.name().version().as_owned()) } fn applied_migrations(&mut self) -> Result>> { setup_database(self)?; Ok(__diesel_schema_migrations::table .select(__diesel_schema_migrations::version) .order(__diesel_schema_migrations::version.desc()) .load(self)?) } } /// A migration harness that writes messages /// into some output for each applied/reverted migration pub struct HarnessWithOutput<'a, C, W> { connection: &'a mut C, output: RefCell, } impl<'a, C, W> HarnessWithOutput<'a, C, W> { /// Create a new `HarnessWithOutput` that writes to a specific writer pub fn new(harness: &'a mut C, output: W) -> Self where C: MigrationHarness, DB: Backend, W: Write, { Self { connection: harness, output: RefCell::new(output), } } } impl<'a, C> HarnessWithOutput<'a, C, std::io::Stdout> { /// Create a new `HarnessWithOutput` that writes to stdout pub fn write_to_stdout(harness: &'a mut C) -> Self where C: MigrationHarness, DB: Backend, { Self { connection: harness, output: RefCell::new(std::io::stdout()), } } } impl<'a, C, W, DB> MigrationHarness for HarnessWithOutput<'a, C, W> where W: Write, C: MigrationHarness, DB: Backend, { fn run_migration( &mut self, migration: &dyn Migration, ) -> Result> { if migration.name().version() != MigrationVersion::from("00000000000000") { let mut output = self.output.try_borrow_mut()?; writeln!(output, "Running migration {}", migration.name())?; } self.connection.run_migration(migration) } fn revert_migration( &mut self, migration: &dyn Migration, ) -> Result> { if migration.name().version() != MigrationVersion::from("00000000000000") { let mut output = self.output.try_borrow_mut()?; writeln!(output, "Rolling back migration {}", migration.name())?; } self.connection.revert_migration(migration) } fn applied_migrations(&mut self) -> Result>> { self.connection.applied_migrations() } } fn setup_database(conn: &mut Conn) -> QueryResult { conn.setup() }