"""execution records

Revision ID: bbb12a12372e
Revises:
Create Date: 2022-09-28 18:52:16.431200

"""

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
from sqlalchemy import create_engine
from sqlalchemy.engine import reflection

from aleph.vm.conf import make_db_url

revision = "bbb12a12372e"
down_revision = None
branch_labels = None
depends_on = None


def upgrade() -> None:
    engine = create_engine(make_db_url())
    inspector = reflection.Inspector.from_engine(engine)

    # The table already exists on most CRNs.
    tables = inspector.get_table_names()
    if "records" not in tables:
        op.create_table(
            "records",
            sa.Column("uuid", sa.String(), nullable=False),
            sa.Column("vm_hash", sa.String(), nullable=False),
            sa.Column("time_defined", sa.DateTime(), nullable=False),
            sa.Column("time_prepared", sa.DateTime(), nullable=True),
            sa.Column("time_started", sa.DateTime(), nullable=True),
            sa.Column("time_stopping", sa.DateTime(), nullable=True),
            sa.Column("cpu_time_user", sa.Float(), nullable=True),
            sa.Column("cpu_time_system", sa.Float(), nullable=True),
            sa.Column("io_read_count", sa.Integer(), nullable=True),
            sa.Column("io_write_count", sa.Integer(), nullable=True),
            sa.Column("io_read_bytes", sa.Integer(), nullable=True),
            sa.Column("io_write_bytes", sa.Integer(), nullable=True),
            sa.Column("vcpus", sa.Integer(), nullable=False),
            sa.Column("memory", sa.Integer(), nullable=False),
            sa.Column("network_tap", sa.String(), nullable=True),
            sa.PrimaryKeyConstraint("uuid"),
        )

    # Support intermediate versions that have the records table
    # but without the network_tap column
    records_columns = [column["name"] for column in inspector.get_columns("records")]
    if "network_tap" not in records_columns:
        op.add_column("records", sa.Column("network_tap", sa.String(), nullable=True))

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("records")
    # ### end Alembic commands ###
