@@ -32,6 +32,9 @@ pub enum DbCommand {
3232
3333 /// Show migration status
3434 Status ,
35+
36+ /// Mark all migrations as applied without running them (for existing databases)
37+ Baseline ,
3538}
3639
3740impl DbCommand {
@@ -42,6 +45,7 @@ impl DbCommand {
4245 match self {
4346 Self :: Migrate => cmd_migrate ( & pool) . await ,
4447 Self :: Status => cmd_status ( & pool) . await ,
48+ Self :: Baseline => cmd_baseline ( & pool) . await ,
4549 }
4650 }
4751}
@@ -137,3 +141,63 @@ async fn cmd_status(pool: &PgPool) -> Result<(), DbError> {
137141
138142 Ok ( ( ) )
139143}
144+
145+ async fn cmd_baseline ( pool : & PgPool ) -> Result < ( ) , DbError > {
146+ // Create _sqlx_migrations table if it doesn't exist
147+ sqlx:: query (
148+ r#"
149+ CREATE TABLE IF NOT EXISTS _sqlx_migrations (
150+ version BIGINT PRIMARY KEY,
151+ description TEXT NOT NULL,
152+ installed_on TIMESTAMPTZ NOT NULL DEFAULT now(),
153+ success BOOLEAN NOT NULL,
154+ checksum BYTEA NOT NULL,
155+ execution_time BIGINT NOT NULL
156+ )
157+ "# ,
158+ )
159+ . execute ( pool)
160+ . await ?;
161+
162+ // Check if already baselined
163+ let count: i64 = sqlx:: query_scalar ( "SELECT COUNT(*) FROM _sqlx_migrations" )
164+ . fetch_one ( pool)
165+ . await ?;
166+
167+ if count > 0 {
168+ println ! (
169+ "{} Database already has {} migration(s) recorded." ,
170+ "Warning:" . yellow( ) . bold( ) ,
171+ count
172+ ) ;
173+ println ! ( "Use '{}' to check status." , "ow db status" . cyan( ) ) ;
174+ return Ok ( ( ) ) ;
175+ }
176+
177+ println ! ( "Marking all migrations as applied...\n " ) ;
178+
179+ for migration in MIGRATOR . iter ( ) {
180+ sqlx:: query (
181+ r#"
182+ INSERT INTO _sqlx_migrations (version, description, success, checksum, execution_time)
183+ VALUES ($1, $2, true, $3, 0)
184+ "# ,
185+ )
186+ . bind ( migration. version )
187+ . bind ( & * migration. description )
188+ . bind ( & migration. checksum [ ..] )
189+ . execute ( pool)
190+ . await ?;
191+
192+ println ! ( " {} {}" , "Baseline" . blue( ) , migration. description) ;
193+ }
194+
195+ // Drop old _migrations table if it exists
196+ sqlx:: query ( "DROP TABLE IF EXISTS _migrations" )
197+ . execute ( pool)
198+ . await ?;
199+
200+ println ! ( "\n {}" , "Baseline complete." . green( ) . bold( ) ) ;
201+
202+ Ok ( ( ) )
203+ }
0 commit comments