Deleting from self-referential inherited objects does not cascade in SQLAlchemy-SQLite - python

I posted a question previously here where I tried to build a hierarchy using different objects. Each object can have any type of object as it's parent, and any type as children. I solved it by using the Node class suggested by SQLAlchemy here and letting the other objects inherit from it.
Now I'm having the problem that deleting a node does not delete it's children. I have tried a lot of solutions like different cascade settings, using ondelete='CASCADE' in the foreignkey, as well as DBSession.execute('pragma foreign_keys=on') but none are working. I think the problem is in the ParentID key because in the child it is not null when the parent is delete.
I'm pretty new to SQLAlchemy so I'm not at all sure where I'm going wrong, any help would be appreciated.
These are my current models:
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
# DBSession.execute('pragma foreign_keys=on')
Base = declarative_base()
class Node(Base):
def getID():
return uuid.uuid1().hex
__tablename__ = 'Node'
ID = Column(Text, primary_key=True, default=getID)
ParentID = Column(Text, ForeignKey('Node.ID', ondelete='CASCADE'))
type = Column(Text(50))
Children = relationship("Node",
backref=backref('Parent',
remote_side=[ID]
),
single_parent=True,
cascade="all, delete, delete-orphan",
passive_deletes = True
)
__mapper_args__ = {
'polymorphic_identity':'Node',
'polymorphic_on':type
}
class A(Node):
__tablename__ = 'A'
ID = Column(Text, ForeignKey('Node.ID', ondelete='CASCADE'), primary_key=True)
Name = Column(Text)
Description = Column(Text)
__mapper_args__ = {'polymorphic_identity':'A'}
class B(Node):
__tablename__ = 'B'
ID = Column(Text, ForeignKey('Node.ID', ondelete='CASCADE'), primary_key=True)
Name = Column(Text)
Description = Column(Text)
__mapper_args__ = {'polymorphic_identity':'B'}
class C(Node):
__tablename__ = 'C'
ID = Column(Text, ForeignKey('Node.ID', ondelete='CASCADE'), primary_key=True)
Name = Column(Text)
Description = Column(Text)
Quantity = Column(Integer)
Rate = Column(Integer)
__mapper_args__ = {'polymorphic_identity':'C' }
This is how I build a hierarchy:
a = A(Name="PName",
Description="PDesc",
ParentID='0')
b = B(Name="BGName",
Description="BGDesc",
ParentID=project.ID)
c = C(Name="BIName",
Description="BIDesc",
Quantity=10,
Rate=5,
ParentID=budgetgroup.ID)
# Append the children nodes to their parents
b.Children.append(c)
a.Children.append(b)
DBSession.add(a)
And this is how I delete it:
def deleteitem(id):
deleteid = id
deletethis = DBSession.query(Node).filter_by(ID=deleteid).first()
qry = DBSession.delete(deletethis)
# qry = DBSession.query(Node).filter_by(ID=deleteid).delete(
# synchronize_session='fetch')
transaction.commit()
Note: neither the one way or the other commented out delete cascades.

I was able to find a solution from this answer here.
Now my Node class looks as follows:
class Node(Base):
__tablename__ = 'Node'
ID = Column(Integer, primary_key=True)
ParentID = Column(Integer, ForeignKey('Node.ID', ondelete='CASCADE'))
type = Column(Text(50))
Children = relationship(
'Node',
cascade="all",
backref=backref("Parent", remote_side='Node.ID'),
)
__mapper_args__ = {
'polymorphic_identity':'Node',
'polymorphic_on':type
}
And this seems to work, all my deletes are cascading.

Related

In sqlalchemy how to access anonymous field in subquery

First, I used Sqlalchemy's polymorphic architecture.
ChildA and ChildB extends Child.
ChildA has name column.
ChildB has age column.
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship(Parent, backref='children')
class ChildA(Child):
__tablename__ = 'child_a'
id = Column(Integer, primary_key=True)
name = Column(String(50))
class ChildB(Child):
__tablename__ = 'child_b'
id = Column(Integer, primary_key=True)
age = Column(Integer)
parent = DBSession.query(Parent).first()
subquery = parent.children.join(ChildA).subquery()
So I want to access ChildA.name column from subquery.
Something like subquery.c.ChildA.name == 'Tom'
If I understood properly what you are trying to do, you don't really need a subquery, it could be simply something like
In [13]:
f = session.query(Parent, ChildA).join(ChildA).first()
print(f.ChildA.name)
Pedro
For the use of subqueries, I would recommend you take a look to sqlalchemy tutorial.
On the other hand, I wasn't able to use the classes as you've defined them, I had to add a ForeignKey like this
class ChildA(Child):
__tablename__ = 'child_a'
id = Column(Integer, ForeignKey('child.id'), primary_key=True)
name = Column(String(50))
class ChildB(Child):
__tablename__ = 'child_b'
id = Column(Integer, ForeignKey('child.id'), primary_key=True)
age = Column(Integer)
I have no doubt that it works for you, this probably depends on the setup.
And finally, I would like to recommend you to use a column for the type of child. With this, it will be easier to recognize the children you are using. Something like this,
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship(Parent, backref='children')
type = Column(String(20))
__mapper_args__ = {
'polymorphic_identity':'child',
'polymorphic_on':type
}
class ChildA(Child):
__tablename__ = 'child_a'
id = Column(Integer, ForeignKey('child.id'), primary_key=True)
name = Column(String(50))
__mapper_args__ = {
'polymorphic_identity':'child_a',
}
class ChildB(Child):
__tablename__ = 'child_b'
id = Column(Integer, ForeignKey('child.id'), primary_key=True)
age = Column(Integer)
__mapper_args__ = {
'polymorphic_identity':'child_b',
}
Please take a look to sqlalchemy docs for details.
Hope it helps.

