SQLAlchemy, polymorphic inheritance with classical mapping [duplicate] - sqlalchemy

This question already has an answer here:
Need classic mapper example for SqlAlchemy single table inheritance
(1 answer)
Closed 5 years ago.
I need to use the classical mapping instead of the declarative, for the last two days I am trying to make inheritance work, I tried with the declarative style and it worked but whatever I tried I cant get it to work when using the old mapping style.
class Item(object):
def specialised_method(self):
return "I am not special"
class SpecialisedItem(Item):
__mapper_args__ = {
'polymorphic_identity': 'special',
}
def specialised_method(self):
return "I am special"
orm.mapper(Item, enviroment.tables.items,
polymorphic_on=enviroment.tables.items.c.type,
polymorphic_identity="normal")
# orm.mapper(SpecialisedItem, enviroment.tables.items,polymorphic_on=enviroment.tables.items.c.type,polymorphic_identity='special')
def test_inheritance(request):
enviroment=get_enviroment()
session=enviroment.session
for item in session.query(Item).filter_by(type="special"):
print(item.type,item.specialised_method(),item)
throws:
AssertionError: No such polymorphic_identity 'special' is defined
If I remove the polymorphic_identity="normal" from the Item mapper_args then the Item's special method gets called, It seems that the SpecialisedItem never gets considered as a child of Item.

The issue is probably that you have not passed the inheritance information to mapper. When using classical mapping, the inheritance structure is not inferred.
Try something like:
class Item(object):
def specialised_method(self):
return "I am not special"
class SpecialisedItem(Item):
def specialised_method(self):
return "I am special"
orm.mapper(Item, enviroment.tables.items,
polymorphic_on=enviroment.tables.items.c.type,
polymorphic_identity="normal")
orm.mapper(SpecialisedItem,
enviroment.tables.items,
# you need to specify the parent
inherits=Item,
polymorphic_identity='special')
Note that there is no need to specify polymorphic_on in the mapping for SpecialisedItem. Generally, it will be inferred if there is an appropriate foreign key between the underlying tables, and here you are using the same underlying table so the point is mout.

Related

Neo4j.rb returns models with incorrect class for nodes with multiple labels

I have two ActiveNode models:
class Company
include Neo4j::ActiveNode
end
and
class Entity
include Neo4j::ActiveNode
end
They correspond to the labels "Entity" and "Company", which are attached to the same node. So, a node and be an entity and a company.
In my console, when I attempt the following query:
Entity.where(entity_id: 1).first
It returns a Company object:
#<Company uuid: entity_id: 1>
I don't want that. If I ask for an entity, I want an entity returned. The Entity model have different methods defined than the Company model. Is there anyway I can enforce the correct behavior? It seems pretty pretty counter intuitive that it behaves in this way.
I am using neo4j 3.0 and neo4j.rb 7.0.3
This is a good point. If both labels could be matched, it should use the one for the class which was used to do the find.
I'm curious about your modeling, though. Can a Company node ever not be an Entity or vice versa? Or is, for example, a Company always a kind of an Entity? If so, you might want to use inheritence:
class Entity
include Neo4j::ActiveNode
end
class Company < Entity
# No need to include Neo4j::ActiveNode
end
But it's partially a question of if it makes sense for Company nodes to inherit the behavior/logic of Entity

Find Table object in query

Using sqlalchemy 0.7.2
Is there a way to find the table class from the query object? For example:
q = session.query(Customers)
how can I find Customers in q? Possible? Not Possible?
Yes. You need column_descriptions.
It's a long road to the table, though. sqlalchemy.orm.Query.column_descriptions returns a list of dicts, describing each query entity as it was given to query. in your example, there's only one entity, so you need the first item from that list. And since you're interested in the type of the query entity, rather than its' structure, you want the "type" key from that list:
q_entity = q.column_descriptions[0]['type']
assert q_entity == Customer
Accessing the table for the mapped class requires snooping around in the mapper subsystem. for that, you should use manager_of_class. The table is accessible from the manager through the mapper.mapped_table attribute:
from sqlalchemy.orm.attribute import manager_of_class
q_table = manager_of_class(q_entity).mapper.mapped_table
Resist the urge to skip strait to the mapper through Customer.__mapper__, or even Customer.__table__; That's specific to sqlalchemy.ext.declarative, and won't work with classes that are mapped by other means.

Polymorphic belongsTo in many to many mapping in grails?

