{"action":"opened","issue":{"url":"https://api.github.com/repos/OpenFn/core/issues/142","labels_url":"https://api.github.com/repos/OpenFn/core/issues/142/labels{/name}","comments_url":"https://api.github.com/repos/OpenFn/core/issues/142/comments","events_url":"https://api.github.com/repos/OpenFn/core/issues/142/events","html_url":"https://github.com/OpenFn/core/issues/142","id":128832127,"number":142,"title":"Create uniqueness constraint on user email","user":{"login":"taylordowns2000","id":8732845,"avatar_url":"https://avatars.githubusercontent.com/u/8732845?v=3","gravatar_id":"","url":"https://api.github.com/users/taylordowns2000","html_url":"https://github.com/taylordowns2000","followers_url":"https://api.github.com/users/taylordowns2000/followers","following_url":"https://api.github.com/users/taylordowns2000/following{/other_user}","gists_url":"https://api.github.com/users/taylordowns2000/gists{/gist_id}","starred_url":"https://api.github.com/users/taylordowns2000/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/taylordowns2000/subscriptions","organizations_url":"https://api.github.com/users/taylordowns2000/orgs","repos_url":"https://api.github.com/users/taylordowns2000/repos","events_url":"https://api.github.com/users/taylordowns2000/events{/privacy}","received_events_url":"https://api.github.com/users/taylordowns2000/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"milestone":null,"comments":0,"created_at":"2016-01-26T14:17:32Z","updated_at":"2016-01-26T14:17:32Z","closed_at":null,"body":"You want to use unique_constraint/3. This is not like Active Record because it is using the database to ensure uniqueness. Active Record would do a query for records with the same value and if any were returned then it would fail. This has a race condition where, if a value is inserted between fetching to check uniqueness and inserting your record, you will either end up with duplicate data or an error being raised (depending on if an index is set on the database or not. unique_constraint/3 does not have this race condition.\r\n\r\nOne thing worth noting is that since the uniqueness is not known until an insert is attempted, the unique constraint will happen after your validations. It is not possible to display both validation and constraint errors at once.\r\n\r\nThe database you are using must support unique constraints too. They won't work with SQLite. You can read more on the GitHub issue.\r\n\r\nIn your migration:\r\n\r\ncreate unique_index(:users, [:email])\r\nThen in your model:\r\n\r\ncast(user, params, ~w(email), ~w())\r\n|> unique_constraint(:email)"}}