SQLAlchemy One-To-One and One-To-Many at the same time (AmbiguousForeignKeysError)

I'm working with SQLAlchemy and I try to achieve one-to-one and one-to-many relationships on the same parent class.
This is for the simplicity of keeping track of the main child entity.
Unfortunately I'm getting an error:
AmbiguousForeignKeysError: Could not determine join condition between
parent/child tables on relationship Customer.contact - there are
multiple foreign key paths linking the tables. Specify the
'foreign_keys' argument, providing a list of those columns which
should be counted as containing a foreign key reference to the parent
table.
Am I doing something wrong or it is not possible?
Here is a code example:
class Customer(Base):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
contact_id = Column(Integer, ForeignKey('contact.id'))
address_id = Column(Integer, ForeignKey('address.id'))
contact = relationship('Contact', backref=backref("contact", uselist=False))
address = relationship('Address', backref=backref("address", uselist=False))
contact_list = relationship('Contact')
address_list = relationship('Address')
class Contact(Base):
__tablename__ = 'contact'
id = Column(Integer, primary_key=True)
customer_id = Column(Integer, ForeignKey(
'customer.id',
use_alter=True, name='fk_contact_customer_id_customer',
onupdate='CASCADE', ondelete='SET NULL'
))
first_name = Column(String(32))
last_name = Column(String(32))
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
customer_id = Column(Integer, ForeignKey(
'customer.id',
use_alter=True, name='fk_address_customer_id_customer',
onupdate='CASCADE', ondelete='SET NULL'
))
label = Column(String(32))
Thanks
Apparently the solution was later in the documentation:
SQLAlchemy does not know which foreign key to use, so you have to specify those as Column objects in relationship(foreign_keys=[]) like so:
class Contact(Base):
# ...
customer_id = Column(Integer, ForeignKey(
'customer.id',
use_alter=True, name='fk_contact_customer_id_customer',
onupdate='CASCADE', ondelete='SET NULL'
))
# ...
class Customer(Base):
# ...
contact_id = Column(Integer, ForeignKey('contact.id'))
#...
contact = relationship('Contact', uselist=False, foreign_keys=[contact_id])
contact_list = relationship('Contact', foreign_keys=[Contact.customer_id])
#...

Sqlalchemy foreign key to a subset of polymorphic classes

I am using sqlalchemy to create a structure that resembles a graph, so that there are several types of nodes and links joining them. The nodes are defined like this:
class Node(Base):
__tablename__ = 'node'
id = Column(Integer, primary_key=True)
type = Column(Unicode)
__mapper_args__ = {'polymorphic_on': type}
class InputNode(Node):
__tablename__ = 'inputnode'
id = Column(Integer, ForeignKey('node.id'), primary_key=True)
__mapper_args__ = {'polymorphic_identity': 'input'}
class ThruNode(Node):
__tablename__ = 'thrunode'
id = Column(Integer, ForeignKey('node.id'), primary_key=True)
__mapper_args__ = {'polymorphic_identity': 'thru'}
class OutputNode(Node):
__tablename__ = 'outputnode'
id = Column(Integer, ForeignKey('node.id'), primary_key=True)
__mapper_args__ = {'polymorphic_identity': 'output'}
Now I want to create a Link table which would looks something like this:
class Link(Base):
__tablename__ = 'link'
input = Column(Integer, ForeignKey('node.id', where='type IN ("input", "thru")'))
output = Column(Integer, ForeignKey('node.id', where='type IN ("thru", "output")'))
The bit I'm struggling with is how to do the where part of it, since as I've written it is not valid in sqlalchemy. I had though of using a CheckConstraint or a ForeignKeyConstraint, but I can't see how either of them could actually be used to do this.
I haven't tryed it nor am I an expert of this, but shouldn't this work?
class Link(Base):
__tablename__ = 'link'
input = Column(Integer, ForeignKey('thrunode.id'))
output = Column(Integer, ForeignKey('outputnode.id'))
First I had another idea that maybe you could have used different names for the ids and than use those, kind of like:
instead of:
class InputNode(Node):
__tablename__ = 'inputnode'
id = Column(Integer, ForeignKey('node.id'), primary_key=True)
__mapper_args__ = {'polymorphic_identity': 'input'}
this:
class ThruNode(Node):
[...]
thrunode_id = Column(Integer, ForeignKey('node.id'), primary_key=True)
[...]
and then:
class Link(Base):
__tablename__ = 'link'
input = Column(Integer, ForeignKey('node.thrunode_id'))
output = Column(Integer, ForeignKey('node.outputnode_id'))
I got the idea from here sqlalchemy docs: declarative.html#joined-table-inheritance

