Repository: supabase/cli
Pull request #1222 (2023-06-20 21:34:33)

fix: baseline should work without specifying version
## What kind of change does this PR introduce?

Bug fix https://github.com/supabase/cli/issues/192#issuecomment-1599364500

## What is the new behavior?

Baselines the earliest version if none is specified.

## Additional context

Add any other context or screenshots.


coveralls: ## Pull Request Test Coverage Report for [Build 5327623594](https://coveralls.io/builds/60855189)

* **7** of **10**   **(70.0%)**  changed or added relevant lines in **2** files are covered.
* **7** unchanged lines in **1** file lost coverage.
* Overall coverage decreased (**-0.06%**) to **61.732%**

---

|  Changes Missing Coverage | Covered Lines | Changed/Added Lines | % |
| :-----|--------------|--------|---: |
| [cmd/migration.go](https://coveralls.io/builds/60855189/source?filename=cmd%2Fmigration.go#L88) | 0 | 3 | 0.0%
<!-- | **Total:** | **7** | **10** | **70.0%** | -->

|  Files with Coverage Reduction | New Missed Lines | % |
| :-----|--------------|--: |
| [internal/gen/keys/keys.go](https://coveralls.io/builds/60855189/source?filename=internal%2Fgen%2Fkeys%2Fkeys.go#L94) | 7 | 7.94% |
<!-- | **Total:** | **7** |  | -->

|  Totals | [![Coverage Status](https://coveralls.io/builds/60855189/badge)](https://coveralls.io/builds/60855189) |
| :-- | --: |
| Change from base [Build 5319215965](https://coveralls.io/builds/60833317): |  -0.06% |
| Covered Lines: | 4741 |
| Relevant Lines: | 7680 |

---
##### 💛  - [Coveralls](https://coveralls.io)


Patch:
diff --git a/cmd/migration.go b/cmd/migration.go
index 1ed499bd..52f880cc 100644
--- a/cmd/migration.go
+++ b/cmd/migration.go
@@ -85,6 +85,9 @@ var (
 			}
 			return squash.Run(ctx, version, dbConfig, fsys)
 		},
+		PostRun: func(cmd *cobra.Command, args []string) {
+			fmt.Println("Finished " + utils.Aqua("supabase migration squash") + ".")
+		},
 	}
 
 	migrationUpCmd = &cobra.Command{
diff --git a/internal/migration/squash/squash.go b/internal/migration/squash/squash.go
index 091a5d99..30d23f9c 100644
--- a/internal/migration/squash/squash.go
+++ b/internal/migration/squash/squash.go
@@ -37,7 +37,6 @@ func Run(ctx context.Context, version string, config pgconn.Config, fsys afero.F
 	if len(config.Host) == 0 {
 		return nil
 	}
-	fmt.Fprintln(os.Stderr, "Baselining migration history to", version)
 	return baselineMigrations(ctx, config, version, fsys, options...)
 }
 
@@ -99,6 +98,15 @@ func squashMigrations(ctx context.Context, migrations []string, fsys afero.Fs, o
 const DELETE_MIGRATION_BEFORE = "DELETE FROM supabase_migrations.schema_migrations WHERE version <= $1"
 
 func baselineMigrations(ctx context.Context, config pgconn.Config, version string, fsys afero.Fs, options ...func(*pgx.ConnConfig)) error {
+	if len(version) == 0 {
+		// Expecting no errors here because the caller should have handled them
+		if migrations, _ := list.LoadPartialMigrations(version, fsys); len(migrations) > 0 {
+			if matches := utils.MigrateFilePattern.FindStringSubmatch(migrations[0]); len(matches) > 1 {
+				version = matches[1]
+			}
+		}
+	}
+	fmt.Fprintln(os.Stderr, "Baselining migration history to", version)
 	conn, err := utils.ConnectRemotePostgres(ctx, config, options...)
 	if err != nil {
 		return err


Test patch:
diff --git a/internal/migration/squash/squash_test.go b/internal/migration/squash/squash_test.go
index 9da73844..aa1fbc55 100644
--- a/internal/migration/squash/squash_test.go
+++ b/internal/migration/squash/squash_test.go
@@ -253,6 +253,33 @@ func TestSquashMigrations(t *testing.T) {
 }
 
 func TestBaselineMigration(t *testing.T) {
+	t.Run("baselines earliest version", func(t *testing.T) {
+		// Setup in-memory fs
+		fsys := afero.NewMemMapFs()
+		paths := []string{
+			filepath.Join(utils.MigrationsDir, "0_init.sql"),
+			filepath.Join(utils.MigrationsDir, "1_target.sql"),
+		}
+		sql := "create schema test"
+		require.NoError(t, afero.WriteFile(fsys, paths[0], []byte(sql), 0644))
+		require.NoError(t, afero.WriteFile(fsys, paths[1], []byte{}, 0644))
+		// Setup mock postgres
+		conn := pgtest.NewConn()
+		defer conn.Close(t)
+		conn.Query(repair.CREATE_VERSION_SCHEMA).
+			Reply("CREATE SCHEMA").
+			Query(repair.CREATE_VERSION_TABLE).
+			Reply("CREATE TABLE").
+			Query(repair.ADD_STATEMENTS_COLUMN).
+			Reply("ALTER TABLE").
+			Query(fmt.Sprintf("DELETE FROM supabase_migrations.schema_migrations WHERE version <= '%[1]d';INSERT INTO supabase_migrations.schema_migrations(version, statements) VALUES('%[1]d', '{%[2]s}')", 0, sql)).
+			Reply("INSERT 1")
+		// Run test
+		err := baselineMigrations(context.Background(), dbConfig, "", fsys, conn.Intercept)
+		// Check error
+		assert.NoError(t, err)
+	})
+
 	t.Run("throws error on connect failure", func(t *testing.T) {
 		// Setup in-memory fs
 		fsys := afero.NewMemMapFs()