Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy necessary table properties

When writing SQLAlchemy models for a pre-existing database, how much information about a table do I have to give? Consider this table which is part of a MySQL database:

CREATE TABLE entities (
    id INTEGER NOT NULL AUTO_INCREMENT,
    dn VARCHAR(100) NOT NULL UNIQUE,
    PRIMARY KEY (id)
) Engine=InnoDB, COLLATE utf8_unicode_ci;

Based on my testing, this would be sufficient to use it:

class Entity(Base):
    __tablename__ = 'entities'
    id          = Column('id', Integer, primary_key=True)
    dn          = Column('dn', String(100))

But of course its missing the UNIQUE, AUTO_INCREMENT, Engine and COLLATE information. Does SQLAlchemy care about these?

Of course I could use Reflection, but I would rather not due to consistency reasons.

like image 391
Gevatter Gaul Avatar asked Mar 08 '13 14:03

Gevatter Gaul


People also ask

Is SQLAlchemy necessary?

SQLAlchemy is the ORM of choice for working with relational databases in python. The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn't require knowledge of SQL to get started.

Is SQLAlchemy good for ETL?

One of the key aspects of any data science workflow is the sourcing, cleaning, and storing of raw data in a form that can be used upstream. This process is commonly referred to as “Extract-Transform-Load,” or ETL for short.

How do I map a table that has no primary key SQLAlchemy?

How do I map a table that has no primary key? ¶ The SQLAlchemy ORM, in order to map to a particular table, needs there to be at least one column denoted as a primary key column; multiple-column, i.e. composite, primary keys are of course entirely feasible as well.

What is the use of MetaData in SQLAlchemy?

Metadata contains definitions of tables and associated objects such as index, view, triggers, etc. Hence an object of MetaData class from SQLAlchemy Metadata is a collection of Table objects and their associated schema constructs.


1 Answers

The below should produce the same result semantically, although will not produce the same query:

class Entity(Base):
    __tablename__ = 'entities'
    __table_args__ = {'mysql_engine':'InnoDB'}
    id          = Column('id', Integer, primary_key=True)
    dn          = Column('dn', String(100, collation='utf8_unicode_ci'), unique=True)

I am only not sure how to specify collation for the whole table.

like image 50
van Avatar answered Nov 01 '22 06:11

van