Refactor & fix sign up constraints

This commit is contained in:
Luka Murn 2016-11-29 16:53:40 +01:00
parent f9c8223fe5
commit 6491cf1806
2 changed files with 25 additions and 15 deletions

View file

@ -1,5 +1,4 @@
module DatabaseHelper
# Check if database adapter equals to the specified name
def db_adapter_is?(adapter_name)
ActiveRecord::Base.connection.adapter_name == adapter_name
@ -22,7 +21,7 @@ module DatabaseHelper
# Create gist trigram index. PostgreSQL only!
def add_gist_index(table, column)
ActiveRecord::Base.connection.execute(
"CREATE INDEX index_#{table}_on_#{column} ON " +
"CREATE INDEX index_#{table}_on_#{column} ON " \
"#{table} USING gist (#{column} gist_trgm_ops);"
)
end
@ -49,21 +48,30 @@ module DatabaseHelper
# in table for specific id. PostgreSQL only!
def get_octet_length(table, column, id)
ActiveRecord::Base.connection.execute(
"SELECT octet_length(cast(t.#{column} as text)) FROM #{table} " +
"SELECT octet_length(cast(t.#{column} as text)) FROM #{table} " \
"AS t WHERE t.id = #{id};"
).getvalue(0, 0).to_i
end
# Adds email domain constraint to the users table.
def add_email_constraint(domain)
# Adds a check constraint to the table
def add_check_constraint(table, constraint_name, constraint)
ActiveRecord::Base.connection.execute(
"ALTER TABLE " \
"users " \
"DROP CONSTRAINT IF EXISTS email_must_be_company_email, " \
"#{table} " \
"DROP CONSTRAINT IF EXISTS #{constraint_name}, " \
"ADD CONSTRAINT " \
"email_must_be_company_email " \
"CHECK ( email ~* '^[A-Za-z0-9._%-]+@#{domain}' ) " \
"#{constraint_name} " \
"CHECK ( #{constraint} ) " \
"not valid;"
)
end
# Remove constraint from the table
def drop_constraint(table, constraint_name)
ActiveRecord::Base.connection.execute(
"ALTER TABLE " \
"#{table} " \
"DROP CONSTRAINT IF EXISTS #{constraint_name}; "
)
end
end

View file

@ -14,17 +14,19 @@ namespace :sign_up_constraint do
domain = args[:domain]
domain = domain.strip.gsub(/\./, '\\.')
add_email_constraint(domain)
add_check_constraint(
'users',
'email_must_be_company_email',
"email ~* '^[A-Za-z0-9._%-+]+@#{domain}'"
)
puts "Created the following domain constraint: #{args[:domain]}"
end
desc 'Remove email domain constraint from the users table.'
task remove_domain: :environment do
ActiveRecord::Base.connection.execute(
'ALTER TABLE ' \
'users ' \
'DROP CONSTRAINT IF EXISTS email_must_be_company_email; '
)
include DatabaseHelper
drop_constraint('users', 'email_must_be_company_email')
puts 'Email constraint has been removed'
end
end