The Codest
  • Sobre nós
  • Serviços
    • Desenvolvimento de software
      • Desenvolvimento de front-end
      • Desenvolvimento backend
    • Staff Augmentation
      • Programadores Frontend
      • Programadores de back-end
      • Engenheiros de dados
      • Engenheiros de nuvem
      • Engenheiros de GQ
      • Outros
    • Aconselhamento
      • Auditoria e consultoria
  • Indústrias
    • Fintech e Banca
    • E-commerce
    • Adtech
    • Tecnologia da saúde
    • Fabrico
    • Logística
    • Automóvel
    • IOT
  • Valor para
    • CEO
    • CTO
    • Gestor de entregas
  • A nossa equipa
  • Case Studies
  • Saber como
    • Blogue
    • Encontros
    • Webinars
    • Recursos
Carreiras Entrar em contacto
  • Sobre nós
  • Serviços
    • Desenvolvimento de software
      • Desenvolvimento de front-end
      • Desenvolvimento backend
    • Staff Augmentation
      • Programadores Frontend
      • Programadores de back-end
      • Engenheiros de dados
      • Engenheiros de nuvem
      • Engenheiros de GQ
      • Outros
    • Aconselhamento
      • Auditoria e consultoria
  • Valor para
    • CEO
    • CTO
    • Gestor de entregas
  • A nossa equipa
  • Case Studies
  • Saber como
    • Blogue
    • Encontros
    • Webinars
    • Recursos
Carreiras Entrar em contacto
Seta para trás VOLTAR
2016-07-09
Desenvolvimento de software

Managing Database Structure Across Multiple Branches

Tomasz Kowalewski

Developing an app does not only mean implementing new functions or patching it. Sometimes you have to reverse the changes and go back to the previous stage of a project. A frequent issue that can come up while working on multiple branches is connected to maintaining the appropriate version of a database structure. Programmers, who use rails, have ready-made solutions at their disposal. These solutions support the implementation and control of database changes – these are migrations. I will not describe how it works and what possibilities it brings – I would like to focus on the problem of maintaining the appropriate version of a database structure while switching branches.

The database layer of an app is a separate being and is controlled only by migrations. While creating new migrations, remember to make the planned transformation of a database structure reversible. Of course, in extreme cases, we can raise IrreversibleMigration no down method. This will also inform nós about the fact that the migration cannot be reversed. There are different types of changes that we make in the migration – creating, modifying and removing tables, columns or indexes. Deleting and modifying operations are the most sensitive to change. Why? Let’s consider the following scenario:We are working with the master branch, which is our main working path. Currently we have one table:

 class CreateArticles < ActiveRecord::Migration
   def change
     create_table :articles do |t|
       t.string :name
       t.text :description
       t.string :status, null: false
       t.timestamps null: false
     end
   end
 end

O nosso Article model has such validations which require the presence of nome, description e estatuto attributes.

 class Article < ActiveRecord::Base
   validates :name, presence: true
   validates :description, presence: true
   validates :status, presence: true
 end

We are implementing changes into our artigos table on feature development branch and we delete the estatuto column.

 class RemoveStatusColumnFromArticles < ActiveRecord::Migration
   def change
     remove_column :articles, :status, :string
   end
 end

We execute the migration:

 $ [example/feature]: bundle exec rake db:migrate
 == 20150605120955 RemoveStatusColumnFromArticles: migrating ===================
 -- remove_column(:articles, :status, :string)
   -> 0.0717s
 == 20150605120955 RemoveStatusColumnFromArticles: migrated (0.0718s) ==========

The schema for a database changes:

diff --git a/db/schema.rb b/db/schema.rb
index 2a100a9..76438c1 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,14 +11,13 @@ #

It's strongly recommended that you check this file into your version control system.

-ActiveRecord::Schema.define(version: 20150605120350) do
+ActiveRecord::Schema.define(version: 20150605120955) do
  createtable "articles", force: :cascade do |t|
    t.string   "name"
    t.text     "description"
-    t.string   "status",      null: false     t.datetime "createdat",  null: false
    t.datetime "updated_at",  null: false
  end

end

Next, we commit the changes to the feature branch. To simulate this issue we switch the current branch to master. The base structure was changed by migration, which deletes the estatuto column on the feature branch. Let’s try to use the following command:

Article.create!(name: "Kaboom", description: "Lorem ipsum...", status: "active")

What will happen after executing the above mentioned código? The error: ActiveRecord::UnknownAttributeError: unknown attribute 'status' for Article will be raised and that’s because of the incompatible structure version of a database. Before changing the branch to master we should roll back the a migration that deletes the estatuto column from the Article table.

What can we do in order to check if we have to roll back some migrations before switching the branches? With the use of the version control system (here it is git) we can check our work by creating a helpful alias:

 ~/.gitconfig
 [alias]
  migrations = "!f() { git diff --name-only $1..$2 db/migrate | tr -d '[A-Za-z/_.]'; }; f"

Executing the git migrations master feature command will result in the list of migration versions, which are located on feature branches, and which cannot be found on master.

 $ [example/feature]: git migrations master feature
 20150605120955