So i know this is possible using a superclass, however, this is very limiting in flexibility. So my question is then, can i use an interface? Something ala.
interface Taggable {
/*Adds tag(s) and returns a list of currently set tags*/
List<String> addTags(String ... tag)
/*Removes tag(s) and returns a list of currently set tags*/
List<String> removeTags(String ... tag)
}
class User implements Taggable {
String username
static hasMany = [tags:Tag]
}
class Tag {
String name
static hasMany = [references:Taggable]
static belongsTo = Taggable
static constraints = {
name(nullable: false, blank: false, unique: true)
}
}
Im interested in a reference back to the object who has the following tag. This object however can't extend a concrete class. Thats why im wondering if this can be done with an interface instead.
So, can it be done?
Hibernate can map an interface - see example. I doubt if Grails supports this in by-convention mapping - but you can try using the mapping annotations from example above, or XML config.
edit: answering a comment question:
On a database level, you have to have a Taggable table for Tag.References to reference with a foreign key.
Discriminator will NOT defeat polymorphism, if it's added automatically - for instance, in table-per-hierarchy mapping, Hibernate/Gorm adds a class field in order to find out a concrete class when reading object from db.
If you map your Taggables to two tables - Taggable part to Taggable and everything else to specific table, referenced 1:1 - all the discriminator work should be done for you by Hibernate.
BTW class field is pretty long - it contains fully qualified class name.
edit 2:
Either way, it's getting pretty complex, and I'd personally go with the approach I suggested in another question:
dynamically query all the classes with Taggable interface for hasMany=[tags:Tag] property;
or, less preferable - to have a hand-crafted child table and a discriminator.

What's the most appropriate way to expose lists inside a class?

Imagine the following model:
A Table has many Rows
A Row has many Cells
What would be the preferable interface to deal with these classes in a "object oriented way"?
1 - Provide access to the properties rows / cells (Not necessarily exposing the underlying data structures, but creating for example a class RowCollection...)
my_table = new Table()
my_table.rows.add([1,2,3])
my_row = my_table.rows.get(0)
my_row.cells.get(0)
for(cell in my_row.cells) {}
...
2 - Or provide the methods directly in the Table and Row classes
my_table = new Table()
my_table.add_row([1,2,3])
my_row = my_table.get_row(0)
my_row.get_cell(0)
for(cell in my_row.get_cells) {}
...
3 - None of the above...
I think that the answer is largely subjective. If we go by your example, providing methods or properties of your class to return a value by a row/column reference might be appropriate. These could be implemented concurrently, eg:
myClass.Row[x].Column[y]
myClass.Column[y].Row[x]
myClass.Cell[x,y]
You might also decide that it is better to expose a list directly, if the data "rows" are finite:
myClass.SomeArrayOfValues[itemIndex]
I notice you using phrases like "tables" and "rows", so I might assume you wish to have your class represent a database or similar structure, but you might find that while it may be efficient to store the data that way, you might find that exposing the data in another form may make more sense to the user of your class.
In the end, how you choose to do this should really be designed to reflect the purpose of the data itself and the system you are modelling, and that can only be decided on a case-by-case basis.
Based on your comment regarding the usage, "The main use case is adding, sorting and iterating the values," I would probably not allow individual elements to be retrieved, but instead have the user provide a functor to act upon the stored elements. Expressed in C++.
class Table
{
public:
Table();
//Table(unsigned int numberOfRows, unsigned int numberOfCells);
void addRow();
void addCell();
//Throw exception if out of range or don't supply these functions if not needed by user.
void removeRow(unsigned int rowNumber);
void removeCell(unsigned int rowNumber, unsigned int cellNumber);
//Iterate over entire table
template<class Pred>
void forEach(Pred pred);
//Iterate over a specific row, throw exception if row is out of range.
template<class Pred>
void forEach(unsigned int row, Pred pred);
}
You will have to tailor the add/update/remove calls based on how you plan on inputting/updating data. This design is strongly oriented towards manipulating collections of elements. The positives of this design is that you are not committing your user to the specific underlying structure of how you are representing the Table. This is in keeping with the Law of Demeter.
If you need to access specific individual elements, you will want a different approach or make it an extension of what's already provided here.
Consider how many getters and setters you can get rid of. A robust OO design has objects exporting behavior to each other, not data. For example, the skeleton of a getter/setter model of a Person:
class Person:
def set_name(value):
def get_name:
def set_age(value):
def get_age:
def set_drink(value):
def get_drink:
def set_favorite_drink(value):
def get_favorite_drink:
And here's some (pseudo-)code that uses Person:
def order_drink(person)
if person.age >= 21:
puts "#{person.name} can have a drink"
person.drink = bar.order(person.favorite_drink)
else:
puts "#{person.name} cannot drink (legally)."
Here's how you can have a person with no getters or setters involved in ordering a drink:
class Person:
def order_drink_from(bar):
if self.age >= 21:
puts "#{self.name} can have a drink"
self.drink = bar.order(favorite_drink)
else:
puts "#{self.name} cannot drink (legally)"
used like this:
person.order_drink_from(bar)
I won't say that you'll never need getters in an OO program. But I will say this: setters, especially, ought to make you rethink the design. And every time you write either a getter or a setter, let a little voice in the back of your head ask you if there's a way to have the objects export behavior rather than data.
It depends on how you intend to access the Rows/Cells.
There is no one correct way of doing it - you need to decide how you want to access them and build your objects to expose them in the way you want to consume them.
It depends a lot on the data and what you plan to do with it.
Will users want individual cells? Individual rows/columns? Subsections of rows/columns?
Probably the cleanest way is to provide functor interfaces. Provide one or more functions that will run the functors on every element, or on a subset defined in the functor.
That may work less well if users need to access complex combinations of cells.

