加载器与关系

Loaders are used to load database row results into objects.

GINO doesn’t support automated relationship. We insist explicit code style in asynchronous programming and that conflicts with some usual ORM relationship patterns. Instead, GINO provides a rich loader system to assist you with manual relationships through foreign keys or whatever magic. That means, you are responsible for writing the queries, and GINO could assemble objects for you from the database result with loaders you defined.

Model Loader

The Model Loader is the magic behind GINO CRUD to translate database rows into model objects. Through CRUD, Model Loaders are assembled internally for you, you can still use it directly. For example, an ordinary query that returns rows may look like this:

  1. query = db.select([User])
  2. rows = await query.gino.all()

In order to load rows into User objects, you can provide an execution option loader with a new ModelLoader instance:

  1. from gino.loader import ModelLoader
  2. query = db.select([User])
  3. query = query.execution_options(loader=ModelLoader(User))
  4. users = await query.gino.all()

The ModelLoader would then load each database row into a User object. As this is frequently used, GINO made it a shortcut:

  1. query = db.select([User])
  2. query = query.execution_options(loader=User.load())
  3. users = await query.gino.all()

And another shortcut:

  1. query = db.select([User])
  2. query = query.execution_options(loader=User)
  3. users = await query.gino.all()

小技巧

User as loader is transformed into ModelLoader(User) by Loader.get(), explained later in “Loader Expression”.

And again:

  1. query = db.select([User])
  2. users = await query.gino.load(User).all()

This is identical to the normal CRUD query:

  1. users = await User.query.gino.all()

Loader Expression

So Loaders are actually row post-processors, they define how the database rows should be processed and returned. Other than ModelLoader, there’re also other loaders that could turn the database rows into different results like based on your definition. GINO provides the Loader Expression feature for you to easily assemble complex loaders.

Here is an example using all loaders at once:

  1. uid, user, sep, cols = await db.select([User]).gino.load(
  2. (
  3. User.id,
  4. User,
  5. '|',
  6. lambda row, ctx: len(row),
  7. )
  8. ).first()

Let’s check this piece by piece. Overall, the argument of load() is a tuple. This is interpreted into a TupleLoader, with each item of the tuple interpreted as a Loader Expression recursively. That means, it is possible to nest tuples. The result of a TupleLoader is a tuple.

Column in Loader Expressions are interpreted as ColumnLoader. It simply outputs the value of the given column in the database row. It is your responsibility to select the column in the query. Please note, ColumnLoader uses the given column as index to look for the value, not the name of the column. This is a SQLAlchemy feature to support selecting multiple columns with the same name from different tables in the same query, especially for ORM. So if you are using raw textual SQL and wishing to use ColumnLoader, you’ll have to declare columns for the query:

  1. now = db.Column('time', db.DateTime())
  2. result = await db.first(db.text(
  3. 'SELECT now() AT TIME ZONE \'UTC\''
  4. ).columns(
  5. now,
  6. ).gino.load(
  7. ('now:', now)
  8. ).query)
  9. print(*result) # now: 2018-04-08 08:23:02.431847

Let’s get back to previous example. The second item in the tuple is a GINO model class. As we’ve presented previously, it is interpreted into a ModelLoader. By default, it loads the values of all the columns of the give model, and create a new model instance with the values.

小技巧

For a complex loader expression, the same row is given to all loaders, so it doesn’t matter User.id is already used before the model loader.

The last item in the tuple is a callable, it will be called for each row with two arguments: the first argument is the row itself, while the second is a contextual value provided by outer loader, we’ll get to that later. Similar to map(), the return value of the call will be the loaded result.

At last, if none of the above types matches a Loader Expression, it will be treated as is. Like the '|' separator, it will show up as the third item in every result returned by the query.

Many-to-One Relationship

A classic many-to-one relationship is also known as referencing - the model on the “many” end keeps a single reference to the model on the “one” end. Although GINO does not enforce it, usually people use a foreign key for the reference:

  1. class Parent(db.Model):
  2. __tablename__ = 'parents'
  3. id = db.Column(db.Integer, primary_key=True)
  4. class Child(db.Model):
  5. __tablename__ = 'children'
  6. id = db.Column(db.Integer, primary_key=True)
  7. parent_id = db.Column(db.Integer, db.ForeignKey('parents.id'))

So every child has a single parent (or no parent at all), while one parent may have multiple children. GINO provides an easy way to load children with their parents:

  1. async for child in Child.load(parent=Parent).gino.iterate():
  2. print(f'Parent of {child.id} is {child.parent.id}')

