On Sunday, February 15, 2015 at 1:23:57 PM UTC-8, Matt Palmer wrote:
>
> On Sun, Feb 15, 2015 at 08:53:28AM -0800, Jeremy Evans wrote: 
> > On Sunday, February 15, 2015 at 12:52:27 AM UTC-8, Matt Palmer wrote: 
> > > Long version: 
> > > 
> > > I tried to define a where clause which contained a modulus 
> calculation, 
> > > like 
> > > so: 
> > > 
> > >     db[:ex].where { col % 3 == 0 } 
> > > 
> > > Much to my surprise, this bombed, telling me 
> > > 
> > >     NoMethodError: undefined method `%' for #<Sequel::SQL::Identifier 
> > > @value=>:col> 
> > > 
> > 
> > This is wrong in two places.  First, equality is done via hashes, 
> second, 
> > the modulus operator is only defined for columns known to be numeric. 
> > 
> >   db[:ex].where{{col.sql_number % 3 => 0}} 
>
> Fair enough.  Why does modulo need to be called against a numeric column, 
> while the other arithmetic-only operators can be applied to anything?  I 
> get 
> why '+' is valid for strings (nice one, by the way), but the others aren't 
> valid Ruby for Strings. 
>

Mostly because it is less common.  It's defined in BitwiseMethods, which is 
only included in NumericExpression by default.   Some of the BitwiseMethods 
overlap with the BooleanMethods that are included in GenericExpression.

Not all databases support modulus for all numeric types.  For example, 
SQLite doesn't appear to support modulus for floating point numbers, always 
returing NULL.  The reason it's defined in BitwiseMethods is it is mostly 
useful for integers (just like the bitwise operators), not for other 
numeric types.

If you want, you can define the % method in NumericMethods if you want it 
to be available for most expression objects:

  Sequel::SQL::NumericMethods.send(:define_method, :%, 
Sequel::SQL::BitwiseMethods.instance_method(:%))

Note that % is already defined for Sequel::LiteralString, which includes 
NumericMethods but not BitwiseMethods, so defining % in NumericExpression 
can affect backwards compatibility.

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.

Reply via email to