0

In first migration I create table:

from alembic import op
import sqlalchemy as sa

revision = 'ab45c3e5334d'
down_revision = None
branch_labels = None
depends_on = None

def upgrade() -> None:
    op.create_table('parts',
    sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
    sa.Column('part', sa.String(length=3), nullable=False),
    sa.Column('results_count', sa.Integer(), nullable=True),
    sa.Column('requested_date', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('part')
    )

def downgrade() -> None:
    op.drop_table('parts')

In second migration I add data to table:

from alembic import op
import sqlalchemy as sa

revision = '2452b817db12'
down_revision = 'ab45c3e5334d'
branch_labels = None
depends_on = None

def upgrade() -> None:
    meta = sa.MetaData()
    table = sa.Table('parts', meta)

    op.bulk_insert(
        table,
        [
            {'part': 'foo'}
        ]
    )

def downgrade() -> None:
    pass

But it raise error:

sqlalchemy.exc.IntegrityError: (psycopg2.errors.NotNullViolation) null value in column "part" violates not-null constraint?
[SQL: INSERT INTO parts DEFAULT VALUES]

If I create column with nullable=True:

sa.Column('part', sa.String(length=3), nullable=True),

then not error but in database I see new row with part is null.

Why column part don't have value?

Kirill
  • 1
  • I think maybe bind your metadata, like this `meta = sa.MetaData(bind=op.get_bind())`, here is another similar answer https://stackoverflow.com/questions/50626928/how-to-instantiate-a-table-object-to-bulk-insert-rows-using-alembic-sqlalchemy – Ian Wilson Nov 25 '22 at 05:33
  • Actually, I'm not sure about that either, the docs show a table without the metadata at all: [op.bulk_insert](https://alembic.sqlalchemy.org/en/latest/ops.html#alembic.operations.Operations.bulk_insert) – Ian Wilson Nov 25 '22 at 05:35

0 Answers0