#800·migrate

Postgres - Error about existing schema even though using "IF NOT EXISTS"

Author: oscarcalderoncCreated Aug 24, 2022Updated Sep 23, 2026

Describe the Bug I have a migration as the 01 SQL file with the following content:

sql
CREATE SCHEMA IF NOT EXISTS my_schema;
...

And then in my code I start a new migration in the following way:

go
// Migrate the database to the latest schema
driver, err := postgres.WithInstance(db, &postgres.Config{})
if err != nil {
	return nil, errors.Wrap(err, "Error creating database connection that is needed to run a database migration.")
}
m, err := migrate.NewWithDatabaseInstance(migrationDirectory, "postgres", driver)
if err != nil {
	return nil, errors.Wrap(err, "Error creating a database migration instance.")
}
err = m.Up()
if err != nil && err.Error() != "no change" {
	return nil, errors.Wrap(err, "Error running a database migration up.")
}

However, even using IF NOT EXISTS clause, migration throws an error indicating that schema already exists:

log
my-app-db     | 2022-08-24 03:35:51.333 UTC [119] ERROR:  schema "my_schema" already exists
my-app-db     | 2022-08-24 03:35:51.333 UTC [119] STATEMENT:  CREATE SCHEMA IF NOT EXISTS my_schema;

Steps to Reproduce Steps to reproduce the behavior:

  1. My migrations look like '...'
  2. I ran migrate with the following options '....'
  3. See error

Expected Behavior To not to fail if I'm trying to create a schema using the option IF NOT EXISTS

Migrate Version e.g. v3.5.4 Obtained by running: migrate -version

Loaded Source Drivers e.g. s3, github, go-bindata, gcs, file Obtained by running: migrate -help

Loaded Database Drivers postgres Obtained by running: migrate -help

Go Version go version go1.18.3 darwin/arm64 Obtained by running: go version

Stacktrace

{"build":"local","error":"Error running a database migration up.: migration failed: schema \"my_schema\" already exists in line 0: CREATE SCHEMA IF NOT EXISTS my_schema;\n\n--
...

Additional context Add any other context about the problem here.