|
| 1 | +Bake Queries |
| 2 | +============ |
| 3 | + |
| 4 | +Baked queries are used to boost execution performance for constantly-used queries. |
| 5 | +Similar to the :doc:`orm/extensions/baked` in SQLAlchemy, GINO could also cache the |
| 6 | +object’s construction and string-compilation steps. Furthermore, GINO automatically |
| 7 | +manages a prepared statement for each baked query in every active connection in the |
| 8 | +pool. Executing baked queries is at least 40% faster than running normal queries, but |
| 9 | +you need to **bake them before creating the engine**. |
| 10 | + |
| 11 | +GINO provides two approaches for baked queries: |
| 12 | + |
| 13 | +1. Low-level :class:`~gino.bakery.Bakery` API |
| 14 | +2. High-level :meth:`Gino.bake() <gino.api.Gino.bake>` integration |
| 15 | + |
| 16 | + |
| 17 | +Use Bakery with Bare Engine |
| 18 | +--------------------------- |
| 19 | + |
| 20 | +First, we need a bakery:: |
| 21 | + |
| 22 | + import gino |
| 23 | + |
| 24 | + bakery = gino.Bakery() |
| 25 | + |
| 26 | +Then, let's bake some queries:: |
| 27 | + |
| 28 | + db_time = bakery.bake("SELECT now()") |
| 29 | + |
| 30 | +Or queries with parameters:: |
| 31 | + |
| 32 | + user_query = bakery.bake("SELECT * FROM users WHERE id = :uid") |
| 33 | + |
| 34 | +Let's assume we have this ``users`` table defined in SQLAlchemy Core:: |
| 35 | + |
| 36 | + import sqlalchemy as sa |
| 37 | + |
| 38 | + metadata = sa.MetaData() |
| 39 | + user_table = sa.Table( |
| 40 | + "users", metadata, |
| 41 | + sa.Column("id", sa.Integer, primary_key=True), |
| 42 | + sa.Column("name", sa.String), |
| 43 | + ) |
| 44 | + |
| 45 | +Now we can bake a similar query with SQLAlchemy Core:: |
| 46 | + |
| 47 | + user_query = bakery.bake( |
| 48 | + sa.select([user_table]).where(user.c.id == sa.bindparam("uid")) |
| 49 | + ) |
| 50 | + |
| 51 | +These baked queries are usually global, and supposed to be shared across the |
| 52 | +application. To run them, we need an engine with the bakery:: |
| 53 | + |
| 54 | + engine = await gino.create_engine("postgresql://localhost/", bakery=bakery) |
| 55 | + |
| 56 | +By doing so, GINO will bake the queries in the bakery. As new connections are added to |
| 57 | +the DB pool, the prepared statements are automatically created behind the scene. |
| 58 | + |
| 59 | +To execute the baked queries, you could treat the :class:`~gino.bakery.BakedQuery` |
| 60 | +instances as if they are the queries themselves, for example:: |
| 61 | + |
| 62 | + now = await engine.scalar(db_time) |
| 63 | + |
| 64 | +Pass in parameter values:: |
| 65 | + |
| 66 | + row = await engine.first(user_query, uid=123) |
| 67 | + |
| 68 | + |
| 69 | +Use the :class:`~gino.api.Gino` Integration |
| 70 | +-------------------------------------------- |
| 71 | + |
| 72 | +In a more common scenario, there will be a :class:`~gino.api.Gino>` instance, which has |
| 73 | +usually a ``bind`` set - either explicitly or by the Web framework extensions:: |
| 74 | + |
| 75 | + from gino import Gino |
| 76 | + |
| 77 | + db = Gino() |
| 78 | + |
| 79 | + async def main(): |
| 80 | + async with db.with_bind("postgresql://localhost/"): |
| 81 | + ... |
| 82 | + |
| 83 | +A :class:`~gino.bakery.Bakery` is automatically created in the ``db`` instance, and fed |
| 84 | +to the engine implicitly. You can immediately start to bake queries without further |
| 85 | +ado:: |
| 86 | + |
| 87 | + class User(db.Model): |
| 88 | + __tablename__ = "users" |
| 89 | + |
| 90 | + id = db.Column(db.Integer, primary_key=True) |
| 91 | + name = db.Column(db.String) |
| 92 | + |
| 93 | + db_time = db.bake("SELECT now()") |
| 94 | + user_getter = db.bake(User.query.where(User.id == db.bindparam("uid"))) |
| 95 | + |
| 96 | +And the execution is also simplified with the same ``bind`` magic:: |
| 97 | + |
| 98 | + async def main(): |
| 99 | + async with db.with_bind("postgresql://localhost/"): |
| 100 | + print(await db_time.scalar()) |
| 101 | + |
| 102 | + user: User = await user_getter.first(uid=1) |
| 103 | + print(user.name) |
| 104 | + |
| 105 | +To make things more easier, you could even define the baked queries directly on the |
| 106 | +model:: |
| 107 | + |
| 108 | + class User(db.Model): |
| 109 | + __tablename__ = "users" |
| 110 | + |
| 111 | + id = db.Column(db.Integer, primary_key=True) |
| 112 | + name = db.Column(db.String) |
| 113 | + |
| 114 | + @db.bake |
| 115 | + def getter(cls): |
| 116 | + return cls.query.where(cls.id == db.bindparam("uid")) |
| 117 | + |
| 118 | + @classmethod |
| 119 | + async def get(cls, uid): |
| 120 | + return await cls.getter.one_or_none(uid=uid) |
| 121 | + |
| 122 | +Here GINO treats the ``getter()`` as a :meth:`~gino.declarative.declared_attr` with |
| 123 | +``with_table=True``, therefore it takes one positional argument ``cls`` for the ``User`` |
| 124 | +class. |
| 125 | + |
| 126 | + |
| 127 | +How to customize loaders? |
| 128 | +------------------------- |
| 129 | + |
| 130 | +If possible, you could bake the additional execution options into the query:: |
| 131 | + |
| 132 | + user_getter = db.bake( |
| 133 | + User.query.where(User.id == db.bindparam("uid")).execution_options( |
| 134 | + loader=User.load(comment="Added by loader.") |
| 135 | + ) |
| 136 | + ) |
| 137 | + |
| 138 | +The :meth:`~gino.bakery.Bakery.bake` method accepts keyword arguments as execution |
| 139 | +options to e.g. simplify the example above into:: |
| 140 | + |
| 141 | + user_getter = db.bake( |
| 142 | + User.query.where(User.id == db.bindparam("uid")), |
| 143 | + loader=User.load(comment="Added by loader."), |
| 144 | + ) |
| 145 | + |
| 146 | +If the query construction is complex, :meth:`~gino.bakery.Bakery.bake` could also be |
| 147 | +used as a decorator:: |
| 148 | + |
| 149 | + @db.bake |
| 150 | + def user_getter(): |
| 151 | + return User.query.where(User.id == db.bindparam("uid")).execution_options( |
| 152 | + loader=User.load(comment="Added by loader.") |
| 153 | + ) |
| 154 | + |
| 155 | +Or with short execution options:: |
| 156 | + |
| 157 | + @db.bake(loader=User.load(comment="Added by loader.")) |
| 158 | + def user_getter(): |
| 159 | + return User.query.where(User.id == db.bindparam("uid")) |
| 160 | + |
| 161 | +Meanwhile, it is also possible to override the loader at runtime:: |
| 162 | + |
| 163 | + user: User = await user_getter.load(User).first(uid=1) |
| 164 | + print(user.name) # no more comment on user! |
| 165 | + |
| 166 | +.. hint:: |
| 167 | + |
| 168 | + This override won't affect the baked query - it's used only in this execution. |
| 169 | + |
| 170 | + |
| 171 | +What APIs are available on :class:`~gino.bakery.BakedQuery`? |
| 172 | +------------------------------------------------------------ |
| 173 | + |
| 174 | +:class:`~gino.bakery.BakedQuery` is a :class:`~gino.api.GinoExecutor`, so it inherited |
| 175 | +all the APIs like :meth:`~gino.api.GinoExecutor.all`, |
| 176 | +:meth:`~gino.api.GinoExecutor.first`, :meth:`~gino.api.GinoExecutor.one`, |
| 177 | +:meth:`~gino.api.GinoExecutor.one_or_none`, :meth:`~gino.api.GinoExecutor.scalar`, |
| 178 | +:meth:`~gino.api.GinoExecutor.status`, :meth:`~gino.api.GinoExecutor.load`, |
| 179 | +:meth:`~gino.api.GinoExecutor.timeout`, etc. |
| 180 | + |
| 181 | +:class:`~gino.api.GinoExecutor` is actually the chained ``.gino`` helper API seen |
| 182 | +usually in queries like this:: |
| 183 | + |
| 184 | + user = await User.query.where(User.id == 123).gino.first() |
| 185 | + |
| 186 | +So a :class:`~gino.bakery.BakedQuery` can be seen as a normal query with the ``.gino`` |
| 187 | +suffix, plus it is directly executable. |
| 188 | + |
| 189 | +.. seealso:: |
| 190 | + |
| 191 | + Please see API document of :mod:`gino.bakery` for more information. |
0 commit comments