@@ -42,6 +42,11 @@ pub async fn add(
42
42
) -> anyhow:: Result < ( ) > {
43
43
fs:: create_dir_all ( migration_source) . context ( "Unable to create migrations directory" ) ?;
44
44
45
+ // if the migrations directory is empty
46
+ let has_existing_migrations = fs:: read_dir ( migration_source)
47
+ . map ( |mut dir| dir. next ( ) . is_some ( ) )
48
+ . unwrap_or ( false ) ;
49
+
45
50
let migrator = Migrator :: new ( Path :: new ( migration_source) ) . await ?;
46
51
// This checks if all existing migrations are of the same type as the reverisble flag passed
47
52
for migration in migrator. iter ( ) {
@@ -74,6 +79,31 @@ pub async fn add(
74
79
) ?;
75
80
}
76
81
82
+ if !has_existing_migrations {
83
+ let quoted_source = if migration_source != "migrations" {
84
+ format ! ( "{:?}" , migration_source)
85
+ } else {
86
+ "" . to_string ( )
87
+ } ;
88
+
89
+ print ! (
90
+ r#"
91
+ Congratulations on creating your first migration!
92
+
93
+ Did you know you can embed your migrations in your application binary?
94
+ On startup, after creating your database connection or pool, add:
95
+
96
+ sqlx::migrate!({}).run(<&your_pool OR &mut your_connection>).await?;
97
+
98
+ Note that the compiler won't pick up new migrations if no Rust source files have changed.
99
+ You can create a Cargo build script to work around this with `sqlx migrate build-script`.
100
+
101
+ See: https://docs.rs/sqlx/0.5/sqlx/macro.migrate.html
102
+ "# ,
103
+ quoted_source
104
+ ) ;
105
+ }
106
+
77
107
Ok ( ( ) )
78
108
}
79
109
@@ -245,3 +275,30 @@ pub async fn revert(
245
275
246
276
Ok ( ( ) )
247
277
}
278
+
279
+ pub fn build_script ( migration_source : & str , force : bool ) -> anyhow:: Result < ( ) > {
280
+ anyhow:: ensure!(
281
+ Path :: new( "Cargo.toml" ) . exists( ) ,
282
+ "must be run in a Cargo project root"
283
+ ) ;
284
+
285
+ anyhow:: ensure!(
286
+ ( force || !Path :: new( "build.rs" ) . exists( ) ) ,
287
+ "build.rs already exists; use --force to overwrite"
288
+ ) ;
289
+
290
+ let contents = format ! (
291
+ r#"// generated by `sqlx migrate build-script`
292
+ fn main() {{
293
+ // trigger recompilation when a new migration is added
294
+ println!("cargo:rerun-if-changed={}");
295
+ }}"# ,
296
+ migration_source
297
+ ) ;
298
+
299
+ fs:: write ( "build.rs" , contents) ?;
300
+
301
+ println ! ( "Created `build.rs`; be sure to check it into version control!" ) ;
302
+
303
+ Ok ( ( ) )
304
+ }
0 commit comments