migrations_macros-2.2.0/.cargo_vcs_info.json0000644000000002010000000000100145460ustar { "git": { "sha1": "197f06d8d1c0f66774b1ab24c5db93d28962e07a" }, "path_in_vcs": "diesel_migrations/migrations_macros" }migrations_macros-2.2.0/Cargo.toml0000644000000022470000000000100125600ustar # 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 = "2021" rust-version = "1.78.0" name = "migrations_macros" version = "2.2.0" include = [ "src/**/*.rs", "tests/**/*.rs", "LICENSE-*", "README.md", ] description = "Codegeneration macros for diesels embedded migrations" homepage = "https://diesel.rs" license = "MIT OR Apache-2.0" repository = "https://github.com/diesel-rs/diesel" [lib] proc-macro = true [dependencies.migrations_internals] version = "~2.2.0" [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dev-dependencies.cfg-if] version = "1.0.0" [dev-dependencies.dotenvy] version = "0.15" [dev-dependencies.tempfile] version = "3.1.0" [features] default = [] mysql = [] postgres = [] sqlite = [] migrations_macros-2.2.0/Cargo.toml.orig000064400000000000000000000013621046102023000162360ustar 00000000000000[package] name = "migrations_macros" version = "2.2.0" license = "MIT OR Apache-2.0" description = "Codegeneration macros for diesels embedded migrations" homepage = "https://diesel.rs" repository = "https://github.com/diesel-rs/diesel" edition = "2021" include.workspace = true rust-version.workspace = true [dependencies] quote = "1" proc-macro2 = "1" [dependencies.migrations_internals] version = "~2.2.0" path = "../migrations_internals" [dev-dependencies] tempfile = "3.1.0" dotenvy = "0.15" cfg-if = "1.0.0" [dev-dependencies.diesel] path = "../../diesel" default-features = false [dev-dependencies.diesel_migrations] path = "../" default-features = false [lib] proc-macro = true [features] default = [] sqlite = [] postgres = [] mysql = [] migrations_macros-2.2.0/LICENSE-APACHE000064400000000000000000000250461046102023000153000ustar 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. migrations_macros-2.2.0/LICENSE-MIT000064400000000000000000000021121046102023000147750ustar 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. migrations_macros-2.2.0/src/embed_migrations.rs000064400000000000000000000050301046102023000200100ustar 00000000000000use crate::migrations::migration_directory_from_given_path; use migrations_internals::{migrations_directories, version_from_string, TomlMetadata}; use quote::quote; use std::error::Error; use std::fs::DirEntry; use std::path::Path; pub fn expand(path: String) -> proc_macro2::TokenStream { let migrations_path_opt = if path.is_empty() { None } else { Some(path.replace('"', "")) }; let migrations_expr = migration_directory_from_given_path(migrations_path_opt.as_deref()) .unwrap_or_else(|_| { panic!( "Failed to receive migrations dir from {:?}", migrations_path_opt ) }); let embedded_migrations = migration_literals_from_path(&migrations_expr).expect("Failed to read migration literals"); quote! { diesel_migrations::EmbeddedMigrations::new(&[#(#embedded_migrations,)*]) } } fn migration_literals_from_path( path: &Path, ) -> Result, Box> { let mut migrations = migrations_directories(path)?.collect::, _>>()?; migrations.sort_by_key(DirEntry::path); Ok(migrations .into_iter() .map(|e| migration_literal_from_path(&e.path())) .collect()) } fn migration_literal_from_path(path: &Path) -> proc_macro2::TokenStream { let name = path .file_name() .unwrap_or_else(|| panic!("Can't get file name from path `{:?}`", path)) .to_string_lossy(); if version_from_string(&name).is_none() { panic!( "Invalid migration directory: the directory's name should be \ _, and it should contain \ up.sql and optionally down.sql." ); } let up_sql_path = path.join("up.sql"); let up_sql_path = up_sql_path.to_str(); let down_sql_path = path.join("down.sql"); let metadata = TomlMetadata::read_from_file(&path.join("metadata.toml")).unwrap_or_default(); let run_in_transaction = metadata.run_in_transaction; let down_sql = match down_sql_path.metadata() { Err(e) if e.kind() == std::io::ErrorKind::NotFound => quote! { None }, _ => { let down_sql_path = down_sql_path.to_str(); quote! { Some(include_str!(#down_sql_path)) } } }; quote!(diesel_migrations::EmbeddedMigration::new( include_str!(#up_sql_path), #down_sql, diesel_migrations::EmbeddedName::new(#name), diesel_migrations::TomlMetadataWrapper::new(#run_in_transaction) )) } migrations_macros-2.2.0/src/lib.rs000064400000000000000000000107461046102023000152600ustar 00000000000000// Built-in Lints // Clippy lints #![allow( clippy::map_unwrap_or, clippy::match_same_arms, clippy::type_complexity, clippy::needless_doctest_main )] #![warn( clippy::unwrap_used, clippy::print_stdout, clippy::mut_mut, clippy::non_ascii_literal, clippy::similar_names, clippy::unicode_not_nfc, clippy::enum_glob_use, clippy::if_not_else, clippy::items_after_statements, clippy::used_underscore_binding, missing_debug_implementations, missing_copy_implementations )] #![cfg_attr(test, allow(clippy::unwrap_used))] extern crate proc_macro; mod embed_migrations; mod migrations; use proc_macro::TokenStream; /// This macro will read your migrations at compile time, and create a constant value containing /// an embedded list of all your migrations as available at compile time. /// This is useful if you would like to use Diesel's migration infrastructure, but want to ship a single executable /// file (such as for embedded applications). It can also be used to apply migrations to an in /// memory database (Diesel does this for its own test suite). /// /// You can optionally pass the path to the migrations directory to this macro. When left /// unspecified, Diesel will search for the migrations directory in the same way that /// Diesel CLI does. If specified, the path should be relative to the directory where `Cargo.toml` /// resides. /// /// # Examples /// /// ```rust /// use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; /// # use std::error::Error; /// # include!("../../../diesel/src/doctest_setup.rs"); /// # /// # #[cfg(feature = "postgres")] /// # fn migration_connection() -> diesel::PgConnection { /// # let connection_url = database_url_from_env("PG_DATABASE_URL"); /// # let mut conn = diesel::PgConnection::establish(&connection_url).unwrap(); /// # conn.begin_test_transaction().unwrap(); /// # conn /// # } /// # /// # #[cfg(feature = "sqlite")] /// # fn migration_connection() -> diesel::SqliteConnection { /// # let connection_url = database_url_from_env("SQLITE_DATABASE_URL"); /// # let mut conn = diesel::SqliteConnection::establish(&connection_url).unwrap(); /// # conn.begin_test_transaction().unwrap(); /// # conn /// # } /// # /// # #[cfg(feature = "mysql")] /// # fn migration_connection() -> diesel::MysqlConnection { /// # let connection_url = database_url_from_env("MYSQL_DATABASE_URL"); /// # let mut conn = diesel::MysqlConnection::establish(&connection_url).unwrap(); /// # conn /// # } /// # /// # /// # #[cfg(feature = "postgres")] /// pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("../../migrations/postgresql"); /// # #[cfg(all(feature = "mysql", not(feature = "postgres")))] /// # pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("../../migrations/mysql"); /// # #[cfg(all(feature = "sqlite", not(any(feature = "postgres", feature = "mysql"))))] /// # pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("../../migrations/sqlite"); /// /// # fn main() { /// # let connection = &mut migration_connection(); /// # run_migrations(connection).unwrap(); /// # } /// /// fn run_migrations(connection: &mut impl MigrationHarness) -> Result<(), Box> { /// # #[cfg(feature = "mysql")] /// # connection.revert_all_migrations(MIGRATIONS)?; /// /// // This will run the necessary migrations. /// // /// // See the documentation for `MigrationHarness` for /// // all available methods. /// connection.run_pending_migrations(MIGRATIONS)?; /// /// Ok(()) /// } /// ``` /// /// # Automatic rebuilds /// /// Due to limitations in rusts proc-macro API there is currently no /// way to signal that a specific proc macro should be rerun if some /// external file changes/is added. This implies that `embed_migrations!` /// cannot regenerate the list of embedded migrations if **only** the /// migrations are changed. This limitation can be solved by adding a /// custom `build.rs` file to your crate, such that the crate is rebuild /// if the migration directory changes. /// /// Add the following `build.rs` file to your project to fix the problem /// /// ``` /// fn main() { /// println!("cargo:rerun-if-changed=path/to/your/migration/dir/relative/to/your/Cargo.toml"); /// } /// ``` #[proc_macro] pub fn embed_migrations(input: TokenStream) -> TokenStream { embed_migrations::expand(input.to_string()) .to_string() .parse() .expect("Failed to create embedded migrations instance") } migrations_macros-2.2.0/src/migrations.rs000064400000000000000000000107651046102023000166670ustar 00000000000000use migrations_internals::search_for_migrations_directory; use std::env; use std::error::Error; use std::path::{Path, PathBuf}; pub fn migration_directory_from_given_path( given_path: Option<&str>, ) -> Result> { let cargo_toml_directory = env::var("CARGO_MANIFEST_DIR")?; let cargo_manifest_path = Path::new(&cargo_toml_directory); let migrations_path = given_path.as_ref().map(Path::new); resolve_migrations_directory(cargo_manifest_path, migrations_path) } fn resolve_migrations_directory( cargo_manifest_dir: &Path, relative_path_to_migrations: Option<&Path>, ) -> Result> { let result = match relative_path_to_migrations { Some(dir) => cargo_manifest_dir.join(dir), None => { // People commonly put their migrations in src/migrations // so start the search there rather than the project root let src_dir = cargo_manifest_dir.join("src"); search_for_migrations_directory(&src_dir).ok_or_else(|| { format!( "Failed to find migration directory in {}", src_dir.display() ) })? } }; result.canonicalize().map_err(Into::into) } #[cfg(test)] mod tests { use tempfile; use self::tempfile::Builder; use super::resolve_migrations_directory; use std::fs; use std::path::Path; #[test] fn migrations_directory_resolved_relative_to_cargo_manifest_dir() { let tempdir = Builder::new().prefix("diesel").tempdir().unwrap(); fs::create_dir_all(tempdir.path().join("foo/special_migrations")).unwrap(); let cargo_manifest_dir = tempdir.path().join("foo"); let relative_path = Some(Path::new("special_migrations")); assert_eq!( tempdir .path() .join("foo/special_migrations") .canonicalize() .ok(), resolve_migrations_directory(&cargo_manifest_dir, relative_path).ok() ); } #[test] fn migrations_directory_canonicalizes_result() { let tempdir = Builder::new().prefix("diesel").tempdir().unwrap(); fs::create_dir_all(tempdir.path().join("foo/migrations/bar")).unwrap(); fs::create_dir_all(tempdir.path().join("foo/bar")).unwrap(); let cargo_manifest_dir = tempdir.path().join("foo/bar"); let relative_path = Some(Path::new("../migrations/bar")); assert_eq!( tempdir .path() .join("foo/migrations/bar") .canonicalize() .ok(), resolve_migrations_directory(&cargo_manifest_dir, relative_path).ok() ); } #[test] fn migrations_directory_defaults_to_searching_migrations_path() { let tempdir = Builder::new().prefix("diesel").tempdir().unwrap(); fs::create_dir_all(tempdir.path().join("foo/migrations")).unwrap(); fs::create_dir_all(tempdir.path().join("foo/bar")).unwrap(); let cargo_manifest_dir = tempdir.path().join("foo/bar"); assert_eq!( tempdir.path().join("foo/migrations").canonicalize().ok(), resolve_migrations_directory(&cargo_manifest_dir, None).ok() ); } #[test] fn migrations_directory_searches_src_migrations_if_present() { let tempdir = Builder::new().prefix("diesel").tempdir().unwrap(); fs::create_dir_all(tempdir.path().join("foo/src/migrations")).unwrap(); fs::create_dir_all(tempdir.path().join("foo/migrations")).unwrap(); let cargo_manifest_dir = tempdir.path().join("foo"); assert_eq!( tempdir .path() .join("foo/src/migrations") .canonicalize() .ok(), resolve_migrations_directory(&cargo_manifest_dir, None).ok() ); } #[test] fn migrations_directory_allows_no_parent_dir_for_cargo_manifest_dir() { let tempdir = Builder::new().prefix("diesel").tempdir().unwrap(); fs::create_dir_all(tempdir.path().join("special_migrations")).unwrap(); let cargo_manifest_dir = tempdir.path().to_owned(); let relative_path = Some(Path::new("special_migrations")); assert_eq!( tempdir .path() .join("special_migrations") .canonicalize() .ok(), resolve_migrations_directory(&cargo_manifest_dir, relative_path).ok() ); } } migrations_macros-2.2.0/src/util.rs000064400000000000000000000024751046102023000154670ustar 00000000000000use syn::*; pub fn str_value_of_meta_item(item: &Meta, name: &str) -> String { match *item { Meta::NameValue(MetaNameValue { lit: Lit::Str(ref value), .. }) => value.value(), _ => panic!( r#"`{}` must be in the form `#[{}="something"]`"#, name, name ), } } pub fn get_options_from_input( name: &Path, attrs: &[Attribute], on_bug: fn() -> !, ) -> Option> { let options = attrs .iter() .find(|a| &a.path == name) .map(Attribute::parse_meta); match options { Some(Ok(Meta::List(MetaList { ref nested, .. }))) => Some( nested .iter() .map(|o| match *o { NestedMeta::Meta(ref m) => m.clone(), _ => on_bug(), }) .collect(), ), Some(_) => on_bug(), None => None, } } pub fn get_option(options: &[Meta], option_name: &str, on_bug: fn() -> !) -> String { get_optional_option(options, option_name).unwrap_or_else(|| on_bug()) } pub fn get_optional_option(options: &[Meta], option_name: &str) -> Option { options .iter() .find(|a| a.path().is_ident(option_name)) .map(|a| str_value_of_meta_item(a, option_name)) }