Skip to content

Instantly share code, notes, and snippets.

@ocharles
Created July 29, 2010 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ocharles/498974 to your computer and use it in GitHub Desktop.
Save ocharles/498974 to your computer and use it in GitHub Desktop.
class Column {
has $.name;
method sql {
$.name;
}
}
class Table {
has $.name = die "The name attribute is required";
has $.columns;
method find_column (Str $name) {
$.columns.first(*.name eq $name);
}
}
class Select {
has $!predicates = [];
has $!columns = [];
has $!from;
has $.bind = [];
method from (Table $from!) {
$!from = $from;
return self;
}
method where (Str $column, Str $operator, $value) {
my $column_obj = $!from.find_column($column)
or die "$!from.name() does not have a column called $column.";
$!predicates.push("$column_obj.sql() $operator ?");
$!bind.push($value);
return self;
}
method sql {
my $sql = "SELECT $!columns.map(*.sql).join(', ') FROM $!from.name()";
if $!predicates.elems {
$sql ~= " WHERE $!predicates.join(' AND ')";
}
return $sql;
}
multi method select (*@columns) {
$!columns.push(@columns.map: { $!from.find_column($_) });
return self;
}
multi method select (Table $table) {
$!columns.push($table.columns);
return self;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment