In code I'm working on at present I have two classes of interest. One class is intended for creating a single instance from that manages the database connection. The second class is the base class for a bundle of classes that mediate access to different tables in the database.
The table accessors don't require a connection at create time and can do a limited range of stuff without a connection being provided, but they die if you try to use them in a way that would require a connection and you've not provided one yet. That allows a Task object to be created for example with a bunch of task information, then handed over to a scheduler that gets the task queued (added to the task table).
The table object base class provides members to insert a derived instance into its table and to update/fetch/delete entries matching various criteria. The base class will also create the table for a derived class if the table doesn't exist (the derived class provides a column spec). Typical derived class code looks like:
package Job;
require Exporter;
our @ISA = ('DBObject');
our @EXPORT = qw( );
my $jobTableDef = ['jobs', # Job specifications
'id INTEGER PRIMARY KEY NOT NULL,
command VARCHAR(1024) NOT NULL,
maxrunmins INTEGER,
numruns INTEGER,
runtimetotal INTEGER,
flags VCHAR(20)
'
];
sub new {
my ($class, %params) = @_;
$params{flags} = '' unless exists $params{flags};
return DBObject::new ($class, %params, tableDef => $jobTableDef);
}
1;
and typical usage looks like:
sub CheckTasks {
my $self = shift;
my $task = Task->new (dbh => $self->{db});
my @readyTasks = $task->getOldest ();
if (@readyTasks) {
my $taskInfo = $task->fetch (id => $readyTasks[0][0]);
my $job = Job->new (dbh => $self->{db});
my $jobInfo = $job->fetch (id => $taskInfo->{jobid});
DWIM is Perl's answer to Gödel
|