What is the difference between a property and an instance variable?

I think I've been using these terms interchangably / wrongly!
Iain, this is basically a terminology question and is, despite the "language-agnostic" tag associated with this question, very language/environment related.
For design discussions sake, property and instance variable can be used interchangeably, since the idea is that a property is a data item describing an object.
When talking about a specific language these two can be different. For example, in C# a property is actually a function that returns an object, while an instance variable is a non-static member variable of a class.
Hershi is right about this being language specific. But to add to the trail of language specific answers:
In python, an instance variable is an attribute of an instance, (generally) something that is referred to in the instance's dictionary. This is analogous to members or instance variables in Java, except everything is public.
Properties are shortcuts to getter/setter methods that look just like an instance variable. Thus, in the following class definition (modified from Guido's new style object manifesto):
class C(object):
def __init__(self):
self.y = 0
def getx(self):
if self.y < 0: return 0
else: return self.y
def setx(self, x):
self.y = x
x = property(getx, setx)
>>> z = C()
>>> z.x = -3
>>> print z.x
0
>>> print z.y
-3
>>> z.x = 5
>>> print z.x
5
>>> print z.y
5
y is an instance variable of z, x is a property. (In general, where a property is defined, there are some techniques used to obscure the associated instance variable so that other code doesn't directly access it.) The benefit of properties in python is that a designer doesn't have to go around pre-emptively encapsulating all instance variables, since future encapsulation by converting an instance variable to a property should not break any existing code (unless the code is taking advantage of loopholes your encapsulation is trying to fix, or relying on class inspection or some other meta-programming technique).
All this is a very long answer to say that at the design level, it's good to talk about properties. It is agnostic as to what type of encapsulation you may need to perform. I guess this principle isn't language agnostic, but does apply to languages beside python.
In objective c, a property is an instance variable which can take advantage of an overloaded dot operator to call its setter and getter. So my.food = "cheeseburger" is actually interpreted as [my setFood:"cheeseburger"]. This is another case where the definition is definitely not language agnostic because objective-c defines the #property keyword.
code example done in C#
public class ClassName
{
private string variable;
public string property
{
get{ return variable; }
set { variable = value; }
}
}
Maybe thats because you first came from C++ right?!
In my school days I had professors that said class properties or class atributes all the time. Since I moved to the Java C# world, I started hearing about members. Class members, instance members...
And then Properties apear! in Java and .NET. So I think its better for you to call it members. Wheather they are instance members (or as you called it instance variable) or class Members....
Cheers!
A property can, and I suppose mostly does, return an instance variable but it can do more. You could put logic in a property, aggregate values or update other instance variables etc. I think it is best to avoid doing so however. Logic should go into methods.
In Java we have something called JavaBeans Properties, but that is basically a instance variable that follows a certain naming pattern for its getter and setter.
At add to what has been said, in a langauge like C#, a property is essentially a get and set function. As a result, it can have custom logic that runs in addition to the getting/setting. An instance variable cannot do this.
A property is some sort of data associated with an object. For instance, a property of a circle is its diameter, and another is its area.
An instance variable is a piece of data that is stored within an object. It doesn't necessarily need to correspond directly with a property. For instance (heh), a circle may store its radius in an instance variable, and calculate its diameter and area based on that radius. All three are still properties, but only the radius is stored in an instance variable.
Some languages have the concept of "first class" properties. This means that to a client application, the property looks and is used like an instance variable. That is, instead of writing something like circle.getDiameter(), you would write circle.diameter, and instead of circle.setRadius(5), you would write circle.radius = 5.
In contrast to the other answers given, I do think that there is a useful distinction between member variables and properties that is language-agnostic.
The distinction is most apparent in component-oriented programming, which is useful anywhere, but easiest to understand in a graphical UI. In that context, I tend to think of the design-time configuration of a component as manipulating the "properties" of an object. For example, I choose the foreground and background colors, the border style, and font of a text input field by setting its properties. While these properties could be changed at runtime, they typically aren't. At runtime, a different set of variables, representing the content of the field, are much more likely to be read and written. I think of this information as the "state" of the component.
Why is this distinction useful? When creating an abstraction for wiring components together, usually only the "state" variables need to be exposed. Going back to the text field example, you might declare an interface that provides access to the current content. But the "properties" that control the look and feel of the component are only defined on a concrete implementation class.