As you may have noticed, Child.load is exactly the shortcut to create ModelLoader in the very first example. With some additional keyword arguments, Child.load(parent=Parent) is still a ModelLoader for Child, the model loader is at the same time a query builder. It is identical to do this:

  1. async for child in Child.load(parent=Parent).query.gino.iterate():
  2. print(f'Parent of {child.id} is {child.parent.id}')

The query dynamically generates a SQLAlchemy query based on the knowledge of the loader, and set the loader as execution option at the same time. The Loader simply forwarded unknown attributes to its query, that’s why .query can be omitted.

For ModelLoader, all keyword arguments are interpreted as subloaders, their results will be set to the attributes of the result model under the corresponding keys using setattr(). For example, Parent is interpreted as ModelLoader(Parent) which loads Parent instances, and Parent instances are set as the parent attribute of the outer Child instance.

警告

If multiple children references the same parent, then each child owns a unique parent instance with identical values.

小技巧

You don’t have to define parent attribute on Child. But if you do, you gain the ability to customize how parent is stored or retrieved. For example, let’s store the parent instance as _parent:

  1. class Child(db.Model):
  2. __tablename__ = 'children'
  3. id = db.Column(db.Integer, primary_key=True)
  4. parent_id = db.Column(db.Integer, db.ForeignKey('parents.id'))
  5. _parent = None
  6. @property
  7. def parent(self):
  8. return self._parent
  9. @parent.setter
  10. def parent(self, value):
  11. self._parent = value

The query builder works recursively. For ModelLoader, it uses LEFT OUTER JOIN to connect the FROM clauses, in order to achieve many-to-one scenario. The ON clause is determined automatically by foreign keys. You can also customize the ON clause in case there is no foreign key (a promise is a promise):

  1. loader = Child.load(parent=Parent.on(Child.parent_id == Parent.id))
  2. async for child in loader.query.gino.iterate():
  3. print(f'Parent of {child.id} is {child.parent.id}')

And subloaders can be nested:

  1. subloader = Child.load(parent=Parent.on(Child.parent_id == Parent.id))
  2. loader = Grandson.load(parent=subloader.on(Grandson.parent_id == Child.id))

By now, GINO supports only loading many-to-one joined query. To modify a relationship, just modify the reference column values.

Self Referencing

警告

Experimental feature.

Self referencing is usually used to create a tree-like structure. For example:

  1. class Category(db.Model):
  2. __tablename__ = 'categories'
  3. id = db.Column(db.Integer, primary_key=True)
  4. parent_id = db.Column(db.Integer, db.ForeignKey('categories.id'))

In order to load leaf categories with their parents, an alias is needed:

  1. Parent = Category.alias()

Then the query would be something like this:

  1. parents = db.select([Category.parent_id])
  2. query = Category.load(parent=Parent.on(
  3. Category.parent_id == Parent.id
  4. )).where(
  5. ~Category.id.in_(db.select([Category.alias().parent_id]))
  6. )
  7. async for c in query.gino.iterate():
  8. print(f'Leaf: {c.id}, Parent: {c.parent.id}')

The generated SQL looks like this:

  1. SELECT categories.id, categories.parent_id, categories_1.id, categories_1.parent_id
  2. FROM categories LEFT OUTER JOIN categories AS categories_1
  3. ON categories.parent_id = categories_1.id
  4. WHERE categories.id NOT IN (
  5. SELECT categories_2.parent_id
  6. FROM categories AS categories_2
  7. )

Other Relationships

GINO 0.7.4 introduced an experimental distinct feature to reduce a result set with loaders, combining rows under specified conditions. This made it possible to build one-to-many relationships. Using the same parent-child example above, we could load distinct parents with all their children:

  1. class Parent(db.Model):
  2. __tablename__ = 'parents'
  3. id = db.Column(db.Integer, primary_key=True)
  4. def __init__(self, **kw):
  5. super().__init__(**kw)
  6. self._children = set()
  7. @property
  8. def children(self):
  9. return self._children
  10. @children.setter
  11. def add_child(self, child):
  12. self._children.add(child)
  13. class Child(db.Model):
  14. __tablename__ = 'children'
  15. id = db.Column(db.Integer, primary_key=True)
  16. parent_id = db.Column(db.Integer, db.ForeignKey('parents.id'))
  17. query = Child.outerjoin(Parent).select()
  18. parents = await query.gino.load(
  19. Parent.distinct(Parent.id).load(add_child=Child)).all()

Here the query is still child outer-joining parent, but the loader is loading parent instances with distinct IDs only, while storing all their children through the add_child setter property. In detail for each row, a parent instance is firstly loaded if no parent instance with the same ID was loaded previously, or the same parent instance will be reused. Then a child instance is loaded from the same row, and fed to the possibly reused parent instance by parent.add_child = new_child.

