My favorites | Sign in
Project Home Downloads Wiki Issues Source
Project Information
Members

Validations for SQLAlchemy

SQLAlchemy validations is an easy way to be sure that no inconsistent data will be saved to your database. It is a new extension for SQLAlchemy that checks if an object is consistent according to a customizable set of rules just before being saved to the database.

Example

You have a Person class:

class Person(object):
    def __init__(self, name, phone, age):
        self.name = name
        self.phone = phone
        self.age = age

    def __repr__(self):
        return "<Person('%s','%s','%d')>" % (self.name, self.phone, self.age)

Now, we will map it to a person_table (declaration of person_table omitted. See SQLAlchemy docs for more about mapping):

mapper(Person, person_table,
       extension=[
                  Validator(range_of('age', 0, 150))
                 ]
      )

The mapper call above is specifying a range validator for the age attribute of Person. Now, if you try to save a Person with age outside of range 0-150 it will raise a ValidationException and no data will be saved:

>>> p = Person('Foobar', '0123456789', 1000) # age = 1000
>>> session.save(p)
>>> session.flush()

(traceback omitted)

<class 'sqlalchemy_validators.ValidationException'>: Range validation of field "age" of instance of class "Person" failed! Person.age = 1000 (min=0, max=150)

You can also add a second validation:

mapper(Person, person_table,
       extension=[Validator(
                            range_of('age', 0, 150),
                            format_of('phone', re.compile(r'\d{4}-?\d{4}'))
                           )
                 ]
      )

The mapper call adds a second validation to Person class. Now its phone attribute must match the format specified by the regular expression.

Using Elixir

Elixir validations are similar to SQLAlchemy validations, but use a syntax similar to Ruby on Rails ActiveRecord.

The class below implements the same validations of the previous example, but using Elixir.

class Person(Entity):
    name  = Field(Text)
    phone = Field(Text)
    age   = Field(Integer)
        
    validates_format_of('phone', re.compile(r'\d{4}-?\d{4}'))
    validates_range_of('age', 0, 150)

Creating new validators

sqlalchemy-validations is extensible. You can create new validations, inheriting from Validation class in sqlalchemy_validations.py. Take a look at classes FieldFormatValidation and FieldPresenceValidation. They should serve as good examples of how to create your own validations.

Powered by Google Project Hosting