Skip to content

Commit f10df8e

Browse files
committed
Docs cleanup, cont.
1 parent 0f39030 commit f10df8e

10 files changed

Lines changed: 60 additions & 109 deletions

File tree

docs/peewee/asyncio.rst

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ Example
3838
-------
3939

4040
``playhouse.pwasyncio`` contains the async database implementations. Typically
41-
this is the only thing you will need in order to use Peewee with asyncio:
41+
this is the only thing you need to use Peewee with asyncio:
4242

4343
.. code-block:: python
4444
@@ -110,14 +110,13 @@ performs I/O. Whenever a query executes, control switches to the event loop and
110110
the I/O coroutine is awaited like any other awaitable. Then the original call
111111
resumes with the result.
112112

113-
This is real asyncio, NOT gevent-style concurrency. Nothing is
113+
This is real asyncio, not gevent-style concurrency. Nothing is
114114
monkey-patched, no sockets are wrapped, and the event loop is the ordinary
115115
asyncio loop running the rest of your application.
116116

117-
To show how this works I'll walk through the following example, which uses two
118-
internal primitives ``greenlet_spawn`` (run sync code in a greenlet) and ``await_``
119-
(suspend the sync greenlet, passing control and a coroutine to the async
120-
parent).
117+
The following example uses two internal primitives, ``greenlet_spawn`` (run sync
118+
code in a greenlet) and ``await_`` (suspend the sync greenlet, passing control
119+
and a coroutine to the async parent).
121120

122121
.. code-block:: python
123122
@@ -147,7 +146,7 @@ When this runs:
147146
the bridge between sync and async python. Inside the new greenlet everything
148147
is synchronous, but it can yield coroutines to the async-world parent, which
149148
then awaits them on the loop.
150-
3. Inside the new greenlet we begin executing ``synchronous()`` (it does NOT know
149+
3. Inside the new greenlet we begin executing ``synchronous()`` (it does not know
151150
anything about asyncio). ``a_add(1, 2)`` creates a coroutine, which gets passed
152151
to ``await_()``.
153152
4. Inside ``await_()``, we *switch contexts* back to the parent (async world),
@@ -176,10 +175,9 @@ asynchronously:
176175
177176
In your code you should never need to use ``greenlet_spawn()`` or ``await_()``
178177
directly. Peewee wraps all this in ``a``-prefixed methods and helpers so that the
179-
greenlet machinery remains an implementation detail, but it's worth taking a
180-
look at to understand what's going on. In short, Peewee uses greenlets to pass
181-
coroutines out of synchronous code, so they can be ``await``-ed, at the cost of
182-
two lightweight context switches.
178+
greenlet machinery remains an implementation detail. Peewee uses greenlets to
179+
pass coroutines out of synchronous code, so they can be ``await``-ed, at the cost
180+
of two lightweight context switches.
183181

184182
Async Model Methods
185183
-------------------
@@ -341,7 +339,7 @@ For single-query operations, the async helpers are more direct:
341339
cursor = await query.aexecute()
342340
343341
# Use a transaction:
344-
async with db.atomic() as tx:
342+
async with db.atomic():
345343
await db.run(User.create, name='Bob')
346344
347345
# SELECT and return one model instance (raises DoesNotExist if none).
@@ -435,10 +433,8 @@ Explicit control is also available:
435433
# ... queries ...
436434
await db.aclose() # Release connection back to pool.
437435
438-
Each asyncio task gets its own connection from the pool. **Connections are not
439-
shared between tasks**. Each async task will have its own connection and
440-
transaction state - this prevents bugs that may occur when connections are
441-
shared and transactions end up interleaved across several running tasks.
436+
Each asyncio task gets its own connection and transaction state, so tasks never
437+
interleave each other's transactions.
442438

443439
To shut down completely (e.g. during application teardown):
444440

@@ -491,9 +487,8 @@ writes will not occur "faster", the bottleneck has merely been moved.
491487
Conversely, if you don't have that much load, the async wrapper adds complexity
492488
and overhead for no measurable benefit.
493489

494-
To use SQLite in an async environment anyways, it is strongly recommended to
495-
use WAL-mode at a minimum, which allows multiple readers to co-exist with a
496-
single writer:
490+
To use SQLite in an async environment anyway, use WAL-mode at a minimum, which
491+
allows multiple readers to co-exist with a single writer:
497492

498493
.. code-block:: python
499494

docs/peewee/installation.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,12 @@ following drivers are supported out of the box:
7272
+-----------------------+----------------------------+--------------------------------------------+
7373
| MySQL (alternate) | ``mysql-connector-python`` | :class:`.MySQLConnectorDatabase` |
7474
+-----------------------+----------------------------+--------------------------------------------+
75-
| MariaDB (alternate) | ``mariadb-connector`` | :class:`.MariaDBConnectorDatabase` |
75+
| MariaDB (alternate) | ``mariadb`` | :class:`.MariaDBConnectorDatabase` |
7676
+-----------------------+----------------------------+--------------------------------------------+
7777
| CockroachDB | ``psycopg`` (2 or 3) | :class:`.CockroachDatabase` |
7878
+-----------------------+----------------------------+--------------------------------------------+
7979
| Postgres (extensions) | ``psycopg`` (2 or 3) | :class:`.PostgresqlExtDatabase` |
8080
+-----------------------+----------------------------+--------------------------------------------+
8181

82-
The three bolded rows cover the majority of deployments. All others are
82+
The bolded rows cover the majority of deployments. All others are
8383
optional; install their drivers when needed.

docs/peewee/query_builder.rst

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ Query Builder
66
Peewee's high-level :class:`Model` and :class:`Field` APIs are built upon
77
lower-level :class:`Table` and :class:`Column` counterparts. While these
88
lower-level APIs are not documented in as much detail as their high-level
9-
counterparts, this document will present an overview with examples that should
10-
hopefully allow you to experiment.
9+
counterparts, this document will present an overview with worked examples.
1110

1211
We'll use the following schema:
1312

@@ -76,8 +75,8 @@ To select the first three notes and print their content, we can write:
7675
the row data, if you wish.
7776

7877
Because we didn't specify any columns, all the columns we defined in the
79-
note's :class:`Table` constructor will be selected. This won't work for
80-
Reminder, as we didn't specify any columns at all.
78+
note's :class:`Table` constructor will be selected. ``Reminder`` declares no
79+
columns, so ``Reminder.select()`` emits ``SELECT * FROM "reminder"`` instead.
8180

8281
To select all notes published in 2018 along with the name of the creator, we
8382
will use :meth:`~Select.join`. We'll also request that rows be returned
@@ -190,7 +189,7 @@ new row is returned):
190189
Note.content: 'meeeeowwww',
191190
Note.timestamp: datetime.datetime.now()}).execute()
192191
193-
It is easy to bulk-insert data, just pass in either:
192+
To bulk-insert data, pass in either:
194193

195194
* A list of dictionaries (all must have the same keys/columns).
196195
* A list of tuples, if the columns are specified explicitly.

docs/peewee/query_library.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ this information?
299299

300300
.. code-block:: sql
301301
302-
SELECT MAX(join_date) FROM members;
302+
SELECT MAX(joindate) FROM members;
303303
304304
.. code-block:: python
305305
@@ -914,7 +914,7 @@ slots, sorted by the number of slots.
914914
915915
SELECT facid, SUM(slots)
916916
FROM bookings
917-
WHERE (date_trunc('month', starttime) = '2012-09-01'::dates)
917+
WHERE (date_trunc('month', starttime) = '2012-09-01'::date)
918918
GROUP BY facid
919919
ORDER BY SUM(slots)
920920
@@ -1090,7 +1090,7 @@ Postgres ONLY.
10901090
.. code-block:: sql
10911091
10921092
SELECT facid, date_part('month', starttime), SUM(slots)
1093-
FROM booking
1093+
FROM bookings
10941094
WHERE date_part('year', starttime) = 2012
10951095
GROUP BY ROLLUP(facid, date_part('month', starttime))
10961096
ORDER BY facid, date_part('month', starttime)

docs/peewee/query_operators.rst

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -216,14 +216,12 @@ Now you can use these custom operators to build richer queries:
216216
Expressions
217217
-----------
218218

219-
Peewee is designed to provide a simple, expressive, and pythonic way of
220-
constructing SQL queries. This section will provide a quick overview of some
221-
common types of expressions.
219+
This section gives an overview of common expression types.
222220

223221
Two common types of objects that are composed to create expressions:
224222

225223
* :class:`Field` instances
226-
* SQL aggregations and functions using :class:`fn`
224+
* SQL aggregations and functions using :func:`fn`
227225

228226
We will assume a simple "User" model with fields for username and other things.
229227
It looks like this:
@@ -260,8 +258,8 @@ arbitrary depth:
260258
# User's username is either charlie or charles
261259
(User.username == 'charlie') | (User.username == 'charles')
262260
263-
# User is active and not a superuser.
264-
(User.is_active & ~User.is_superuser)
261+
# User is active and not an admin.
262+
(User.is_active & ~User.is_admin)
265263
266264
Comparisons can be used with functions as well:
267265

