All about

To enforce a specific format for the string stored in update_user using SQLAlchemy, you can utilize methods such as CheckConstraint or server_default to validate the data and perform transformations if necessary.

For instance, you can use CheckConstraint along with a regular expression to validate the format.

from sqlalchemy import Column, String, create_engine, CheckConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'my_table'
    
    user_id = Column(String(36), nullable=False, server_default='', comment="User ID")
    
    # Regular expression for validation
    __table_args__ = (
        CheckConstraint("user_id ~ '^[a-f0-9-]{36}$'", name='valid_user_id'),
    )

# Configure to use an SQLite in-memory database
engine = create_engine('sqlite:///:memory:')

# Create the table
Base.metadata.create_all(engine)

# Create a session
Session = sessionmaker(bind=engine)
session = Session()

# Case where validation fails
new_data = MyTable(user_id='invalid_format')
session.add(new_data)

try:
    session.commit()
except Exception as e:
    print(f"Error: {e}")
    session.rollback()

# Case where validation succeeds
new_data = MyTable(user_id='valid-format-12345')
session.add(new_data)
session.commit()

# Verify the validated data in the database
result = session.query(MyTable).first()
print(result.user_id)

 

In this example, CheckConstraint is used to ensure that the user_id value adheres to a specific regular expression. The server_default is used to set a default value when assigning a value to this field.

Keep in mind that the effectiveness of this approach may depend on the database engine, as some engines may not support regular expressions. In certain cases, validation at the application level may be required.

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading