morgon has asked for the wisdom of the Perl Monks concerning the following question:
I am trying to persist Moose-objects via DBIx::Class in an Oracle database.
This is the first time ever that I use DBIx::Class so any hints would be very welcome...
As a simple example my class has 3 attributes, "id" as integer (which will be used as primary key in the table) and two string-attributes "a" and "b".
Here is the table I want my objects to be persisted in:
The I create a Schema-class like this:create table hubba (id int, a varchar2(20), b varchar2(20));
Then I implement my class like this:package SMU::Schema; use base qw(DBIx::Class::Schema); __PACKAGE__->load_namespaces; 1;
So now I can save/retrive data like this:package SMU::Schema::Result::Hubba; use DBIx::Class; use Moose; extends 'DBIx::Class'; has 'id' => ( is => "ro", isa => "Int"); has 'a' => ( is => "rw", isa => "Str"); has 'b' => ( is => "rw", isa => "Str"); sub dump { my($this)=@_; return $this->id . " - " . $this->a . " - " . $this->b; } __PACKAGE__->load_components('Core'); __PACKAGE__->table('hubba'); __PACKAGE__->add_columns( id => { data_type => 'integer', size => 16 }, a => { data_type => 'varchar', size => 20 }, b => { data_type => 'varchar', size => 20 }, ); __PACKAGE__->set_primary_key('id'); 1;
While the above works, there are a lot of things that I don't like about it very much.my $schema = SMU::Schema->connect("dbi:Oracle:SMU", "user", "pw") or d +ie $!; # find row with id=1 and return as object my $h1 = $schema->resultset('Hubba')->find(1); # persist new object $schema->resultset('Hubba')->create( { id => 2, a => "blah", b => "blubb", });
For a start Moose generates a "new"-constructor while DBIx::Class uses a "create"-constructor. While I can use the DBIx::Class constructor to get back an instance of my Moose-class, for whatever reason I don't seem to be able to use the Moose-constructor any more (calling e.g. SMU::Schema::Result::Hubba->new(id => 1) results in an error).
But ok I could live with this.
What I dislike the most is that in my class-implementation I basically have to tell Moose about the attributes (via "has") as well as DBIx::Class (via add_columns). Now you may argue that this is not quite the same thing (and I would agree) but I wonder if there is some MooseX::?? extension that would allow me to map my attributes to columns via some trait or the like ... the above just looks very clumsy to me.
I would be very grateful for anyone that could show me a better way of persisting a simple Moose-object in a database via DBIx::Class.
Many thanks!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: DBIx::Class and Moose
by Corion (Patriarch) on Apr 14, 2009 at 16:12 UTC | |
|
Re: DBIx::Class and Moose
by Raster Burn (Beadle) on Apr 15, 2009 at 18:54 UTC | |
by morgon (Priest) on Apr 15, 2009 at 20:38 UTC |