Commit 5c614b0d authored by Imre Farkas's avatar Imre Farkas

Merge branch '298703-terraform-name-validation' into 'master'

Add name validation to Terraform state model

See merge request gitlab-org/gitlab!52102
parents 17e6278f 272ca833
......@@ -24,6 +24,7 @@ module Terraform
scope :ordered_by_name, -> { order(:name) }
scope :with_name, -> (name) { where(name: name) }
validates :name, presence: true, uniqueness: { scope: :project_id }
validates :project_id, presence: true
validates :uuid, presence: true, uniqueness: true, length: { is: UUID_LENGTH },
format: { with: HEX_REGEXP, message: 'only allows hex characters' }
......
......@@ -68,12 +68,14 @@ module Terraform
find_params = { project: project, name: params[:name] }
if find_only
Terraform::State.find_by(find_params) || # rubocop: disable CodeReuse/ActiveRecord
raise(ActiveRecord::RecordNotFound.new("Couldn't find state"))
else
Terraform::State.create_or_find_by(find_params)
end
return find_state!(find_params) if find_only
state = Terraform::State.create_or_find_by(find_params)
# https://github.com/rails/rails/issues/36027
return state unless state.errors.of_kind? :name, :taken
find_state(find_params)
end
def lock_matches?(state)
......@@ -86,5 +88,13 @@ module Terraform
def can_modify_state?
current_user.can?(:admin_terraform_state, project)
end
def find_state(find_params)
Terraform::State.find_by(find_params) # rubocop: disable CodeReuse/ActiveRecord
end
def find_state!(find_params)
find_state(find_params) || raise(ActiveRecord::RecordNotFound.new("Couldn't find state"))
end
end
end
---
title: Add name validation to Terraform state
merge_request: 52102
author:
type: changed
......@@ -8,8 +8,11 @@ RSpec.describe Terraform::State do
it { is_expected.to belong_to(:project) }
it { is_expected.to belong_to(:locked_by_user).class_name('User') }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_presence_of(:project_id) }
it { is_expected.to validate_uniqueness_of(:name).scoped_to(:project_id) }
describe 'scopes' do
describe '.ordered_by_name' do
let_it_be(:project) { create(:project) }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment