Skip to content

Commit 448d472

Browse files
committed
add sqlmodel and alembic
1 parent 21e4a80 commit 448d472

File tree

11 files changed

+352
-2
lines changed

11 files changed

+352
-2
lines changed

docker-compose.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ services:
1010
ports:
1111
- 8004:8000
1212
environment:
13-
- DATABASE_URL=postgresql://postgres:postgres@db:5432/foo
13+
- DATABASE_URL=postgresql+asyncpg://postgres:postgres@db:5432/foo
1414
depends_on:
1515
- db
1616

project/alembic.ini

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
script_location = migrations
6+
7+
# template used to generate migration files
8+
# file_template = %%(rev)s_%%(slug)s
9+
10+
# sys.path path, will be prepended to sys.path if present.
11+
# defaults to the current working directory.
12+
prepend_sys_path = .
13+
14+
# timezone to use when rendering the date within the migration file
15+
# as well as the filename.
16+
# If specified, requires the python-dateutil library that can be
17+
# installed by adding `alembic[tz]` to the pip requirements
18+
# string value is passed to dateutil.tz.gettz()
19+
# leave blank for localtime
20+
# timezone =
21+
22+
# max length of characters to apply to the
23+
# "slug" field
24+
# truncate_slug_length = 40
25+
26+
# set to 'true' to run the environment during
27+
# the 'revision' command, regardless of autogenerate
28+
# revision_environment = false
29+
30+
# set to 'true' to allow .pyc and .pyo files without
31+
# a source .py file to be detected as revisions in the
32+
# versions/ directory
33+
# sourceless = false
34+
35+
# version location specification; This defaults
36+
# to migrations/versions. When using multiple version
37+
# directories, initial revisions must be specified with --version-path.
38+
# The path separator used here should be the separator specified by "version_path_separator"
39+
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
40+
41+
# version path separator; As mentioned above, this is the character used to split
42+
# version_locations. Valid values are:
43+
#
44+
# version_path_separator = :
45+
# version_path_separator = ;
46+
# version_path_separator = space
47+
version_path_separator = os # default: use os.pathsep
48+
49+
# the output encoding used when revision files
50+
# are written from script.py.mako
51+
# output_encoding = utf-8
52+
53+
sqlalchemy.url = postgresql+asyncpg://postgres:postgres@db:5432/foo
54+
55+
56+
[post_write_hooks]
57+
# post_write_hooks defines scripts or Python functions that are run
58+
# on newly generated revision scripts. See the documentation for further
59+
# detail and examples
60+
61+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
62+
# hooks = black
63+
# black.type = console_scripts
64+
# black.entrypoint = black
65+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
66+
67+
# Logging configuration
68+
[loggers]
69+
keys = root,sqlalchemy,alembic
70+
71+
[handlers]
72+
keys = console
73+
74+
[formatters]
75+
keys = generic
76+
77+
[logger_root]
78+
level = WARN
79+
handlers = console
80+
qualname =
81+
82+
[logger_sqlalchemy]
83+
level = WARN
84+
handlers =
85+
qualname = sqlalchemy.engine
86+
87+
[logger_alembic]
88+
level = INFO
89+
handlers =
90+
qualname = alembic
91+
92+
[handler_console]
93+
class = StreamHandler
94+
args = (sys.stderr,)
95+
level = NOTSET
96+
formatter = generic
97+
98+
[formatter_generic]
99+
format = %(levelname)-5.5s [%(name)s] %(message)s
100+
datefmt = %H:%M:%S

project/app/db.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import os
2+
3+
from sqlmodel import SQLModel
4+
5+
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
6+
from sqlalchemy.orm import sessionmaker
7+
8+
9+
DATABASE_URL = os.environ.get("DATABASE_URL")
10+
11+
engine = create_async_engine(DATABASE_URL, echo=True, future=True)
12+
13+
14+
async def init_db():
15+
async with engine.begin() as conn:
16+
# await conn.run_sync(SQLModel.metadata.drop_all)
17+
await conn.run_sync(SQLModel.metadata.create_all)
18+
19+
20+
async def get_session() -> AsyncSession:
21+
async_session = sessionmaker(
22+
engine, class_=AsyncSession, expire_on_commit=False
23+
)
24+
async with async_session() as session:
25+
yield session

project/app/main.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,29 @@
1-
from fastapi import FastAPI
1+
from fastapi import Depends, FastAPI
2+
from sqlalchemy.future import select
3+
from sqlalchemy.ext.asyncio import AsyncSession
4+
5+
from app.db import get_session, init_db
6+
from app.models import Song, SongCreate
27

38
app = FastAPI()
49

510

611
@app.get("/ping")
712
async def pong():
813
return {"ping": "pong!"}
14+
15+
16+
@app.get("/songs", response_model=list[Song])
17+
async def get_songs(session: AsyncSession = Depends(get_session)):
18+
result = await session.execute(select(Song))
19+
songs = result.scalars().all()
20+
return [Song(name=song.name, artist=song.artist, year=song.year, id=song.id) for song in songs]
21+
22+
23+
@app.post("/songs")
24+
async def add_song(song: SongCreate, session: AsyncSession = Depends(get_session)):
25+
song = Song(name=song.name, artist=song.artist, year=song.year)
26+
session.add(song)
27+
await session.commit()
28+
await session.refresh(song)
29+
return song

project/app/models.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import Optional
2+
3+
from sqlmodel import SQLModel, Field
4+
5+
6+
class SongBase(SQLModel):
7+
name: str
8+
artist: str
9+
year: Optional[int] = None
10+
11+
12+
class Song(SongBase, table=True):
13+
id: int = Field(default=None, primary_key=True)
14+
15+
16+
class SongCreate(SongBase):
17+
pass