Thanks to this information we can easily roll back the changes done in the database structure before switching to master.

 $ [example/feature]: bundle exec rake db:migrate:down VERSION=20150605120955
 == 20150605120955 RemoveStatusColumnFromArticles: reverting ===================
 -- add_column(:articles, :status, :string)
   -> 0.0009s
 == 20150605120955 RemoveStatusColumnFromArticles: reverted (0.0045s) ==========

One more thing that we should do after rolling back the migration is to restore the status of a database schema.

$ [example/feature]: git status
On branch feature
Changes not staged for commit:
 (use "git add ..." to update what will be committed)
 (use "git checkout -- ..." to discard changes in working directory)

modified:   db/schema.rb

no changes added to commit (use "git add" and/or "git commit -a")
$ [example/feature]: git checkout db/schema.rb
$ [example/feature]: git status
On branch feature
nothing to commit, working directory clean

Now we can easily switch to the master branch.

The given example is not a complicated problem to solve but it should help you realize how important it is to maintain the structure of a database during the change in the work context.

Artigos relacionados

Ilustração de uma aplicação de cuidados de saúde para smartphone com um ícone de coração e um gráfico de saúde em ascensão, com o logótipo The Codest, representando soluções digitais de saúde e HealthTech.
Desenvolvimento de software

Softwares para o setor de saúde: Tipos, casos de uso

As ferramentas em que as organizações de cuidados de saúde confiam atualmente não se assemelham em nada às fichas de papel de há décadas atrás. O software de cuidados de saúde apoia agora os sistemas de saúde, os cuidados aos doentes e a prestação de cuidados de saúde modernos em...

OCODEST
Ilustração abstrata de um gráfico de barras em declínio com uma seta ascendente e uma moeda de ouro que simboliza a eficiência ou a poupança de custos. O logótipo The Codest aparece no canto superior esquerdo com o slogan "In Code We Trust" sobre um fundo cinzento claro
Desenvolvimento de software

Como dimensionar a sua equipa de desenvolvimento sem perder a qualidade do produto

Aumentar a sua equipa de desenvolvimento? Saiba como crescer sem sacrificar a qualidade do produto. Este guia cobre sinais de que é hora de escalar, estrutura da equipe, contratação, liderança e ferramentas - além de como o The Codest pode...

OCODEST
Desenvolvimento de software

Construir aplicações Web preparadas para o futuro: ideias da equipa de especialistas do The Codest

Descubra como o The Codest se destaca na criação de aplicações web escaláveis e interactivas com tecnologias de ponta, proporcionando experiências de utilizador perfeitas em todas as plataformas. Saiba como a nossa experiência impulsiona a transformação digital e o negócio...

OCODEST
Desenvolvimento de software

As 10 principais empresas de desenvolvimento de software sediadas na Letónia

Saiba mais sobre as principais empresas de desenvolvimento de software da Letónia e as suas soluções inovadoras no nosso último artigo. Descubra como estes líderes tecnológicos podem ajudar a elevar o seu negócio.

thecodest
Soluções para empresas e escalas

Fundamentos do desenvolvimento de software Java: Um Guia para Terceirizar com Sucesso

Explore este guia essencial sobre o desenvolvimento de software Java outsourcing com sucesso para aumentar a eficiência, aceder a conhecimentos especializados e impulsionar o sucesso do projeto com The Codest.

thecodest

Subscreva a nossa base de conhecimentos e mantenha-se atualizado sobre os conhecimentos do sector das TI.

    Sobre nós

    The Codest - Empresa internacional de desenvolvimento de software com centros tecnológicos na Polónia.

    Reino Unido - Sede

    • Office 303B, 182-184 High Street North E6 2JA
      Londres, Inglaterra

    Polónia - Pólos tecnológicos locais

    • Parque de escritórios Fabryczna, Aleja
      Pokoju 18, 31-564 Cracóvia
    • Embaixada do Cérebro, Konstruktorska
      11, 02-673 Varsóvia, Polónia

      The Codest

    • Início
    • Sobre nós
    • Serviços
    • Case Studies
    • Saber como
    • Carreiras
    • Dicionário

      Serviços

    • Aconselhamento
    • Desenvolvimento de software
    • Desenvolvimento backend
    • Desenvolvimento de front-end
    • Staff Augmentation
    • Programadores de back-end
    • Engenheiros de nuvem
    • Engenheiros de dados
    • Outros
    • Engenheiros de GQ

      Recursos

    • Factos e mitos sobre a cooperação com um parceiro externo de desenvolvimento de software
    • Dos EUA para a Europa: Porque é que as empresas americanas decidem mudar-se para a Europa?
    • Comparação dos centros de desenvolvimento da Tech Offshore: Tech Offshore Europa (Polónia), ASEAN (Filipinas), Eurásia (Turquia)
    • Quais são os principais desafios dos CTOs e dos CIOs?
    • The Codest
    • The Codest
    • The Codest
    • Privacy policy
    • Website terms of use

    Direitos de autor © 2026 por The Codest. Todos os direitos reservados.

    pt_PTPortuguese
    en_USEnglish de_DEGerman sv_SESwedish da_DKDanish nb_NONorwegian fiFinnish fr_FRFrench pl_PLPolish arArabic it_ITItalian jaJapanese es_ESSpanish nl_NLDutch etEstonian elGreek cs_CZCzech pt_PTPortuguese