Skip to content

Instantly share code, notes, and snippets.

@jace jace/dump.sql
Created Sep 14, 2012

Embed
What would you like to do?
SQLAlchemy joined table inheritance and mixins
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE node (
id INTEGER NOT NULL, -- from Mixin
name VARCHAR(200), -- from Mixin
published BOOLEAN NOT NULL,
type VARCHAR(20),
title VARCHAR(200), -- from Mixin
PRIMARY KEY (id),
CHECK (published IN (0, 1))
);
CREATE TABLE page (
name VARCHAR(200), -- from Mixin, but shouldn't be here
id INTEGER NOT NULL, -- from Page
content TEXT,
PRIMARY KEY (id),
FOREIGN KEY(id) REFERENCES node (id) -- from Page
);
COMMIT;
from sqlalchemy import Column, Unicode, Integer, Boolean, Text, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base, declared_attr
Base = declarative_base()
class Mixin(object):
id = Column(Integer, primary_key=True)
name = Column(Unicode(200))
@declared_attr
def title(cls):
return Column(Unicode(200))
class Node(Mixin, Base):
__tablename__ = 'node'
published = Column(Boolean, nullable=False, default=False)
type = Column(Unicode(20))
__mapper_args__ = {'polymorphic_on': type, 'polymorphic_identity': 'node'}
class Page(Node):
__tablename__ = 'page'
id = Column(Integer, ForeignKey('node.id'), primary_key=True, nullable=False)
content = Column(Text)
__mapper_args__ = {'polymorphic_identity': 'page'}
if __name__ == '__main__':
engine = create_engine('sqlite:///test.db')
Base.metadata.create_all(engine)
import os
os.system("echo .dump | sqlite3 test.db")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.