Junior — Middle
Have you created migrations for databases in your projects?
sobes.tech AI
Answer from AI
Yes, in Go projects, migrations are often created to manage changes in the database structure. Migrations allow applying changes sequentially (creating tables, adding columns, indexes, etc.) and rolling them back if necessary.
For working with migrations in Go, popular libraries include golang-migrate/migrate. They enable storing migrations as SQL or Go code files and applying them programmatically.
Example of using migrations with the migrate library:
import (
"database/sql"
_ "github.com/lib/pq" // PostgreSQL driver
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
func main() {
db, _ := sql.Open("postgres", "postgres://user:pass@localhost:5432/dbname?sslmode=disable")
driver, _ := postgres.WithInstance(db, &postgres.Config{})
m, _ := migrate.NewWithDatabaseInstance(
"file://migrations",
"postgres", driver)
err := m.Up() // apply all migrations
if err != nil && err != migrate.ErrNoChange {
panic(err)
}
}
Thus, migrations help keep the database up-to-date and simplify the deployment and update process of applications.