Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define minimum length for PostgreSQL string column with SQLAlchemy

I'm defining an PostgreSQL table using an SQLAlchemy declarative base, like this:

from sqlalchemy import Column, String, BigInteger
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    id = Column('id', BigInteger, primary_key=True)
    some_string = Column('some_string', String(256), nullable=False)

The nullable constraint guarantees that some_string cannot be null. However, I'd additionally like to give some_string a minimum length, or just forbid it from being the empty string. How can I do this?

like image 230
Mark Amery Avatar asked May 04 '18 11:05

Mark Amery


1 Answers

Ideally we want the validation to be applied both at the database layer via a constraint and also in our model by rejecting attempts to set the property to a string that's too short even before trying to save it to the database. We can do the former with a CheckConstraint using the char_length function, and the latter by adding a validator. Below is an example that enforces a minimum length of 3 characters on some_string:

from sqlalchemy import Column, String, BigInteger
from sqlalchemy.schema import CheckConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import validates
Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    id = Column('id', BigInteger, primary_key=True)
    some_string = Column('some_string', String(256), nullable=False)

    __table_args__ = (
        CheckConstraint('char_length(some_string) > 2',
                        name='some_string_min_length'),
    )

    @validates('some_string')
    def validate_some_string(self, key, some_string) -> str:
        if len(some_string) <= 2:
            raise ValueError('some_string too short')
        return some_string
like image 173
Mark Amery Avatar answered Oct 21 '22 13:10

Mark Amery