SQLAlchemy Automap does not create class for tables without primary key

Question:

I am using SQL Alchemy v(0.9.1) which has the automap functionality. This allows me to create classes and relationships automatically. http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/automap.html

The problem I am experiencing is that when using automap_base, I see that not all the tables that are available in the metadata.tables list are mapped.

There are no errors when preparing, except that I am unable to access the class (e.g. Base.classes.Example_Table) from the Base after calling automap_base()

from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import create_session

from sqlalchemy.ext.automap import automap_base

engine = create_engine("mysql+mysqldb://")

Base = automap_base()
Base.prepare(engine, reflect = True)

session = create_session(bind = engine)

Then I run to find that classes do not exist for all tables in metadata (I did not use only = [] argument in metadata)

for mappedclass in Base.classes:
    print mappedclass

for mdtable in metadata.tables:
    print mdtable

Only to find that Example_Table (with the following create syntax) does not have a class

    CREATE TABLE `Example_Table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `attributeType` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3290719 DEFAULT CHARSET=latin1

i.e. Base.class.Example_Table returns the following error

    ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-94492ae1b8ba> in <module>()
      7 type(metadata.tables)
      8 
----> 9 Base.classes.Example_Table

/usr/local/lib/python2.7/site-packages/sqlalchemy/util/_collections.pyc in __getattr__(self, key)
    172             return self._data[key]
    173         except KeyError:
--> 174             raise AttributeError(key)
    175 
    176     def __contains__(self, key):

AttributeError: Example_Table

I don’t think this problem happens because my Example_Table name has an underscore in it.

I think the problem is related to the fact that my Example_Table does not have a primary key. The Example_Table is only meant to link two other tables.

Asked By: ivrin

||

Answers:

Figured it out by combing through the reference/reframing the problem.

In case it helps someone else –

Because SQLAlchemy ORM is based on an identity map model, one cannot map (or automap) a table that does not have a primary key. An arbitrary primary key should be specified.

http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key

Answered By: ivrin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.