Skip to content

Commit b1ce612

Browse files
make chapter 6 code match the walkthrough
Remove unrequested exercise solutions and additional behavior. Assemble the chapter snippets and retain only the standard Alembic scaffold and two walkthrough migrations. Generated with [Snowflake CoCo](https://docs.snowflake.com/en/user-guide/cortex-code/cortex-code) Co-authored-by: Snowflake CoCo <noreply@snowflake.com>
1 parent c7dbc03 commit b1ce612

22 files changed

Lines changed: 550 additions & 785 deletions
Lines changed: 4 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,9 @@
11
# Chapter 6: Registration Service
22

3-
This is the final version of the chapter's SQLAlchemy service, including the three exercises. It uses Python 3.13 and uv. Run these commands from this directory:
3+
This directory contains the final code from the chapter walkthrough, without exercise solutions or additional features.
44

5-
```bash
6-
uv sync
7-
uv run alembic upgrade head
8-
uv run fastapi dev main.py
9-
```
5+
From this directory, install the dependencies with `uv sync`. The final `database.py` uses the local PostgreSQL connection shown in the chapter. Start that database, run `uv run python check_db.py`, then `uv run alembic upgrade head` and `uv run fastapi dev main.py`.
106

11-
Open http://127.0.0.1:8000/docs to register, list, read, update, and delete users. This is a teaching example with no authentication or authorization; do not expose it publicly. Access controls are covered later in the book.
7+
Run the chapter's eight tests with `uv run pytest -v`. They use SQLite and do not require PostgreSQL.
128

13-
## Database setup
14-
15-
SQLite is the default and needs no server. The final application does not create tables at startup: run the committed migrations before starting it against an empty database. Do not generate a second initial migration. If following the earlier `create_all` example, use a fresh database for the migration walkthrough rather than applying the initial migration to an existing `users` table.
16-
17-
For PostgreSQL, provision a database and supply a `postgresql+asyncpg` connection URL through `DATABASE_URL` using your deployment's secret management. Never commit real credentials. Run the same migrations and `uv run python check_db.py` before starting the service. The check script also supports SQLite.
18-
19-
The migrations create the seven-column users table, add the optional phone number, and add JSON preferences. Preferences use JSONB on PostgreSQL and JSON on SQLite. Python-side defaults are applied by SQLAlchemy, not by direct database inserts.
20-
21-
## Tests
22-
23-
```bash
24-
uv run pytest -v
25-
uv run ruff check .
26-
```
27-
28-
Tests use temporary SQLite databases and do not connect to the configured application database. They cover the chapter's eight API cases, stored password hashing, validation, pagination, concurrent-duplicate handling, and migration upgrades/downgrades that preserve existing users. PostgreSQL integration must be checked separately against a running server.
29-
30-
Compared with the printed snippets, the runnable service also returns 409 if a duplicate insert wins a race and rejects explicit null updates to non-nullable columns. Omitted update fields remain unchanged.
31-
32-
## Exercises
33-
34-
- **6.1:** `crud.get_users` and `GET /users` provide pagination ordered by user ID, with validated bounds.
35-
- **6.2:** `User.phone_number`, `UserBase.phone_number`, and migration `0002` add an optional phone number without deleting users.
36-
- **6.3:** `exercises/slot_repository.py` implements Chapter 3's `AvailabilitySlotRepository`. It imports the existing domain rather than duplicating it; pytest adds the Chapter 3 service to its Python path. The tests also run the unchanged Chapter 3 use cases against this adapter.
37-
38-
The slot repository is synchronous because Chapter 3's repository interface is synchronous. Its separate metadata is not part of the registration database migrations. Construct it with a SQLAlchemy `sessionmaker` and inject it in place of the in-memory repository. The example does not implement concurrent reservation conflict detection.
9+
The Alembic scaffold comes from `alembic init -t async alembic`. Its two generated revisions create the users table and add preferences. `script.py.mako` is Alembic's standard template for generating revisions.
Lines changed: 146 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,149 @@
1+
# A generic, single database configuration.
2+
13
[alembic]
4+
# path to migration scripts.
5+
# this is typically a path given in POSIX (e.g. forward slashes)
6+
# format, relative to the token %(here)s which refers to the location of this
7+
# ini file
28
script_location = %(here)s/alembic
3-
prepend_sys_path = %(here)s
9+
10+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
11+
# Uncomment the line below if you want the files to be prepended with date and time
12+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
13+
# for all available tokens
14+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
15+
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
16+
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
17+
18+
# sys.path path, will be prepended to sys.path if present.
19+
# defaults to the current working directory. for multiple paths, the path separator
20+
# is defined by "path_separator" below.
21+
prepend_sys_path = .
22+
23+
# timezone to use when rendering the date within the migration file
24+
# as well as the filename.
25+
# If specified, requires the tzdata library which can be installed by adding
26+
# `alembic[tz]` to the pip requirements.
27+
# string value is passed to ZoneInfo()
28+
# leave blank for localtime
29+
# timezone =
30+
31+
# max length of characters to apply to the "slug" field
32+
# truncate_slug_length = 40
33+
34+
# set to 'true' to run the environment during
35+
# the 'revision' command, regardless of autogenerate
36+
# revision_environment = false
37+
38+
# set to 'true' to allow .pyc and .pyo files without
39+
# a source .py file to be detected as revisions in the
40+
# versions/ directory
41+
# sourceless = false
42+
43+
# version location specification; This defaults
44+
# to <script_location>/versions. When using multiple version
45+
# directories, initial revisions must be specified with --version-path.
46+
# The path separator used here should be the separator specified by "path_separator"
47+
# below.
48+
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
49+
50+
# path_separator; This indicates what character is used to split lists of file
51+
# paths, including version_locations and prepend_sys_path within configparser
52+
# files such as alembic.ini.
53+
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
54+
# to provide os-dependent path splitting.
55+
#
56+
# Note that in order to support legacy alembic.ini files, this default does NOT
57+
# take place if path_separator is not present in alembic.ini. If this
58+
# option is omitted entirely, fallback logic is as follows:
59+
#
60+
# 1. Parsing of the version_locations option falls back to using the legacy
61+
# "version_path_separator" key, which if absent then falls back to the legacy
62+
# behavior of splitting on spaces and/or commas.
63+
# 2. Parsing of the prepend_sys_path option falls back to the legacy
64+
# behavior of splitting on spaces, commas, or colons.
65+
#
66+
# Valid values for path_separator are:
67+
#
68+
# path_separator = :
69+
# path_separator = ;
70+
# path_separator = space
71+
# path_separator = newline
72+
#
73+
# Use os.pathsep. Default configuration used for new projects.
474
path_separator = os
75+
76+
77+
# set to 'true' to search source files recursively
78+
# in each "version_locations" directory
79+
# new in Alembic version 1.10
80+
# recursive_version_locations = false
81+
82+
# the output encoding used when revision files
83+
# are written from script.py.mako
84+
# output_encoding = utf-8
85+
86+
# database URL. This is consumed by the user-maintained env.py script only.
87+
# other means of configuring database URLs may be customized within the env.py
88+
# file.
89+
sqlalchemy.url = driver://user:pass@localhost/dbname
90+
91+
92+
[post_write_hooks]
93+
# post_write_hooks defines scripts or Python functions that are run
94+
# on newly generated revision scripts. See the documentation for further
95+
# detail and examples
96+
97+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
98+
# hooks = black
99+
# black.type = console_scripts
100+
# black.entrypoint = black
101+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
102+
103+
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
104+
# hooks = ruff
105+
# ruff.type = module
106+
# ruff.module = ruff
107+
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
108+
109+
# Alternatively, use the exec runner to execute a binary found on your PATH
110+
# hooks = ruff
111+
# ruff.type = exec
112+
# ruff.executable = ruff
113+
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
114+
115+
# Logging configuration. This is also consumed by the user-maintained
116+
# env.py script only.
117+
[loggers]
118+
keys = root,sqlalchemy,alembic
119+
120+
[handlers]
121+
keys = console
122+
123+
[formatters]
124+
keys = generic
125+
126+
[logger_root]
127+
level = WARNING
128+
handlers = console
129+
qualname =
130+
131+
[logger_sqlalchemy]
132+
level = WARNING
133+
handlers =
134+
qualname = sqlalchemy.engine
135+
136+
[logger_alembic]
137+
level = INFO
138+
handlers =
139+
qualname = alembic
140+
141+
[handler_console]
142+
class = StreamHandler
143+
args = (sys.stderr,)
144+
level = NOTSET
145+
formatter = generic
146+
147+
[formatter_generic]
148+
format = %(levelname)-5.5s [%(name)s] %(message)s
149+
datefmt = %H:%M:%S
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration with an async dbapi.
Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,94 @@
11
import asyncio
2+
from logging.config import fileConfig
23

34
from sqlalchemy import pool
5+
from sqlalchemy.engine import Connection
46
from sqlalchemy.ext.asyncio import async_engine_from_config
57

68
from alembic import context
79
from database import DATABASE_URL
810
from models import Base
911

12+
# this is the Alembic Config object, which provides
13+
# access to the values within the .ini file in use.
1014
config = context.config
11-
config.set_main_option(
12-
"sqlalchemy.url", DATABASE_URL.replace("%", "%%")
13-
)
15+
16+
# Interpret the config file for Python logging.
17+
# This line sets up loggers basically.
18+
if config.config_file_name is not None:
19+
fileConfig(config.config_file_name)
20+
21+
# add your model's MetaData object here
22+
# for 'autogenerate' support
23+
# from myapp import mymodel
24+
# target_metadata = mymodel.Base.metadata
1425
target_metadata = Base.metadata
26+
config.set_main_option("sqlalchemy.url", DATABASE_URL)
27+
28+
# other values from the config, defined by the needs of env.py,
29+
# can be acquired:
30+
# my_important_option = config.get_main_option("my_important_option")
31+
# ... etc.
1532

1633

1734
def run_migrations_offline() -> None:
35+
"""Run migrations in 'offline' mode.
36+
37+
This configures the context with just a URL
38+
and not an Engine, though an Engine is acceptable
39+
here as well. By skipping the Engine creation
40+
we don't even need a DBAPI to be available.
41+
42+
Calls to context.execute() here emit the given string to the
43+
script output.
44+
45+
"""
46+
url = config.get_main_option("sqlalchemy.url")
1847
context.configure(
19-
url=DATABASE_URL,
48+
url=url,
2049
target_metadata=target_metadata,
2150
literal_binds=True,
2251
dialect_opts={"paramstyle": "named"},
2352
)
53+
2454
with context.begin_transaction():
2555
context.run_migrations()
2656

2757

28-
def do_run_migrations(connection) -> None:
58+
def do_run_migrations(connection: Connection) -> None:
2959
context.configure(
3060
connection=connection, target_metadata=target_metadata
3161
)
62+
3263
with context.begin_transaction():
3364
context.run_migrations()
3465

3566

3667
async def run_async_migrations() -> None:
68+
"""In this scenario we need to create an Engine
69+
and associate a connection with the context.
70+
71+
"""
72+
3773
connectable = async_engine_from_config(
3874
config.get_section(config.config_ini_section, {}),
3975
prefix="sqlalchemy.",
4076
poolclass=pool.NullPool,
4177
)
42-
try:
43-
async with connectable.connect() as connection:
44-
await connection.run_sync(do_run_migrations)
45-
finally:
46-
await connectable.dispose()
78+
79+
async with connectable.connect() as connection:
80+
await connection.run_sync(do_run_migrations)
81+
82+
await connectable.dispose()
83+
84+
85+
def run_migrations_online() -> None:
86+
"""Run migrations in 'online' mode."""
87+
88+
asyncio.run(run_async_migrations())
4789

4890

4991
if context.is_offline_mode():
5092
run_migrations_offline()
5193
else:
52-
asyncio.run(run_async_migrations())
94+
run_migrations_online()

‎Chapter06/registration-service/alembic/script.py.mako‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,27 @@
22

33
Revision ID: ${up_revision}
44
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
57
"""
8+
from typing import Sequence, Union
9+
610
from alembic import op
711
import sqlalchemy as sa
812
${imports if imports else ""}
913

10-
revision = ${repr(up_revision)}
11-
down_revision = ${repr(down_revision)}
12-
branch_labels = ${repr(branch_labels)}
13-
depends_on = ${repr(depends_on)}
14+
# revision identifiers, used by Alembic.
15+
revision: str = ${repr(up_revision)}
16+
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
17+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
1419

1520

1621
def upgrade() -> None:
22+
"""Upgrade schema."""
1723
${upgrades if upgrades else "pass"}
1824

1925

2026
def downgrade() -> None:
27+
"""Downgrade schema."""
2128
${downgrades if downgrades else "pass"}

‎Chapter06/registration-service/alembic/versions/0001_create_users.py‎

Lines changed: 0 additions & 37 deletions
This file was deleted.

‎Chapter06/registration-service/alembic/versions/0002_add_phone_number.py‎

Lines changed: 0 additions & 22 deletions
This file was deleted.

0 commit comments

Comments
 (0)