sub insert_unique( $table, $column, $value ) { state %sths; if ( !exists $sths{$table} ) { $sths{$table}{SELECT} = $dbh->prepare("SELECT id FROM $table WHERE $column = (?)"); $sths{$table}{INSERT} = $dbh->prepare("INSERT INTO $table ($column) VALUES (?) RETURNING id"); } my $rowid; my $sth = $sths{$table}{SELECT}; $sth->execute($value); my $rows = $sth->fetchall_arrayref( {} ); if ($rows->@*) { $rowid = $rows->[0]->{id}; } else { $sth = $sths{$table}{INSERT}; $sth->execute($value); $rows = $sth->fetchall_arrayref( {} ); $rowid = $rows->[0]->{id}; } return $rowid; }