@@ -286,7 +284,7 @@ Expressions allow us to do *atomic updates*:
286284
# when a user logs in we want to increment their login count:
287285
User.update(login_count=User.login_count + 1).where(User.id == user_id)
288286
289-
Expressions can be used in all parts of a query, so experiment!
287+
Expressions can be used in all parts of a query.
290288

291289
Row values
292290
^^^^^^^^^^
@@ -368,10 +366,8 @@ parameters can be fields, values, subqueries, or even nested functions.
368366
Nesting function calls
369367
^^^^^^^^^^^^^^^^^^^^^^
370368

371-
Suppose you need to want to get a list of all users whose username begins with
372-
*a*. There are a couple ways to do this, but one method might be to use some
373-
SQL functions like *LOWER* and *SUBSTR*. To use arbitrary SQL functions, use
374-
the special :func:`fn` object to construct queries:
369+
To get all users whose username begins with *a*, use SQL functions like *LOWER*
370+
and *SUBSTR* via the :func:`fn` object:
375371

376372
.. code-block:: python
377373
@@ -388,8 +384,7 @@ the special :func:`fn` object to construct queries:
388384
SQL Helper
389385
----------
390386

391-
There are times when you may want to simply pass in some arbitrary sql. You can
392-
do this using the special :class:`SQL` class. One use-case is when
387+
To pass arbitrary SQL, use the special :class:`SQL` class. One use-case is
393388
referencing an alias:
394389

395390
.. code-block:: python
@@ -404,7 +399,7 @@ referencing an alias:
404399
# Now we will order by the count, which was aliased to "ct"
405400
query = query.order_by(SQL('ct'))
406401
407-
# You could, of course, also write this as:
402+
# Or equivalently:
408403
query = query.order_by(fn.COUNT(Tweet.id))
409404
410405
There are two ways to execute hand-crafted SQL statements with peewee:

docs/peewee/quickstart.rst

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ Quickstart
44
==========
55

66
This guide walks through defining a schema, writing rows, and reading them
7-
back. It takes about ten minutes. Every concept introduced here is covered in
8-
depth in the following documents.
7+
back.
98

109
.. tip::
1110
Follow along in an interactive Python session.
@@ -40,8 +39,6 @@ classes map to tables.
4039
default=datetime.datetime.now,
4140
index=True)
4241
43-
Three things to notice:
44-
4542
* ``BaseModel`` exists only to carry the ``database`` setting. Every subclass
4643
inherits it automatically.
4744
* Peewee adds an auto-incrementing integer ``id`` primary key to any model
@@ -106,7 +103,7 @@ if no match is found:
106103
print(user.id, user.username)
107104
108105
Retrieve multiple rows with :meth:`~Model.select`. The result is a lazy
109-
query - rows are fetched only when you iterate:
106+
query. Rows are fetched only when you iterate:
110107

111108
.. code-block:: python
112109
@@ -134,9 +131,7 @@ Join to combine data from related tables in a single query:
134131

