Exemplo n.º 1
0
    def test_identity_on_null(self):
        m1 = MetaData()
        m2 = MetaData()

        Table(
            "user",
            m1,
            Column("id", Integer, sa.Identity(start=2, on_null=True)),
            Column("other", sa.Text),
        )

        Table(
            "user",
            m2,
            Column("id", Integer, sa.Identity(start=2, on_null=False)),
            Column("other", sa.Text),
        )

        diffs = self._fixture(m1, m2)
        if not config.requirements.supports_identity_on_null.enabled:
            eq_(diffs, [])
        else:
            eq_(len(diffs[0]), 1)
            diffs = diffs[0][0]
            eq_(diffs[0], "modify_default")
            eq_(diffs[2], "user")
            eq_(diffs[3], "id")
            old = diffs[5]
            new = diffs[6]

            is_true(isinstance(old, sa.Identity))
            is_true(isinstance(new, sa.Identity))
class DataPoint(models.model.Model):
    def __init_subclass__(cls: typing.Type['DataPoint'],
                          /,
                          plural: typing.Optional[str] = None) -> None:
        super().__init_subclass__()
        cls.base_name = inflection.underscore(cls.__name__)
        if plural:
            cls.plural = plural
        else:
            cls.plural = cls.base_name + 's'

        cls.__tablename__ = cls.plural
        cls.id = sqlalchemy.Column(cls.base_name + '_id',
                                   sqlalchemy.Integer,
                                   sqlalchemy.Identity(always=True),
                                   primary_key=True)
        cls.name = sqlalchemy.Column(cls.base_name,
                                     sqlalchemy.Text,
                                     nullable=False,
                                     index=True,
                                     unique=True)
        for parent in cls.__parent_data_points__:
            if isinstance(parent, type) and issubclass(parent, DataPoint):
                foreign_key = sqlalchemy.Column(
                    parent.base_name + '_id', sqlalchemy.ForeignKey(parent.id))
                setattr(cls, parent.id.name, foreign_key)
                setattr(
                    cls, parent.base_name,
                    sqlalchemy.orm.relationship(parent,
                                                backref=cls.plural,
                                                foreign_keys=(foreign_key, )))
            else:
                raise TypeError("Did not recognize type of parent.")
Exemplo n.º 3
0
    def test_remove_identity_column(self):
        m1 = MetaData()
        m2 = MetaData()

        Table(
            "user",
            m1,
            Column(
                "id",
                Integer,
                sa.Identity(start=2, increment=3),
                primary_key=True,
            ),
        )

        Table("user", m2)

        diffs = self._fixture(m1, m2)

        eq_(diffs[0][0], "remove_column")
        eq_(diffs[0][2], "user")
        c = diffs[0][3]
        eq_(c.name, "id")

        is_true(isinstance(c.identity, sa.Identity))
        eq_(c.identity.start, 2)
        eq_(c.identity.increment, 3)
Exemplo n.º 4
0
    def test_add_identity_column(self):
        m1 = MetaData()
        m2 = MetaData()

        Table("user", m1, Column("other", sa.Text))

        Table(
            "user",
            m2,
            Column("other", sa.Text),
            Column(
                "id",
                Integer,
                sa.Identity(start=5, increment=7),
                primary_key=True,
            ),
        )

        diffs = self._fixture(m1, m2)

        eq_(diffs[0][0], "add_column")
        eq_(diffs[0][2], "user")
        eq_(diffs[0][3].name, "id")
        i = diffs[0][3].identity

        is_true(isinstance(i, sa.Identity))
        eq_(i.start, 5)
        eq_(i.increment, 7)
Exemplo n.º 5
0
    def test_remove_identity_from_column(self):
        m1 = MetaData()
        m2 = MetaData()

        Table(
            "user",
            m1,
            Column("id", Integer, sa.Identity(start=2, maxvalue=1000)),
            Column("other", sa.Text),
        )

        Table(
            "user",
            m2,
            Column("id", Integer),
            Column("other", sa.Text),
        )

        diffs = self._fixture(m1, m2)

        eq_(len(diffs[0]), 1)
        diffs = diffs[0][0]
        eq_(diffs[0], "modify_default")
        eq_(diffs[2], "user")
        eq_(diffs[3], "id")
        eq_(diffs[6], None)
        removed = diffs[5]

        is_true(isinstance(removed, sa.Identity))
Exemplo n.º 6
0
def test_Column_identity():
    """ _column.Column() works ith identity """
    if not getattr(_sa, 'Identity', None):
        skip("Identity not defined")

    meta = _sa.MetaData()
    table = _sa.Table(
        u'mytable',
        meta,
        _sa.Column(u'Lala', _mysql.VARCHAR(255), _sa.Identity()),
        _sa.Column(u'lolo',
                   _mysql.INTEGER,
                   primary_key=True,
                   autoincrement=False),
    )
    meta.bind = _test.Bunch(dialect=_test.Bunch(name='mysql'))
    symbols = _symbols.Symbols(symbols=dict(type="TT"))

    inst = _column.Column.from_sa(table.c.Lala, symbols)
    if bytes is str:
        assert repr(inst) == ('C(\'Lala\', TT.VARCHAR(255), '
                              'nullable=False, '
                              'server_default=_sa.Identity())')
    else:
        assert repr(inst) == ('C(\'Lala\', TT.VARCHAR(255), '
                              'nullable=False, '
                              'server_default=_sa.Identity())')

    inst = _column.Column.from_sa(table.c.lolo, symbols)
    assert repr(inst) == ("C('lolo', TT.INTEGER, nullable=False, "
                          "autoincrement=False)")
