Joel Mellon Joel Mellon - 6 months ago 20
Python Question

How do I set the server_default for a MySQL SET in SQLAlchemy?

I've got a MySQL set column I'm describing using

sqlalchemy.dialects.mysql.SET
and I want to set the
server_default
arg to a set containing two values. I'm looking for something like this:

from sqlalchemy.dialects.mysql import SET
class MyTable(Model):
letters = Column(SET('a', 'b', 'c', 'd', 'e'), server_default=['a','b'])


If I try something as simple as the above I get:

Argument 'arg' is expected to be one of type '<class 'str'>' or '<class 'sqlalchemy.sql.elements.ClauseElement'>' or '<class 'sqlalchemy.sql.elements.TextClause'>', got '<class 'list'>'


Is there somewhere I can find a list of ClauseElements I can use?

Answer

Perhaps the best reference for different ClauseElements is "Column Elements and Expressions".

From reading "The SET Type" it seems that a common way to pass values to a SET column in MySQL is to use a (SQL) string literal with comma separated values. One way then would be to use SQLAlchemy's literal(), which produces a suitable bind parameter. You would then pass a literal string like this:

from sqlalchemy import literal
from sqlalchemy.dialects.mysql import SET

class MyTable(Model):

    letters = Column(SET('a', 'b', 'c', 'd', 'e'), server_default=literal('a,b'))