135132
.. code-block:: python
136133
137-
# Fetch each tweet alongside its author's username.
138-
# Without the join, accessing tweet.user.username would issue
139-
# an extra query per tweet - see the N+1 section in Relationships.
134+
# Select each tweet with its author in one query.
140135
query = (Tweet
141136
.select(Tweet, User)
142137
.join(User)
@@ -177,7 +172,7 @@ Working with Existing databases
177172
-------------------------------
178173

179174
If you have an existing database, peewee can generate models using :ref:`pwiz`.
180-
For example to generate models for a Postgres database named ``blog_db``:
175+
For example to generate models for a Postgres database named ``blog``:
181176

182177
.. code-block:: shell
183178

docs/peewee/relationships.rst

Lines changed: 6 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,6 @@ across tables. This document explains how Peewee models those links, what
88
happens under the hood when you traverse them, and how to write queries that
99
cross table boundaries efficiently.
1010

11-
By the end of this document you will understand:
12-
13-
* How :class:`ForeignKeyField` behaves at runtime, not just at schema
14-
definition time.
15-
* What a back-reference is and when to use one.
16-
* What the N+1 problem is and how to recognise it.
17-
* How to write joins, including multi-table and self-referential joins.
18-
* How many-to-many relationships are modelled.
19-
* When to use eager loading (:meth:`~ModelSelect.with_related`) instead of a
20-
join.
21-
2211

2312
Model Definitions
2413
-----------------
@@ -204,8 +193,7 @@ that user's tweets:
204193
alice-2
205194
alice-3
206195
207-
Taking a closer look at ``alice.tweets``, we can see that it is just a simple
208-
pre-filtered ``SELECT`` query:
196+
``alice.tweets`` is a pre-filtered ``SELECT`` query:
209197

210198
.. code-block:: pycon
211199
@@ -292,28 +280,7 @@ Joins
292280

293281
A SQL join combines columns from two or more tables into a single result set.
294282
Peewee's :meth:`~ModelSelect.join` method generates the appropriate ``JOIN``
295-
clause and reconstructs the model graph automatically:
296-
297-
.. code-block:: python
298-
299-
TweetUser = User.alias() # We are going to reference the User table twice,
300-
# so we need an alias.
301-
302-
query = (Favorite
303-
.select(Favorite, User, Tweet, TweetUser)
304-
.join_from(Favorite, User) # Get user who owns this Favorite.
305-
.join_from(Favorite, Tweet) # What tweet was favorite-d.
306-
.join_from(Tweet, TweetUser)) # What user created the tweet.
307-
308-
# Single query is issued.
309-
for fav in query:
310-
print(fav.user.username, 'likes', fav.tweet.content,
311-
'by', fav.tweet.user.username)
312-
313-
# alice likes bob-2 by bob
314-
# bob likes alice-3 by alice
315-
# carol likes alice-1 by alice
316-
# carol likes alice-3 by alice
283+
clause and reconstructs the model graph automatically.
317284

318285
Simple joins
319286
^^^^^^^^^^^^
@@ -452,8 +419,7 @@ corresponding attributes.
452419
# bob -> bob-1
453420
# bob -> bob-2
454421
455-
To make it a bit more obvious that it's doing the correct thing, we can ask
456-
Peewee to return the rows as dictionaries.
422+
Returning the rows as dictionaries makes this clearer:
457423

458424
.. code-block:: python
459425
@@ -611,8 +577,7 @@ Iterating over the query, we can see each user and their latest tweet.
611577
# alice -> alice-3
612578
# bob -> bob-2
613579
614-
There are a couple things you may not have seen before in the code we used to
615-
create the query in this section:
580+
Three things in this query:
616581

617582
* We used :meth:`~ModelSelect.join_from` to explicitly specify the join
618583
context. We wrote ``.join_from(Tweet, User)``, which is equivalent to
@@ -847,8 +812,8 @@ the corresponding instance in the reconstructed graph:
847812
.. code-block:: python
848813
849814
name = Case(User.username, [
850-
('u1', 'User One'),
851-
('u2', 'User Two')], 'Someone Else')
815+
('alice', 'Alice A.'),
816+
('bob', 'Bob B.')], 'Someone Else')
852817
853818
query = (Tweet
854819
.select(Tweet.content, name.alias('display').bind_to(User))

docs/peewee/schema.rst

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,8 @@ Indexes declared in ``Meta.indexes`` and via :meth:`Model.add_index` are
3636
created along with the table.
3737

3838
.. note::
39-
A common pattern in web applications is to call ``db.create_tables(MODELS, safe=True)``
40-
once at startup. This ensures all tables exist without failing on an already-
41-
initialized database. It does **not** apply schema changes - for that, see
42-
:ref:`migrations`.
39+
``create_tables`` creates missing tables but does **not** apply schema
40+
changes to existing ones. For that, see :ref:`migrations`.
4341

4442
Dropping Tables
4543
---------------
@@ -55,8 +53,8 @@ multiple times. To disable this, pass ``safe=False``.
5553
5654
db.drop_tables([User, Tweet, Favorite], safe=False)
5755
58-
Pass ``cascade=True`` (Postgresql and MySQL) to let the database handle
59-
dependency ordering:
56+
Pass ``cascade=True`` on Postgresql to drop dependent objects and let the
57+
database handle ordering (MySQL parses but ignores CASCADE):
6058

6159
.. code-block:: python
6260
@@ -113,8 +111,8 @@ Schema Migrations
113111
-----------------
114112

115113
Peewee does not include a built-in migration system. For schema changes in an
116-
existing deployment - adding columns, dropping columns, renaming tables,
117-
modifying indexes - use one of the following approaches.
114+
existing deployment (adding columns, dropping columns, renaming tables,
115+
modifying indexes), use one of the following approaches.
118116

119117
Playhouse migrate module
120118
^^^^^^^^^^^^^^^^^^^^^^^^^

0 commit comments

Comments
 (0)