在sqlalchemy 与django 自带ORM之间,我选择了前者。
今天通过automap api试图将已经有的ORACLE 数据库映射到MODEL层,一直没有成功。
仔细分析报错后发现:
2016-06-11 15:56:37,940 INFO sqlalchemy.engine.base.Engine SELECT table_name FROM all_tables WHERE nvl(tablespace_name, 'no tablespace') NOT IN ('SYSTEM', 'SYSAUX') AND OWNER = :owner AND IOT_NAME IS NULL AND DURATION IS NULL
2016-06-11 15:56:37,940 INFO sqlalchemy.engine.base.Engine {'owner': u'KING'}
2016-06-11 15:56:37,950 INFO sqlalchemy.engine.base.Engine SELECT table_name, compression, compress_for FROM ALL_TABLES WHERE table_name = :table_name AND owner = :owner
2016-06-11 15:56:37,950 INFO sqlalchemy.engine.base.Engine {'owner': u'KING', 'table_name': u'WEEKLYQUOTE'}
2016-06-11 15:56:37,953 INFO sqlalchemy.engine.base.Engine SELECT column_name, data_type, char_length, data_precision, data_scale, nullable, data_default FROM ALL_TAB_COLUMNS WHERE table_name = :table_name AND owner = :owner ORDER BY column_id
2016-06-11 15:56:37,953 INFO sqlalchemy.engine.base.Engine {'owner': u'KING', 'table_name': u'WEEKLYQUOTE'}
2016-06-11 15:56:37,957 INFO sqlalchemy.engine.base.Engine SELECT
ac.constraint_name,
ac.constraint_type,
loc.column_name AS local_column,
rem.table_name AS remote_table,
rem.column_name AS remote_column,
rem.owner AS remote_owner,
loc.position as loc_pos,
rem.position as rem_pos
FROM all_constraints ac,
all_cons_columns loc,
all_cons_columns rem
WHERE ac.table_name = :table_name
AND ac.constraint_type IN ('R','P')
AND ac.owner = :owner
AND ac.owner = loc.owner
AND ac.constraint_name = loc.constraint_name
AND ac.r_owner = rem.owner(+)
AND ac.r_constraint_name = rem.constraint_name(+)
AND (rem.position IS NULL or loc.position=rem.position)
ORDER BY ac.constraint_name, loc.position
2016-06-11 15:56:37,957 INFO sqlalchemy.engine.base.Engine {'owner': u'KING', 'table_name': u'WEEKLYQUOTE'}
2016-06-11 15:56:37,974 INFO sqlalchemy.engine.base.Engine SELECT a.index_name, a.column_name,
b.index_type, b.uniqueness, b.compression, b.prefix_length
FROM ALL_IND_COLUMNS a,
ALL_INDEXES b
WHERE
a.index_name = b.index_name
AND a.table_owner = b.table_owner
AND a.table_name = b.table_name
AND a.table_name = :table_name AND a.table_owner = :schema ORDER BY a.index_name, a.column_position
2016-06-11 15:56:37,974 INFO sqlalchemy.engine.base.Engine {'table_name': u'WEEKLYQUOTE', 'schema': u'KING'}
以上粗体的SQL 出了问题 ,
用户名KING下的WEEKLYQUOTE表缺少主键(或外键)
补上后即成功。
automap使用场景:
假如你有一个Django项目,通过ORM创建了一大堆Model。这时来了一个新项目,需要操作 这些表,应该怎么办?拷贝这些Models?使用原始的DB-API加上sql来操作?其实使用SQLAlchemy的Automap可以让你的工作变得非常的方便,你只要在新项目连接到旧数据库,然后 稍微配置一下Automap,就可以使用SQLAlchemy的ORM操作那些通过别的系统创建的表了。