Sobes.tech
Senior

Have you had experience with migrations and what is this mechanism?

sobes.tech AI

Answer from AI

Yes, I have experience with migrations. Migrations are a mechanism for managing changes to the database schema over time. They allow applying changes sequentially, such as creating tables, adding columns, modifying indexes, and rolling them back if necessary.

In Go, migrations are usually implemented using third-party libraries, such as golang-migrate or goose. Migrations consist of a set of files with instructions in SQL or Go code, which are applied in a specific order.

Example of using golang-migrate:

  1. Create a migration file named like 0001_create_users_table.up.sql for applying and 0001_create_users_table.down.sql for rollback.

  2. In the .up.sql file, write SQL to create the table:

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);
  1. In the .down.sql file, write SQL to delete the table:
DROP TABLE users;
  1. Run the migrations with the command:
migrate -path ./migrations -database "postgres://user:pass@localhost:5432/dbname?sslmode=disable" up

Thus, migrations provide database version control, simplify team collaboration, and automate the deployment process.

Have you had experience with migrations and what is… - sobes.tech