sqlalchemy.exc.CircularDependencyError: Circular dependency detected

The business logic - One Category may have multiple (1:M) attributes, like Category "Memory" could have attributes Speed, Size, Type etc.
at the same time one Category could be sorted by the attribute value (this is stored inside Category.sortByAttribute - which is foreign key to LookupCategoryAttributes table.
Trying to construct it via SQLAlchemy, but getting circular dependency detected. What is wrong?
class Attribute(Base):
__tablename__ = "LookupCategoryAttributes"
types = ["date", "float", "integer", "select", "string", "text"]
# Properties
ID = Column(BigInteger, primary_key=True)
categoryID = Column(BigInteger, ForeignKey('LookupCategories.ID'), nullable=False )
attribute = Column(VARCHAR(255), nullable=False)
listValues = Column(VARCHAR(4000))
typeID = Column(VARCHAR(40), nullable=False)
isRequired = Column(SmallInteger, nullable=False, default=0)
displayInMenu = Column(SmallInteger, nullable=False, default=0)
displayInFilter = Column(SmallInteger, nullable=False, default=0)
class Category(Base):
__tablename__ = "LookupCategories"
# Properties
ID = Column(BigInteger, primary_key=True)
category = Column(VARCHAR(255), nullable=False)
description = Column(VARCHAR(1000), nullable=False)
parentCategoryID = Column(BigInteger, ForeignKey('LookupCategories.ID'))
leftPos = Column(Integer)
rightPos = Column(Integer)
sortByAttribute = Column(BigInteger, ForeignKey('LookupCategoryAttributes.ID'))
sortOrder = Column(SmallInteger, default=1)
# Relationships
ParentCategory = relationship("Category", uselist=False, remote_side=[ID], backref='SubCategories')
SortByAttribute = relationship("Attribute", uselist=False, foreign_keys=[sortByAttribute], primaryjoin="Attribute.ID==Category.sortByAttribute")
Attributes = relationship("Attribute", backref="Category", primaryjoin="Attribute.categoryID==Category.ID")
and then the code looks like this:
category = Category(record['Name'], extID=extID)
attr1 = Attribute(v)
attr2 = Attribute(v)
category.Attributes.append(attr1)
category.Attributes.append(attr2)
category.SortByAttribute = attr1
when I execute commit I get:
sqlalchemy.exc.CircularDependencyError: Circular dependency detected.
Okay found the answer - use post_update in relationship
http://docs.sqlalchemy.org/en/latest/orm/relationship_persistence.html#post-update
so what I did is inside Category class is changed this:
SortByAttribute = relationship(
"Attribute",
uselist=False,
foreign_keys=[sortByAttribute],
primaryjoin="Attribute.ID==Category.sortByAttribute"
)
to this:
SortByAttribute = relationship(
"Attribute",
uselist=False,
foreign_keys=[sortByAttribute],
primaryjoin="Attribute.ID==Category.sortByAttribute",
post_update=True
)

SQLAlchemy - Mapping self-referential relationship as one to many (declarative form)

I want to map a Tag entity using declarative method with SQLAlchemy. A tag can have a parent (another Tag).
I have:
class Tag(Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
label = Column(String)
def __init__(self, label, parentTag=None):
self.label = label
How can I add the "parent" relationship?
You add a ForeignKey referencing the parent, and then create a relationship that specifies the direction via remote_side. This is documented under adjacency list relationships. For declarative you'd do something like this:
class Tag(Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
label = Column(String)
parent_id = Column(Integer, ForeignKey('tag.id'))
parent = relationship('Tag', remote_side=[id])
If you want the reverse relation also, add backref='children' to the relationship definition.
If you need children, you need to use uselist:
class Tag(Base):
__tablename__ = 'tag'
id = Column(Integer, primary_key=True)
label = Column(String)
child_id = Column(Integer, ForeignKey('tag.id'))
children = relation('Tag', remote_side=[id], uselist=True)
class Company(BaseModel):
__tablename__ = 'companies'
companyName = db.Column(db.String(50))
contactPerson = db.Column(db.String(50))
email = db.Column(db.String(50))
mobile = db.Column(db.String(20))
parentID = db.Column(db.Integer, db.ForeignKey('companies.id')) # parent company ID
childrenCompany = db.relationship('Company', remote_side='Company.id',
backref=db.backref('children_company')) # parent Company
use:
In [2]: company_query = Company.query.get_or_404(1)
In [3]: company_query.children_company
Out[3]:
[<app.models.user.Company at 0x10f527850>,
<app.models.user.Company at 0x10f527c10>]
parent = relation('Tag') — see http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#configuring-relations.

Categories

Resources