3

I'm using sqlalchemy_utils to add a "choices" field to my database. And after I ran my migrate using Flask Migrate, it converts all my choices into 255, below is a simplified example:

# models.py
from sqlalchemy_utils.types.choice import ChoiceType

class Stuff(db.Model):
    type = db.Column(ChoiceType(Stuff_types))

After running manage.py migrate, the migration file looks like:

# /migrations/versions/1234migrate.py
import sqlalchemy_utils

def upgrade():
    sa.Column('type', sqlalchemy_utils.types.choice.ChoiceType(length=255), nullable=False),

I manually changed those length=255 into the correct types(in this case stuff_types), and it worked. I wonder if I did not set up alemic correctly to work with sqlalchemy_utils. Or if there is a better solution that I'm not aware of?

Thanks guys!

benjaminz
  • 3,118
  • 3
  • 35
  • 47
  • What do you mean by "correct types"? Why shouldn't the length be 255? – dirn Oct 30 '15 at 21:53
  • @dirn for example, tuples of choices like ('stuff1', 'Stuff One'), ('stuff2', 'Stuff Two) – benjaminz Oct 30 '15 at 22:05
  • 1
    All of those will fit into a 255 character field. What is the exact problem you were running into? Did you get an error running the migration? Did you get an error inserting into the field? – dirn Oct 30 '15 at 22:17
  • @dirn yes there was error, because this field is suppose to be a `ChoiceField`, not a `StringField`, and the `length=255` argument is for `StringField`. – benjaminz Nov 02 '15 at 18:05
  • Databases don't always have a field that can handle choices (e.g., enums). SQLAlchemy will store the value in a string-based field. Unless you are getting an exception due to Alembic's use of `StringField`, your model should work as you expect it to. – dirn Nov 02 '15 at 18:08
  • @dirn Unfortunately that is not the case, and when I manually change the `length=255` back to the choices tuples, the migration's upgrade was successfully executed. – benjaminz Nov 02 '15 at 18:19
  • [It looks like sqlalchemy-util's custom types aren't supported by Alembic](https://github.com/kvesteri/sqlalchemy-utils/issues/129). – dirn Nov 02 '15 at 18:24
  • @dirn yeah that's my guess. Maybe I'll just write up some scripts to clean up this mess for future references... Thanks anyway! – benjaminz Nov 02 '15 at 21:34

1 Answers1

0

Yeah I dont get this fully with Alembic. What worked for me is going into the created migration file in alembic > versions and editing it.

In my case I has a array of TYPES and I added that to the upgrade function, since Alembic didn't seem to do it. I them replaced the length=255 with 'TYPES' and it was all good

kayuzee
  • 75
  • 5