2

I am using PostgreSQL and Alembic for migration. When I added new column to my User table Alembic generated migration with the following script:

from alembic import op
import sqlalchemy as sa
import random

def generate_toke():
    return random.random()

def upgrade():
    op.add_column('user', sa.Column('token', sa.String(), nullable=True ))
    op.execute('some code here')

What I actually want to do is autogenerating the value of token by the generate_toke function.How can I achieve the goal

bin381
  • 342
  • 1
  • 4
  • 14

1 Answers1

2

The problem is random.random() is a python-side function. alembic turns those operations to sql and then executes them. One way would be to add a server_default and use postgres random() function to generate the token:

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('user', sa.Column(
        'token', 
        sa.String(), 
        server_default=sa.text("random()"), 
        nullable=True ))
    op.execute('some code here')
Sam R.
  • 16,027
  • 12
  • 69
  • 122