From: Ash Berlin Date: Mon, 23 Feb 2009 21:30:33 +0000 (+0000) Subject: Add a simple test for WHERE X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=4769c837a8e2873c47a2f90e96e77b161a23cf7d;p=dbsrgits%2FSQL-Abstract-2.0-ish.git Add a simple test for WHERE --- diff --git a/lib/SQL/Abstract.pm b/lib/SQL/Abstract.pm index c5eafff..7c89615 100644 --- a/lib/SQL/Abstract.pm +++ b/lib/SQL/Abstract.pm @@ -10,6 +10,9 @@ class SQL::Abstract { use Moose::Util::TypeConstraints; use MooseX::Types -declare => ['NameSeparator']; use MooseX::Types::Moose qw/ArrayRef Str/; + use MooseX::AttributeHelpers; + + use namespace::clean -except => ['meta']; subtype NameSeparator, as ArrayRef[Str]; @@ -37,15 +40,30 @@ class SQL::Abstract { required => 1, ); + has binds => ( + isa => ArrayRef, + default => sub { [ ] }, + metaclass => 'Collection::Array', + provides => { + push => 'add_bind', + get => 'binds' + } + ); + method generate (ArrayRef $ast) { $self = new $self unless blessed($self); local $_ = $ast->[0]; s/^-/_/ or croak "Unknown type tag '$_'"; - return $self->$_($ast); + my $meth = $self->can($_) || \&_generic_func; + return $meth->($self, $ast); + } + + method _select(ArrayRef $ast) { + } - method _name(ArrayRef[Str] $ast) { + method _name(ArrayRef $ast) { my (undef, @names) = @$ast; my $sep = $self->name_separator; @@ -64,7 +82,46 @@ class SQL::Abstract { return join( $self->list_separator, map { $self->generate($_) } @items); - } + method _alias(ArrayRef $ast) { + my (undef, $alias, $as) = @$ast; + + return $self->generate($alias) . " AS $as"; + + } + + method _value(ArrayRef $ast) { + my ($undef, $value) = @$ast; + + $self->add_bind($value); + return "?"; + } + + method _where(ArrayRef $ast) { + my (undef, @clauses) = @$ast; + + my @output; + + foreach (@clauses) { + my $op = $_->[0]; + + unless (substr($op, 0, 1) eq '-') { + # A simple comparison op (==, >, etc.) + croak "Binary operator $op expects 2 children, got " . $#$_ + if @{$_} > 3; + + push @output, $self->generate($_->[1]), + $op, + $self->generate($_->[2]); + } + } + + return join(' ', 'WHERE', @output); + } + + method _generic_func(ArrayRef $ast) { + } + + }; diff --git a/t/001_basic.t b/t/001_basic.t index 9a6dc39..de18152 100644 --- a/t/001_basic.t +++ b/t/001_basic.t @@ -1,7 +1,7 @@ use strict; use warnings; -use Test::More tests => 3; +use Test::More tests => 5; use_ok('SQL::Abstract') or BAIL_OUT( "$@" ); @@ -16,3 +16,14 @@ is SQL::Abstract->generate( ] ), "me.id, me.foo.bar, bar", "List generator"; + +is SQL::Abstract->generate( + [ -alias => [ -name => qw/me id/], "foobar", ] +), "me.id AS foobar", + "Alias generator"; + +is SQL::Abstract->generate( + [ -where => + [ '>', [-name => qw/me.id/], [-value => 500 ] ] + ] +), "WHERE me.id > ?", "where clause";