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.
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.
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? ¶ 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With