@@ -18,6 +18,10 @@ use std::error::Error;
1818use std:: env;
1919use std:: io:: stdout;
2020use std:: path:: Path ;
21+ #[ cfg( feature="postgres" ) ]
22+ use std:: fs:: { self , File } ;
23+ #[ cfg( feature="postgres" ) ]
24+ use std:: io:: Write ;
2125
2226enum Backend {
2327 #[ cfg( feature="postgres" ) ]
@@ -116,8 +120,10 @@ pub fn reset_database(args: &ArgMatches, migrations_dir: &Path) -> DatabaseResul
116120pub fn setup_database ( args : & ArgMatches , migrations_dir : & Path ) -> DatabaseResult < ( ) > {
117121 let database_url = database_url ( args) ;
118122
119- try!( create_database_if_needed ( & database_url) ) ;
120- create_schema_table_and_run_migrations_if_needed ( & database_url, migrations_dir)
123+ create_database_if_needed ( & database_url) ?;
124+ create_default_migration_if_needed ( & database_url, migrations_dir) ?;
125+ create_schema_table_and_run_migrations_if_needed ( & database_url, migrations_dir) ?;
126+ Ok ( ( ) )
121127}
122128
123129pub fn drop_database_command ( args : & ArgMatches ) -> DatabaseResult < ( ) > {
@@ -158,6 +164,31 @@ fn create_database_if_needed(database_url: &str) -> DatabaseResult<()> {
158164 Ok ( ( ) )
159165}
160166
167+ fn create_default_migration_if_needed ( database_url : & str , migrations_dir : & Path )
168+ -> DatabaseResult < ( ) >
169+ {
170+ let initial_migration_path = migrations_dir. join ( "00000000000000_diesel_initial_setup" ) ;
171+ if initial_migration_path. exists ( ) {
172+ return Ok ( ( ) )
173+ }
174+
175+ #[ allow( unreachable_patterns) ]
176+ #[ cfg_attr( feature="clippy" , allow( single_match) ) ]
177+ match Backend :: for_url ( database_url) {
178+ #[ cfg( feature="postgres" ) ]
179+ Backend :: Pg => {
180+ fs:: create_dir_all ( & initial_migration_path) ?;
181+ let mut up_sql = File :: create ( initial_migration_path. join ( "up.sql" ) ) ?;
182+ up_sql. write_all ( include_bytes ! ( "setup_sql/postgres/initial_setup/up.sql" ) ) ?;
183+ let mut down_sql = File :: create ( initial_migration_path. join ( "down.sql" ) ) ?;
184+ down_sql. write_all ( include_bytes ! ( "setup_sql/postgres/initial_setup/down.sql" ) ) ?;
185+ }
186+ _ => { } // No default migration for this backend
187+ }
188+
189+ Ok ( ( ) )
190+ }
191+
161192/// Creates the `__diesel_schema_migrations` table if it doesn't exist. If the
162193/// table didn't exist, it also runs any pending migrations. Returns a
163194/// `DatabaseError::ConnectionError` if it can't create the table, and exits
0 commit comments