#!/usr/local/bin/perl use strict; use DBI; my $db_file = 'database.db'; package MyDbase::DBI; use base 'Class::DBI'; sub connect { DBI->connect("dbi:SQLite:dbname=$db_file","",""); } if (!-e $db_file) { my $db = &connect; $db->do(q{ CREATE TABLE user ( handle STRING PRIMARY KEY, password STRING, session INTEGER )}); $db->do(q{ CREATE TABLE session ( id STRING PRIMARY KEY, timestamp INTEGER )}); } package MyDbase::Session; use base 'MyDbase::DBI'; MyDbase::Session->table('session'); MyDbase::Session->columns(All => qw/id timestamp/); MyDbase::DBI->set_db('Main',"dbi:SQLite:dbname=$db_file","",""); package MyDbase::User; use base 'MyDbase::DBI'; MyDbase::User->table('user'); MyDbase::User->columns(All => qw/handle password session/); MyDbase::User->has_a(session => 'MyDbase::Session'); MyDbase::DBI->set_db('Main',"dbi:SQLite:dbname=$db_file","",""); package main; MyDbase::DBI->connect; my $session_id = 'aaa'; my $user_rec = { 'handle' => 'a', 'password' => crypt('a','a'), }; # is this a requirement or can both records be created at once? #my $session_rec = MyDbase::Session->insert({ my $session_rec = { 'id' => $session_id, 'timestamp' => time, }; #}); $user_rec->{'session'} = $session_rec; MyDbase::User->insert($user_rec);
The error produced is:
Can't deflate session: HASH(0x84ee954) is not a MyDbase::Session at /u +sr/local/lib/perl5/site_perl/5.8.5/Class/DBI/Relationship/HasA.pm lin +e 86
This error goes away if I used the commented out code (using a MyDbase::Session object instead of a hash).
However, doing it that way hits the database twice instead of once.

My question is how to do this insert with a single database access.
Thanks in advance :)


In reply to Inserting a relation into a database with Class::DBI by wojtyk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.