On Feb 16, 2014, at 7:05 PM, Alexander Perepelica <
perepel...@gmail.com> wrote:
> Ok, I understand, but how can I bind model with this session? Must I use declarative_base or mapping approach?
the concept of “the thing that talks to a database” and “the kinds of structures that write SQL for us” are separate. You might have seen some old tutorials that talk about this thing called “metadata.bind = engine”, or even “BoundMetaData”, you should ignore that stuff completely.
so the Session here is the “thing that talks to a database”. It’s a semi-short lived object that usually spans the length of a transaction, or possibly several, but always within the scope of “here’s some things we want to do with a database connection”:
sess = Session(engine)
the mapping()/declarative_base() all that, knows nothing about any Session or Engine. That has to do with the Table object, which is a thing that talks about what a hypothetical database table looks like, which is then inside a collection of other Table objects called a MetaData, which is essentially just a dictionary, and then mapping has to do with taking any kind of Python class you’ve made and linking it to a Table. Declarative base just does class->mapper->Table with less typing. You do whatever method you want to get a Table, and if you want, a class mapped to it. Then you can create SQL constructs using those objects, and those SQL constructs, when passed along to a Session or Engine, get turned into strings and sent to a real database over a connection.
With the ORM, the connection point is kind of automatic, because you start with a Session:
sess = Session(engine)
then the Session is a factory for a Query:
my_query = sess.query(MyMappedClass).filter_by(id=7)
the “my_query” above is a Query object that refers to our “session”. This is just how the API is, it really doesn’t matter too much that it is linked to the Session as of yet, since it hasn’t don’t anything with a database yet.
But when you say this:
my_query.all()
now we’re going to look at self.session, which will look at self.bind, which will do “conn = self.bind.connect()) and then “conn.execute(my_query.statement)”.
So the linkage of “databases” to a “model” is made as late as possible, and only within the scope of when a query actually executes.