Question

I'm using Perl DBI with PostgreSQL, and my users will be deleting rows from a table, some of which can't be deleted because of foreign key constraints, which is fine, but I want a way to mark those rows on the front end so that it's known which rows have constraints before trying to delete them. Right now, a user would just hit "delete" and would either get an error or have the row deleted.

Was it helpful?

Solution 2

So I figured it out on my own. For anyone in a similar situation, you can turn on transactions

$dbh->{AutoCommit} = 0;

And then try to delete the row, like this for example…

my $sth = $dbh->prepare("DELETE FROM auth_users WHERE username = ?");
$sth->execute($username);

And then check for an error...

if ( $sth->err ) { print "CAN'T be deleted.";}
else { print "CAN be deleted.";}

And then just roll back to not commit to the delete in case it could be deleted…

$dbh->rollback;

This is what works for me. If anyone has any better ideas, or some concerns with this method, feel free to share.

OTHER TIPS

I'm not terribly familiar with PostgreSQL, but I believe you can use:

SELECT * 
FROM information_schema.table_constraints 
WHERE table_name = 'YourTable'

Update- Looks like a solid answer here: Postgres: SQL to list table foreign keys

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top