0

I'm using alembic for database migration. And using sqlalchemy to connect to the database using python.
In alembic, we define table schema as the first version and this the actual one which creates the schema.
For example, I have given schema like this in my first version of alembic.

op.create_table(
        'my_table',
        sa.Column('id', sa.String(10), primary_key=True),
        sa.Column('mail', sa.String(20), unique=True)
)

Now, lets come to sqlalchemy part. Inside my python project, I have a database connection file, where I have created user table like this.

class CompanyInfo(Base):
    __tablename__ = 'my_table'

    id = Column(String(10), primary_key=False)
    name = Column(String(20), unique=False)

Here, Alembic is the first thing which is connecting to the database and creating tables. So how does it matter whether I specify primary_key, unique constraint or nullable=T/F values inside my python class?

My question is only about constraints not on data types and it's length.

venkat
  • 453
  • 4
  • 16

2 Answers2

0

Firstly, if you do not keep your code in order, it will be a bloody mess. Having different information in the database and in the sqlalchemy schema is really a bad idea.

Once you start using ORM, these things are super-important. Primary key will be used to identify the object in memory. Foreign key will be used to automatically make queries with both tables. Not sure about unique.

I thing sqlalchemy will use the foreign key constraints for creating the join when querying related table.

Again, I am not absolutely sure about nullable handling, but I believe sqlalchemy uses it when setting default value - if nullable, it can create an object without knowing the default.

Petr Blahos
  • 2,253
  • 1
  • 11
  • 14
  • My intention is not to violate the structure. I'm just curious to know, how it will affect the functionality when constraints are mismatching. – venkat Mar 05 '20 at 14:18
0

That will be useful while serializing the table data and deserializing from objects.

for example, you want to insert data in table, you can simply create a object where those attributes will be checked, and then save it.

company_info = CompanyInfo(id=12,name='ABC')
company_info.save()


def save(self):
    self.add()
    self.commit()
def commit(cls):
    db.session.commit()
Summit
  • 26
  • 4