def generate_table(meta: sa.MetaData, min_cols, max_cols, dialect_name):
    col_number = random.randint(min_cols, max_cols)
    table_num = len(meta.tables)
    add_identity = random.random() > 0.90
    identity = sa.Identity(
        always=random.randint(0, 1),
        start=random.randint(1, 100),
        increment=random.randint(1, 7),
    )
    is_mssql = dialect_name == "mssql"
    cols = []
    for i in range(col_number - (0 if is_mssql else add_identity)):
        args = []
        if random.random() < 0.95 or table_num == 0:
            if is_mssql and add_identity and i == 0:
                args.append(sa.Integer)
                args.append(identity)
            else:
                args.append(random.choice(types))
        else:
            args.append(
                sa.ForeignKey(f"table_{table_num-1}.table_{table_num-1}_col_1")
            )
        cols.append(
            sa.Column(
                f"table_{table_num}_col_{i+1}",
                *args,
                primary_key=i == 0,
                comment=f"primary key of table_{table_num}"
                if i == 0
                else None,
                index=random.random() > 0.9 and i > 0,
                unique=random.random() > 0.95 and i > 0,
            )
        )
    if add_identity and not is_mssql:
        cols.append(
            sa.Column(
                f"table_{table_num}_col_{col_number}",
                sa.Integer,
                identity,
            )
        )
    args = ()
    if table_num % 3 == 0:
        # mysql can't do check constraint on PK col
        args = (sa.CheckConstraint(cols[1].is_not(None)),)
    return sa.Table(
        f"table_{table_num}",
        meta,
        *cols,
        *args,
        comment=f"comment for table_{table_num}" if table_num % 2 else None,
    )
Exemplo n.º 8
0
    def test_change_identity(self, before, after):
        arg_before = (sa.Identity(**before), ) if before else ()
        arg_after = (sa.Identity(**after), ) if after else ()

        m1 = MetaData()
        m2 = MetaData()

        Table(
            "user",
            m1,
            Column("id", Integer, *arg_before),
            Column("other", sa.Text),
        )

        Table(
            "user",
            m2,
            Column("id", Integer, *arg_after),
            Column("other", sa.Text),
        )

        diffs = self._fixture(m1, m2)

        eq_(len(diffs[0]), 1)
        diffs = diffs[0][0]
        eq_(diffs[0], "modify_default")
        eq_(diffs[2], "user")
        eq_(diffs[3], "id")
        old = diffs[5]
        new = diffs[6]

        def check(kw, idt):
            if kw:
                is_true(isinstance(idt, sa.Identity))
                for k, v in kw.items():
                    eq_(getattr(idt, k), v)
            else:
                is_true(idt in (None, False))

        check(before, old)
        check(after, new)
Exemplo n.º 9
0
    def test_no_change_identity_column(self):
        m1 = MetaData()
        m2 = MetaData()

        for m in (m1, m2):
            Table(
                "user",
                m,
                Column("id", Integer, sa.Identity(start=2)),
            )

        diffs = self._fixture(m1, m2)

        eq_(diffs, [])
Exemplo n.º 10
0
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        'hosting_service', sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('type', sa.String(length=80), nullable=False),
        sa.Column('landingpage_url', sa.String(length=500), nullable=True),
        sa.Column('api_url', sa.String(length=500), nullable=False),
        sa.Column('label', sa.String(length=80), nullable=True),
        sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('api_url'))
    op.create_table('repositories',
                    sa.Column('id',
                              sa.Integer(),
                              sa.Identity(always=False),
                              nullable=False),
                    sa.Column('foreign_id', sa.Integer(), nullable=True),
                    sa.Column('hosting_service_id',
                              sa.Integer(),
                              nullable=True),
                    sa.Column('name', sa.String(length=500), nullable=False),
                    sa.Column('username',
                              sa.String(length=500),
                              nullable=False),
                    sa.Column('description', sa.Text(), nullable=True),
                    sa.Column('created_at', sa.DateTime(), nullable=True),
                    sa.Column('updated_at', sa.DateTime(), nullable=True),
                    sa.Column('pushed_at', sa.DateTime(), nullable=True),
                    sa.Column('stars_count', sa.Integer(), nullable=True),
                    sa.Column('forks_count', sa.Integer(), nullable=True),
                    sa.Column('is_private', sa.Boolean(), nullable=True),
                    sa.Column('is_fork', sa.Boolean(), nullable=True),
                    sa.Column('is_archived', sa.Boolean(), nullable=True),
                    sa.Column('is_disabled', sa.Boolean(), nullable=True),
                    sa.Column('is_mirror', sa.Boolean(), nullable=True),
                    sa.Column('homepage_url',
                              sa.String(length=500),
                              nullable=True),
                    sa.Column('repo_url', sa.String(length=500),
                              nullable=True),
                    sa.ForeignKeyConstraint(
                        ['hosting_service_id'],
                        ['hosting_service.id'],
                    ),
                    sa.PrimaryKeyConstraint('id'),
                    prefixes=['UNLOGGED'])
Exemplo n.º 11
0
class Items(Base):
    __tablename__ = 'items'

    item_id: int = sa.Column(sa.BigInteger,
                             sa.Identity(minvalue=1),
                             primary_key=True)
    name: str = sa.Column(sa.VARCHAR(255), nullable=False)
    price: int = sa.Column(sa.Integer, nullable=False)
    description: str = sa.Column(sa.VARCHAR(1024))
    thumb_url: str = sa.Column(sa.Text)
    create_date: datetime = sa.Column(sa.DateTime,
                                      server_default=sa.func.now())

    def __init__(self, name: str, price: int, description: str,
                 thumb_url: str):
        self.name = name
        self.price = price
        self.description = description
        self.thumb_url = thumb_url

    def __repr__(self):
        return "<Items('%s', '%s', '%s', '%s', '%s')>" % (
            self.item_id, self.name, self.price, self.description,
            self.create_date)