diff --git a/app/helpers/database_helper.rb b/app/helpers/database_helper.rb index e65ebe285..f84089728 100644 --- a/app/helpers/database_helper.rb +++ b/app/helpers/database_helper.rb @@ -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 diff --git a/lib/tasks/sign_up_constraint.rake b/lib/tasks/sign_up_constraint.rake index d8953e662..11e0399cd 100644 --- a/lib/tasks/sign_up_constraint.rake +++ b/lib/tasks/sign_up_constraint.rake @@ -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