perldbix-class

DBIx::Class how to retrieve generated UUID on create?


I have an application that uses DBIx::Class, currently when I create an object that corresponds to a table I get back the object but the id column will be set to 0 instead of to the UUID that's generated on the database level. How can I properly retrieve the id column when I create a new record?

Here is my table:

CREATE TABLE IF NOT EXISTS log (
    id VARCHAR(36) DEFAULT (UUID()) PRIMARY KEY,
    ...

Here is my DBIx::Class schema:

__PACKAGE__->load_components(qw/InflateColumn::DateTime PK::Auto Core/);

__PACKAGE__->table('log');
__PACKAGE__->add_columns(
    id => {
        data_type         => 'varchar',
        size              => 36,
        unique            => 1,
        is_auto_increment => 1
    },
    qw/.../ # other columns
);
__PACKAGE__->set_primary_key('id');

When I go to insert, like (log_repository is my resultset):

my $log = $self->log_repository->create($json);

print $log->get_column('id'); # 0 instead of valid UUID

How can I retrieve the UUID on create?


Solution

  • I found one way to solve it, though it isn't pretty, and far from what i'd like to do, it works.

    In my ResultSet classes, I over-wrote the create method to append a pre-generated UUID to the id field before executing the super-classes' create like so:

    sub create {
        my $self = shift;
        my $qry  = shift;
    
        return $self->SUPER::create( { %{$qry}, id => Data::UUID->new->create_str } );
    }
    

    Then I can call create like usual, and get the id back.