sqlalchemy在postgres中使用继承

时间:2011-07-21 20:49:15

标签: python postgresql inheritance sqlalchemy polymorphic-associations

试图学习sqlalchemy(和python),我试图复制已经存在的项目,但是我很难用postgres来计算sqlalchemy和继承。

这是我们的postgres数据库的一个例子(显然,这是简化的):

CREATE TABLE system (system_id SERIAL PRIMARY KEY, 
                     system_name VARCHAR(24) NOT NULL);
CREATE TABLE file_entry(file_entry_id SERIAL, 
                        file_entry_msg VARCHAR(256) NOT NULL, 
                        file_entry_system_name VARCHAR(24) REFERENCES system(system_name) NOT NULL);
CREATE TABLE ops_file_entry(CONSTRAINT ops_file_entry_id_pkey PRIMARY KEY (file_entry_id), 
     CONSTRAINT ops_system_name_check CHECK ((file_entry_system_name = 'ops'::bpchar))) INHERITS (file_entry);
CREATE TABLE eng_file_entry(CONSTRAINT eng_file_entry_id_pkey PRIMARY KEY (file_entry_id),
     CONSTRAINT eng_system_name_check CHECK ((file_entry_system_name = 'eng'::bpchar)) INHERITS (file_entry);
CREATE INDEX ops_file_entry_index ON ops_file_entry USING btree (file_entry_system_id);
CREATE INDEX eng_file_entry_index ON eng_file_entry USING btree (file_entry_system_id);

然后插件将使用触发器完成,以便将它们正确插入子数据库中。类似的东西:

CREATE FUNCTION file_entry_insert_trigger() RETURNS "trigger"
    AS $$
DECLARE 
BEGIN
     IF NEW.file_entry_system_name = 'eng' THEN
        INSERT INTO eng_file_entry(file_entry_id, file_entry_msg, file_entry_type, file_entry_system_name) VALUES (NEW.file_entry_id, NEW.file_entry_msg, NEW.file_entry_type, NEW.file_entry_system_name);
     ELSEIF NEW.file_entry_system_name = 'ops' THEN
        INSERT INTO ops_file_entry(file_entry_id, file_entry_msg, file_entry_type, file_entry_system_name) VALUES (NEW.file_entry_id, NEW.file_entry_msg, NEW.file_entry_type, NEW.file_entry_system_name);
     END IF;
     RETURN NULL;
 END;
 $$ LANGUAGE plpgsql;

总之,我有一个父表与另一个表的外键。然后我有2个子表存在,插入是基于给定的值完成的。在上面的例子中,如果file_entry_system_name是'ops',那么该行进入ops_file_entry表; 'eng'进入eng_file_entry_table。我们在生产环境中有数百个子表,考虑到数据量,它确实加快了速度,所以我想保持这个相同的结构。我可以查询父级,只要我给它正确的'system_name',它就会立即知道要查看哪个子表。

我的愿望是用sqlalchemy来模仿这个,但我找不到任何涉及这个细节的例子。我通过示例查看sqlalchemy生成的sql,我可以告诉它在数据库端没有做类似的事情。

我能想到的最好的东西是:

class System(_Base):
    __tablename__ = 'system'
    system_id = Column(Integer, Sequence('system_id_seq'), primary_key = True)
    system_name = Column(String(24), nullable=False)
    def __init(self, name)
        self.system_name = name
class FileEntry(_Base):
    __tablename__ = 'file_entry'
    file_entry_id = Column(Integer, Sequence('file_entry_id_seq'), primary_key=True)
    file_entry_msg = Column(String(256), nullable=False)
    file_entry_system_name = Column(String(24), nullable=False, ForeignKey('system.system_name'))
    __mapper_args__ = {'polymorphic_on': file_entry_system_name}
    def __init__(self, msg, name)
        self.file_entry_msg = msg
        self.file_entry_system_name = name
class ops_file_entry(FileEntry):
    __tablename__ = 'ops_file_entry'
    ops_file_entry_id = Column(None, ForeignKey('file_entry.file_entry_id'), primary_key=True)
    __mapper_args__ = {'polymorphic_identity': 'ops_file_entry'}

最后,我错过了什么?我如何告诉sqlalchemy将插入到FileEntry中的任何内容与系统名称“ops”相关联以转到'ops_file_entry'表?我理解的方式是什么?

对我应该做些什么的一些见解会很棒。

2 个答案:

答案 0 :(得分:1)

您只需创建ops_file_entry的新实例(不应该是OpsFileEntry?),将其添加到会话中,并在刷新时,将一行插入到表{{1}中}以及表格file_entry

您无需设置ops_file_entry属性,也无需设置触发器。

答案 1 :(得分:0)

我不太了解python或sqlalchemy,但我想我会为了旧时的缘故给它一个机会。 ;)

您是否尝试过在应用程序级别设置自己的触发器?这样的事情可能有用:

from sqlalchemy import event, orm

def my_after_insert_listener(mapper, connection, target):
    # set up your constraints to store the data as you want
    if target.file_entry_system_name = 'eng'
        # do your child table insert
    elseif target.file_entry_system_name = 'ops'
        # do your child table insert
    #…

mapped_file_entry_class = orm.mapper(FileEntry, 'file_entry')
# associate the listener function with FileEntry,
# to execute during the "after_insert" hook
event.listen(mapped_file_entry_class, 'after_insert', my_after_insert_listener)

我不是肯定的,但我认为target(或者mapper)应该包含要插入的数据。

Events (esp. after_create)mapper可能会有所帮助。