Distinct loaders can be nested to load hierarchical data, but it cannot be used as a query builder to automatically generate queries.

GINO provides no additional support for one-to-one relationship - the user should make sure that the query produces rows of distinct instance pairs, and load them with regular GINO model loaders. When in doubt, the distinct feature can be used on both sides, but you’ll have to manually deal with the conflict if more than one related instances are found. For example, we could keep only the last child for each parent:

  1. class Parent(db.Model):
  2. __tablename__ = 'parents'
  3. id = db.Column(db.Integer, primary_key=True)
  4. def __init__(self, **kw):
  5. super().__init__(**kw)
  6. self._child = None
  7. @property
  8. def child(self):
  9. return self._child
  10. @child.setter
  11. def child(self, child):
  12. self._child = child
  13. class Child(db.Model):
  14. __tablename__ = 'children'
  15. id = db.Column(db.Integer, primary_key=True)
  16. parent_id = db.Column(db.Integer, db.ForeignKey('parents.id'))
  17. query = Child.outerjoin(Parent).select()
  18. parents = await query.gino.load(
  19. Parent.distinct(Parent.id).load(child=Child.distinct(Child.id))).all()

Similarly, you can build many-to-many relationships in the same way:

  1. class Parent(db.Model):
  2. __tablename__ = 'parents'
  3. id = db.Column(db.Integer, primary_key=True)
  4. def __init__(self, **kw):
  5. super().__init__(**kw)
  6. self._children = set()
  7. @property
  8. def children(self):
  9. return self._children
  10. def add_child(self, child):
  11. self._children.add(child)
  12. child._parents.add(self)
  13. class Child(db.Model):
  14. __tablename__ = 'children'
  15. id = db.Column(db.Integer, primary_key=True)
  16. def __init__(self, **kw):
  17. super().__init__(**kw)
  18. self._parents = set()
  19. @property
  20. def parents(self):
  21. return self._parents
  22. class ParentXChild(db.Model):
  23. __tablename__ = 'parents_x_children'
  24. parent_id = db.Column(db.Integer, db.ForeignKey('parents.id'))
  25. child_id = db.Column(db.Integer, db.ForeignKey('children.id'))
  26. query = Parent.outerjoin(ParentXChild).outerjoin(Child).select()
  27. parents = await query.gino.load(
  28. Parent.distinct(Parent.id).load(add_child=Child.distinct(Child.id))).all()

Likewise, there is for now no way to modify the relationships automatically, you’ll have to manually create, delete or modify ParentXChild instances.

Advanced Usage of Loaders

You could use combined loaders flexibly in complex queries - loading relationships is just one special use case. For example, you could load the count of visits at the same time of loading each user, by using a tuple loader with two items - model loader for the user, and column loader for the count:

  1. import asyncio
  2. import random
  3. import string
  4. import gino
  5. from gino.loader import ColumnLoader
  6. db = gino.Gino()
  7. class User(db.Model):
  8. __tablename__ = 'users'
  9. id = db.Column(db.Integer(), primary_key=True)
  10. name = db.Column(db.Unicode())
  11. class Visit(db.Model):
  12. __tablename__ = 'visits'
  13. id = db.Column(db.Integer(), primary_key=True)
  14. time = db.Column(db.DateTime(), server_default='now()')
  15. user_id = db.Column(db.ForeignKey('users.id'))
  16. async def main():
  17. async with db.with_bind('postgresql://localhost/gino'):
  18. await db.gino.create_all()
  19. for i in range(random.randint(5, 10)):
  20. u = await User.create(
  21. name=''.join(random.choices(string.ascii_letters, k=10)))
  22. for v in range(random.randint(10, 20)):
  23. await Visit.create(user_id=u.id)
  24. visits = db.func.count(Visit.id)
  25. q = db.select([
  26. User,
  27. visits,
  28. ]).select_from(
  29. User.outerjoin(Visit)
  30. ).group_by(
  31. *User,
  32. ).gino.load((User, ColumnLoader(visits)))
  33. async with db.transaction():
  34. async for user, visits in q.iterate():
  35. print(user.name, visits)
  36. await db.gino.drop_all()
  37. asyncio.run(main())

Using alias to get ID-ascending pairs from the same table:

  1. ua1 = User.alias()
  2. ua2 = User.alias()
  3. join_query = select([ua1, ua2]).where(ua1.id < ua2.id)
  4. loader = ua1.load('id'), ua2.load('id')
  5. result = await join_query.gino.load(loader).all()
  6. print(result) # e.g. [(1, 2), (1, 3), (2, 3)]

Potentially there could be a lot of different use cases of loaders. We’ll add more inspiration here in the future.