Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy 0.7 - maximum column length

I am using SQLAlchemy maximum column length recipe from my previous question (SQLAlchemy - maximum column length). Since I upgraded to SQLAlchemy 0.7, the LengthValidator cannot be installed using the following expression:

inst.impl.extensions.insert(0, LengthValidator(col.type.length))

The extension attribute is not defined in SQLAchemy 0.7. Is there any way how to change the recipe to work with 0.7?

like image 593
honzas Avatar asked Dec 22 '22 07:12

honzas


2 Answers

Below is Ants' solution rewritten with event system of SQLAlchemy:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import ColumnProperty
from sqlalchemy import event

def check_string_length(cls, key, inst):
    prop = inst.prop
    # Only interested in simple columns, not relations
    if isinstance(prop, ColumnProperty) and len(prop.columns) == 1:
        col = prop.columns[0]
        # if we have string column with a length, install a length validator
        if isinstance(col.type, String) and col.type.length:
            max_length = col.type.length
            def set_(instance, value, oldvalue, initiator):
                if len(value)>max_length:
                    raise ValueError("Length %d exceeds allowed %d" % \
                                            (len(value), max_length))
            event.listen(inst, 'set', set_)

Base = declarative_base()

event.listen(Base, 'attribute_instrument', check_string_length)
like image 168
Denis Otkidach Avatar answered Dec 28 '22 09:12

Denis Otkidach


You can use sqlalchemy.orm.validates decorator:

@validates('name')
def validate_name(self, key, name):
    assert len(name) <= 50
    return name
like image 39
Alexander Solovyov Avatar answered Dec 28 '22 08:12

Alexander Solovyov