project/migrations/README

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.

project/migrations/env.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import asyncio
2+
from logging.config import fileConfig
3+
4+
from sqlalchemy import engine_from_config
5+
from sqlalchemy import pool
6+
from sqlalchemy.ext.asyncio import AsyncEngine
7+
from sqlmodel import SQLModel
8+
9+
from alembic import context
10+
11+
from app.models import Song
12+
13+
# this is the Alembic Config object, which provides
14+
# access to the values within the .ini file in use.
15+
config = context.config
16+
17+
# Interpret the config file for Python logging.
18+
# This line sets up loggers basically.
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
25+
target_metadata = SQLModel.metadata
26+
27+
# other values from the config, defined by the needs of env.py,
28+
# can be acquired:
29+
# my_important_option = config.get_main_option("my_important_option")
30+
# ... etc.
31+
32+
33+
def run_migrations_offline():
34+
"""Run migrations in 'offline' mode.
35+
36+
This configures the context with just a URL
37+
and not an Engine, though an Engine is acceptable
38+
here as well. By skipping the Engine creation
39+
we don't even need a DBAPI to be available.
40+
41+
Calls to context.execute() here emit the given string to the
42+
script output.
43+
44+
"""
45+
url = config.get_main_option("sqlalchemy.url")
46+
context.configure(
47+
url=url,
48+
target_metadata=target_metadata,
49+
literal_binds=True,
50+
dialect_opts={"paramstyle": "named"},
51+
)
52+
53+
with context.begin_transaction():
54+
context.run_migrations()
55+
56+
57+
def do_run_migrations(connection):
58+
context.configure(connection=connection, target_metadata=target_metadata)
59+
60+
with context.begin_transaction():
61+
context.run_migrations()
62+
63+
64+
async def run_migrations_online():
65+
"""Run migrations in 'online' mode.
66+
67+
In this scenario we need to create an Engine
68+
and associate a connection with the context.
69+
70+
"""
71+
connectable = AsyncEngine(
72+
engine_from_config(
73+
config.get_section(config.config_ini_section),
74+
prefix="sqlalchemy.",
75+
poolclass=pool.NullPool,
76+
future=True,
77+
)
78+
)
79+
80+
async with connectable.connect() as connection:
81+
await connection.run_sync(do_run_migrations)
82+
83+
84+
if context.is_offline_mode():
85+
run_migrations_offline()
86+
else:
87+
asyncio.run(run_migrations_online())

project/migrations/script.py.mako

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
import sqlmodel
11+
${imports if imports else ""}
12+
13+
# revision identifiers, used by Alembic.
14+
revision = ${repr(up_revision)}
15+
down_revision = ${repr(down_revision)}
16+
branch_labels = ${repr(branch_labels)}
17+
depends_on = ${repr(depends_on)}
18+
19+
20+
def upgrade():
21+
${upgrades if upgrades else "pass"}
22+
23+
24+
def downgrade():
25+
${downgrades if downgrades else "pass"}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""add year
2+
3+
Revision ID: 53754b2c08a4
4+
Revises: f9c634db477d
5+
Create Date: 2021-09-10 00:52:38.668620
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
import sqlmodel
11+
12+
13+
# revision identifiers, used by Alembic.
14+
revision = '53754b2c08a4'
15+
down_revision = 'f9c634db477d'
16+
branch_labels = None
17+
depends_on = None
18+
19+
20+
def upgrade():
21+
# ### commands auto generated by Alembic - please adjust! ###
22+
op.add_column('song', sa.Column('year', sa.Integer(), nullable=True))
23+
op.create_index(op.f('ix_song_year'), 'song', ['year'], unique=False)
24+
# ### end Alembic commands ###
25+
26+
27+
def downgrade():
28+
# ### commands auto generated by Alembic - please adjust! ###
29+
op.drop_index(op.f('ix_song_year'), table_name='song')
30+
op.drop_column('song', 'year')
31+
# ### end Alembic commands ###
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""init
2+
3+
Revision ID: f9c634db477d
4+
Revises:
5+
Create Date: 2021-09-10 00:24:32.718895
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
import sqlmodel
11+
12+
13+
# revision identifiers, used by Alembic.
14+
revision = 'f9c634db477d'
15+
down_revision = None
16+
branch_labels = None
17+
depends_on = None
18+
19+
20+
def upgrade():
21+
# ### commands auto generated by Alembic - please adjust! ###
22+
op.create_table('song',
23+
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
24+
sa.Column('artist', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
25+
sa.Column('id', sa.Integer(), nullable=True),
26+
sa.PrimaryKeyConstraint('id')
27+
)
28+
op.create_index(op.f('ix_song_artist'), 'song', ['artist'], unique=False)
29+
op.create_index(op.f('ix_song_id'), 'song', ['id'], unique=False)
30+
op.create_index(op.f('ix_song_name'), 'song', ['name'], unique=False)
31+
# ### end Alembic commands ###
32+
33+
34+
def downgrade():
35+
# ### commands auto generated by Alembic - please adjust! ###
36+
op.drop_index(op.f('ix_song_name'), table_name='song')
37+
op.drop_index(op.f('ix_song_id'), table_name='song')
38+
op.drop_index(op.f('ix_song_artist'), table_name='song')
39+
op.drop_table('song')
40+
# ### end Alembic commands ###

0 commit comments

Comments
 (0)