2

I slightly modified the official example for a directed graph and added a cascade='all, delete-orphan as recommended for cascading deletion if the relationship is defined in the child. Still, when I try to delete a parent I get a foreign key constraint error.

I want to be able to delete a Node object and all related Edges should also be deleted. Using passive_deletes=True would be preferred, I did not get that to work either.

Full sourcecode with my modifications, removed mysql connection data:

"""a directed graph example."""

from sqlalchemy import Column, Integer, ForeignKey, \
    create_engine
from sqlalchemy.orm import relationship, sessionmaker, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Node(Base):
    __tablename__ = 'node'

    node_id = Column(Integer, primary_key=True)

    def higher_neighbors(self):
        return [x.higher_node for x in self.lower_edges]

    def lower_neighbors(self):
        return [x.lower_node for x in self.higher_edges]


class Edge(Base):
    __tablename__ = 'edge'

    lower_id = Column(
        Integer,
        ForeignKey('node.node_id'),
        primary_key=True)

    higher_id = Column(
        Integer,
        ForeignKey('node.node_id'),
        primary_key=True)

    lower_node = relationship(
        Node,
        primaryjoin=lower_id == Node.node_id,
        backref=backref('lower_edges', cascade='all, delete-orphan'))

    higher_node = relationship(
        Node,
        primaryjoin=higher_id == Node.node_id,
        backref=backref('higher_edges', cascade='all, delete-orphan'))

    def __init__(self, n1, n2):
        self.lower_node = n1
        self.higher_node = n2

engine = create_engine('mysql+pymysql:', echo=True)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)

session = sessionmaker(engine)()

# create a directed graph like this:
#       n1 -> n2 -> n1
#                -> n5
#                -> n7
#          -> n3 -> n6

n1 = Node()
n2 = Node()
n3 = Node()
n4 = Node()
n5 = Node()
n6 = Node()
n7 = Node()

Edge(n1, n2)
Edge(n1, n3)
Edge(n2, n1)
Edge(n2, n5)
Edge(n2, n7)
Edge(n3, n6)

session.add_all([n1, n2, n3, n4, n5, n6, n7])
session.commit()

session = sessionmaker(engine)()
session.query(Node).filter(Node.node_id==1).delete()
session.commit()
wackazong
  • 474
  • 7
  • 18
  • `Query.delete()` is a bulk operation that does not (and pretty much cannot) respect ORM relationship cascades – all this is noted [in the documentation](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.delete). You will have to configure DB cascades for that. – Ilja Everilä Mar 27 '18 at 06:00
  • Related, if not a duplicate of [SQLAlchemy delete doesn't cascade](https://stackoverflow.com/questions/19243964/sqlalchemy-delete-doesnt-cascade) – Ilja Everilä Mar 27 '18 at 06:07
  • Ah, I did not see the query in the delete command before. Thanks... – wackazong Mar 27 '18 at 09:47

1 Answers1

2

Delete is done via session.query().delete() which does not work with SQLAlchemy cascade and needs cascading in the DB to work.

wackazong
  • 474
  • 7
  • 18