~free.ekanayaka/storm/any-expr

« back to all changes in this revision

Viewing changes to storm/expr.py

  • Committer: James Henstridge
  • Date: 2009-11-02 12:30:44 UTC
  • mfrom: (329.4.5 storm.bug-387840)
  • Revision ID: james@jamesh.id.au-20091102123044-t5do87h5jd52i09i
Add startswith(), endswith() and contains_string() methods to Comparable.

[r=jkakar,jdo] [f=387840]

Show diffs side-by-side

added added

removed removed

Lines of Context:
395
395
    raise CompileError("Can't compile python expressions with %r" % type(expr))
396
396
 
397
397
 
 
398
# A translation table that can escape a unicode string for use in a
 
399
# Like() expression that uses "!" as the escape character.
 
400
like_escape = {
 
401
    ord(u"!"): u"!!",
 
402
    ord(u"_"): u"!_",
 
403
    ord(u"%"): u"!%"
 
404
    }
 
405
 
 
406
 
398
407
class Comparable(object):
399
408
    __slots__ = ()
400
409
 
498
507
    def upper(self):
499
508
        return Upper(self)
500
509
 
 
510
    def startswith(self, prefix):
 
511
        if not isinstance(prefix, unicode):
 
512
            raise ExprError("Expected unicode argument, got %r" % type(prefix))
 
513
        pattern = prefix.translate(like_escape) + u"%"
 
514
        return Like(self, pattern, u"!")
 
515
 
 
516
    def endswith(self, suffix):
 
517
        if not isinstance(suffix, unicode):
 
518
            raise ExprError("Expected unicode argument, got %r" % type(suffix))
 
519
        pattern = u"%" + suffix.translate(like_escape)
 
520
        return Like(self, pattern, u"!")
 
521
 
 
522
    def contains_string(self, substring):
 
523
        if not isinstance(substring, unicode):
 
524
            raise ExprError("Expected unicode argument, got %r" % type(substring))
 
525
        pattern = u"%" + substring.translate(like_escape) + u"%"
 
526
        return Like(self, pattern, u"!")
 
527
 
501
528
 
502
529
class ComparableExpr(Expr, Comparable):
503
530
    __slots__ = ()