go-pg / migrations

SQL database migrations for Golang go-pg and PostgreSQL
https://godoc.org/github.com/go-pg/migrations
BSD 2-Clause "Simplified" License
309 stars 59 forks source link

Add schemaName field to Collection struct #104

Closed maximerety closed 3 years ago

maximerety commented 3 years ago

This allows to use a default schema different than "public" without prefixing the resources to create (tables, sequences, ...) with the schema name explicitly.

Say, for the sake of example, that you have a test PostgreSQL database and a schema called test_schema (but no public schema).

You might want to run the migration against this schema without having to hard-code the test_schema. prefix in all the migration definitions (e.g. you want CREATE TABLE table1 (...) instead of CREATE TABLE test_schema.table1 (...)).

This is currently not possible as the default public. schema prefix would be used.

With the feature added in this commit this would be as simple as doing:

package tests

// With collection being a *migrations.Collection definition imported from a non-test package:
collection.SetSchemaName("test_schema")
collection.Run(testDB, "init")
collection.Run(testDB, "up")
// a.s.o.

Apart for the tests scenario, this allows to deploy the same migration definitions to different schemas, e.g. if you have different databases and schemas to deploy to (think shards or multiple envs).

maximerety commented 3 years ago

I realized that my understanding was erroneous and the code of the migrations themselves was not related at all to the selected schema.

The schema used in migrations will be either the one specified explicitly in the migration definition, e.g. CREATE TABLE test_schema.table (...) or the schema found by PostgreSQL in the search_path, which can be overridden in the database connection itself.

Choosing a schema other than "public" for the creation of the gopg_migrations table itself is already supported by using the existing SetTableName method:

package tests

// With collection being a *migrations.Collection definition imported from a non-test package:
collection.SetTableName("test_schema.gopg_migrations")
collection.Run(testDB, "init")
collection.Run(testDB, "up")
// a.s.o.

There is no need for the SetSchemaName method anymore, so I'm closing this PR.