I'm using ORM and I've defined a unique constraint on a column, and I want to prevent inserting another row with the same value for that column. For example if you don't want 2 users with the same name.
One way to prevent it would be to take the provided name and query the user table to see if anyone has that name, and if not then insert the record. The problem with this is that in between checking for the name and inserting the name, someone else could have inserted a record with that name. So is there any advantage to doing this? Is there any better way to do it?
If not, I suppose you'd want to handle the IntegrityError that SQLAlchemy throws when it detects a unique constraint violation. But since IntegrityError handles several types of types of violations, would checking the string of the error message be the only way to ensure you're handling the correct error condition, so that you can put a specific message like "A user with that name already exists"?
sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates unique constraint "name_of_constraint"
If so, how can I use metadata to get the name of the particular constraint I have in mind, so that I can search for it in the error message string? I've tried looking through the MetaData API and have got this far but I am stuck. I can't seem to find the constraint name set on the name column here.
Base.metadata.tables.user.c.name
User.name.info