GrandFather has asked for the wisdom of the Perl Monks concerning the following question:
As part of a scheduling project I need to retrieve "active sessions" for selected people. For each session a person may be the teacher or learner. I have code (see getActiveSessions) that retrieves the data I want from the Sessions table in a SQLite database. However the duplication if the id list to be matched smells somewhat to me. Can you come up with a tidy alternative that avoids duplicating the id list?
A test script that reflects the current code is given below:
use strict; use warnings; use DBI; my $dbh = DBI->connect('dbi:SQLite:dbname=xr.SQLite'); $dbh->do(<<SQL); CREATE TABLE Sessions ( SessId INTEGER PRIMARY KEY AUTOINCREMENT, TeacherId INTEGER, LearnerId INTEGER, DoneDate TEXT, Topic TEXT ) SQL my $self = bless {dbh => $dbh}; $self->addSession(1, 2, 'Perl is fun', '2015-06-27'); $self->addSession(3, 4, 'SQL is fun', '2015-06-27'); $self->addSession(3, 5, 'SQL for fun and profit', '2015-06-20'); $self->addSession(4, 1, 'PerlMonks is great', '2015-06-20'); $self->addSession(2, 6, 'PerlMonks is great', '2015-06-20'); my $active = $self->getActiveSessions(1, 2); print "$_->{TeacherId}, $_->{LearnerId}: '$_->{Topic}'\n" for values %$active; sub addSession { my ($self, $teacher, $learner, $topic) = @_; $self->{dbh}->do(<<SQL, {}, $teacher, $learner, $topic); INSERT INTO Sessions (TeacherId, LearnerId, Topic, DoneDate) VALUES (?, ?, ?, '') SQL } sub getActiveSessions { my ($self, @ids) = @_; my $idPlaces = (join ', ', ('?') x @ids) || ''; $idPlaces = <<SQL if $idPlaces; AND (TeacherId IN ($idPlaces) OR LearnerId IN ($idPlaces)) SQL return $self->{dbh}->selectall_hashref(<<SQL, 'SessId', {}, @ids, +@ids); SELECT SessId, TeacherId, LearnerId, Topic FROM Sessions WHERE DoneDate == ''$idPlaces SQL }
Prints:
4, 1: 'PerlMonks is great' 1, 2: 'Perl is fun' 2, 6: 'PerlMonks is great'
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Avoiding SQL double jeopardy
by graff (Chancellor) on Jun 27, 2015 at 02:22 UTC | |
by NetWallah (Canon) on Jun 27, 2015 at 04:28 UTC | |
by GrandFather (Saint) on Jun 27, 2015 at 05:55 UTC | |
by GrandFather (Saint) on Jun 27, 2015 at 05:52 UTC | |
by Pope-O-Matik (Pilgrim) on Jun 28, 2015 at 03:55 UTC | |
by GrandFather (Saint) on Jun 28, 2015 at 05:08 UTC | |
by Pope-O-Matik (Pilgrim) on Jun 28, 2015 at 09:25 UTC | |
| |
by Pope-O-Matik (Pilgrim) on Jun 28, 2015 at 03:23 UTC | |
|
Re: Avoiding SQL double jeopardy
by 1nickt (Canon) on Jun 28, 2015 at 05:17 UTC | |
by GrandFather (Saint) on Jun 28, 2015 at 06:17 UTC | |
|
Re: Avoiding SQL double jeopardy
by Anonymous Monk on Jun 27, 2015 at 04:01 UTC |