Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks.
I am using the Class::DBI module for database operations. When I am using the following code snippet. I am calling cddata::addUsers method i am getting error.
Error :: "Can't create autocd::users object with null primary key columns () at /var/www/lib/autocd/cddata.pm "
package cddata; ##cddata.pm use autocd::users; sub addUser($ $){ my $username = shift; my $rolename = shift; my $roleid=autocd::roles->search(rolename => $rolename); if (!$roleid || !$username){ return ""; } return autocd::users->insert({ roleid => $roleid, username=$user +name}); } Users Table Def: _______________ +----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+----------------+ | userid | int(10) | NO | PRI | NULL | auto_increment | | roleid | int(10) | NO | | | | | username | varchar(200) | NO | | | | +----------+--------------+------+-----+---------+----------------+ package autocd::users; ##users.pm use base 'autocd::autocd'; autocd::users->table('Users'); autocd::users->columns(Primary => qw/userid/); autocd::users->columns(Essential => qw/roleid username/);

I am getting "Can't create autocd::users object with null primary key columns () at /var/www/lib/autocd/cddata.pm " error.
I am using mysql 5.1.
Please help me to resolve this error. Thanks,

Replies are listed 'Best First'.
Re: Class::DBI insert error
by Corion (Patriarch) on Jan 21, 2008 at 07:13 UTC

    Whatever autocd is, you don't tell us. From the "table definition" you posted, it seems as if userid was declared as PRIMARY KEY NOT NULL AUTOINCREMENT which should be a hint to MySQL to make this an automatic primary key. Maybe you can enable the DBI logging and look at what SQL gets sent to MySQL:

    DBI->trace(99);

    Update: Now, reading the title you gave to your question, I realize that you're talking about Class::DBI and thus your autocd class likely is a subclass of Class::DBI. It would then likely help to see the (Class::DBI-setup-)part of autocd too.

Re: Class::DBI insert error
by rhesa (Vicar) on Jan 21, 2008 at 10:59 UTC
    In scalar context, search() returns an iterator. You can't use that as a record value.

    Either do:

    # Note the braces to force list context on the left hand side my ($roleid) = autocd::roles->search(rolename => $rolename);

    or

    my $role_iter = autocd::roles->search(rolename => $rolename); if (!$role_iter->count || !$username){ return ""; } my $roleid = $role_iter->first;

    I'd go for the first option.

Re: Class::DBI insert error
by perrin (Chancellor) on Jan 21, 2008 at 22:19 UTC
    In addition to the pointer you got about using search(), I'd suggest you get rid of that prototype on your AddUser method. Prototypes are nearly always a mistake with perl. They don't do argument checking.