Skip to content

Commit ca43d72

Browse files
authored
Merge pull request #43 from Zerohertz/issue#21/feat/alembic
[Feat] DB 고도화 및 Alembic을 통한 migration
2 parents d675e51 + d69bf24 commit ca43d72

File tree

11 files changed

+483
-5
lines changed

11 files changed

+483
-5
lines changed

Makefile

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,21 @@ lint:
1212
uv run isort app --check-only
1313
uv run black app --check
1414

15+
.PHONY: alembic
16+
alembic:
17+
@uv sync
18+
@export DESCRIPTION=$$(cat README.md) && \
19+
set -o allexport && \
20+
source envs/$${ENV,,}.env && \
21+
set +o allexport && \
22+
if [ "$(revision)" = "downgrade" ]; then \
23+
uv run alembic downgrade base; \
24+
elif [ -z "$(revision)" ]; then \
25+
uv run alembic upgrade head; \
26+
else \
27+
uv run alembic revision --autogenerate -m "$(revision)"; \
28+
fi
29+
1530
.PHONY: test
1631
test:
1732
uv sync --group test
@@ -59,6 +74,9 @@ swagger:
5974

6075
.PHONY: deploy
6176
deploy:
77+
ifndef tag
78+
$(error tag is not set.)
79+
endif
6280
echo $(tag)
6381
sed -i 's|zerohertzkr/fastapi-cookbook:[^ ]*|zerohertzkr/fastapi-cookbook:$(tag)|' k8s/postgresql/fastapi.yaml
6482
git add k8s/postgresql/fastapi.yaml

alembic.ini

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
# Use forward slashes (/) also on windows to provide an os agnostic path
6+
script_location = alembic
7+
8+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
9+
# Uncomment the line below if you want the files to be prepended with date and time
10+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
11+
# for all available tokens
12+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
13+
14+
# sys.path path, will be prepended to sys.path if present.
15+
# defaults to the current working directory.
16+
prepend_sys_path = .
17+
18+
# timezone to use when rendering the date within the migration file
19+
# as well as the filename.
20+
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
21+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
22+
# string value is passed to ZoneInfo()
23+
# leave blank for localtime
24+
# timezone =
25+
26+
# max length of characters to apply to the "slug" field
27+
# truncate_slug_length = 40
28+
29+
# set to 'true' to run the environment during
30+
# the 'revision' command, regardless of autogenerate
31+
# revision_environment = false
32+
33+
# set to 'true' to allow .pyc and .pyo files without
34+
# a source .py file to be detected as revisions in the
35+
# versions/ directory
36+
# sourceless = false
37+
38+
# version location specification; This defaults
39+
# to alembic/versions. When using multiple version
40+
# directories, initial revisions must be specified with --version-path.
41+
# The path separator used here should be the separator specified by "version_path_separator" below.
42+
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
43+
44+
# version path separator; As mentioned above, this is the character used to split
45+
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
46+
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
47+
# Valid values for version_path_separator are:
48+
#
49+
# version_path_separator = :
50+
# version_path_separator = ;
51+
# version_path_separator = space
52+
# version_path_separator = newline
53+
#
54+
# Use os.pathsep. Default configuration used for new projects.
55+
version_path_separator = os
56+
57+
# set to 'true' to search source files recursively
58+
# in each "version_locations" directory
59+
# new in Alembic version 1.10
60+
# recursive_version_locations = false
61+
62+
# the output encoding used when revision files
63+
# are written from script.py.mako
64+
# output_encoding = utf-8
65+
66+
sqlalchemy.url = driver://user:pass@localhost/dbname
67+
68+
69+
[post_write_hooks]
70+
# post_write_hooks defines scripts or Python functions that are run
71+
# on newly generated revision scripts. See the documentation for further
72+
# detail and examples
73+
74+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
75+
# hooks = black
76+
# black.type = console_scripts
77+
# black.entrypoint = black
78+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
79+
80+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
81+
# hooks = ruff
82+
# ruff.type = exec
83+
# ruff.executable = %(here)s/.venv/bin/ruff
84+
# ruff.options = --fix REVISION_SCRIPT_FILENAME
85+
86+
# Logging configuration
87+
[loggers]
88+
keys = root,sqlalchemy,alembic
89+
90+
[handlers]
91+
keys = console
92+
93+
[formatters]
94+
keys = generic
95+
96+
[logger_root]
97+
level = WARNING
98+
handlers = console
99+
qualname =
100+
101+
[logger_sqlalchemy]
102+
level = WARNING
103+
handlers =
104+
qualname = sqlalchemy.engine
105+
106+
[logger_alembic]
107+
level = INFO
108+
handlers =
109+
qualname = alembic
110+
111+
[handler_console]
112+
class = StreamHandler
113+
args = (sys.stderr,)
114+
level = NOTSET
115+
formatter = generic
116+
117+
[formatter_generic]
118+
format = %(levelname)-5.5s [%(name)s] %(message)s
119+
datefmt = %H:%M:%S

alembic/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

alembic/env.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import asyncio
2+
from logging.config import fileConfig
3+
4+
from sqlalchemy import engine_from_config, pool
5+
6+
from alembic import context
7+
from app.core.configs import configs
8+
from app.core.database import database
9+
from app.models.base import BaseModel
10+
11+
# this is the Alembic Config object, which provides
12+
# access to the values within the .ini file in use.
13+
config = context.config
14+
15+
# Interpret the config file for Python logging.
16+
# This line sets up loggers basically.
17+
if config.config_file_name is not None:
18+
fileConfig(config.config_file_name)
19+
config.set_main_option("sqlalchemy.url", configs.DATABASE_URI)
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 = BaseModel.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() -> None:
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 run_migrations_online_sync() -> None:
58+
"""Run migrations in 'online' mode.
59+
60+
In this scenario we need to create an Engine
61+
and associate a connection with the context.
62+
63+
"""
64+
connectable = engine_from_config(
65+
config.get_section(config.config_ini_section, {}),
66+
prefix="sqlalchemy.",
67+
poolclass=pool.NullPool,
68+
)
69+
70+
with connectable.connect() as connection:
71+
context.configure(connection=connection, target_metadata=target_metadata)
72+
73+
with context.begin_transaction():
74+
context.run_migrations()
75+
76+
77+
async def run_migrations_online_async() -> None:
78+
connectable = database.engine
79+
80+
def run_migrations(connection):
81+
context.configure(connection=connection, target_metadata=target_metadata)
82+
with context.begin_transaction():
83+
context.run_migrations()
84+
85+
async with connectable.connect() as connection:
86+
await connection.run_sync(run_migrations)
87+
await connectable.dispose()
88+
89+
90+
if context.is_offline_mode():
91+
run_migrations_offline()
92+
else:
93+
asyncio.run(run_migrations_online_async())

alembic/script.py.mako

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
${imports if imports else ""}
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = ${repr(up_revision)}
16+
down_revision: Union[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)}
19+
20+
21+
def upgrade() -> None:
22+
${upgrades if upgrades else "pass"}
23+
24+
25+
def downgrade() -> None:
26+
${downgrades if downgrades else "pass"}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""init: alembic
2+
3+
Revision ID: 0bdf3abd5213
4+
Revises:
5+
Create Date: 2025-02-14 01:13:13.993395
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = '0bdf3abd5213'
16+
down_revision: Union[str, None] = None
17+
branch_labels: Union[str, Sequence[str], None] = None
18+
depends_on: Union[str, Sequence[str], None] = None
19+
20+
21+
def upgrade() -> None:
22+
# ### commands auto generated by Alembic - please adjust! ###
23+
op.create_table('user',
24+
sa.Column('name', sa.String(length=255), nullable=False),
25+
sa.Column('email', sa.String(length=255), nullable=False),
26+
sa.Column('role', sa.Enum('ADMIN', 'USER', name='role'), nullable=False),
27+
sa.Column('refresh_token', sa.String(length=255), nullable=True),
28+
sa.Column('id', sa.Integer(), nullable=False),
29+
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
30+
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
31+
sa.PrimaryKeyConstraint('id'),
32+
sa.UniqueConstraint('email'),
33+
sa.UniqueConstraint('name')
34+
)
35+
op.create_table('oauth',
36+
sa.Column('user_id', sa.Integer(), nullable=False),
37+
sa.Column('provider', sa.Enum('PASSWORD', 'GITHUB', 'GOOGLE', name='oauthprovider'), nullable=False),
38+
sa.Column('password', sa.String(length=255), nullable=True),
39+
sa.Column('oauth_id', sa.String(length=255), nullable=True),
40+
sa.Column('oauth_token', sa.String(length=255), nullable=True),
41+
sa.Column('id', sa.Integer(), nullable=False),
42+
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
43+
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
44+
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
45+
sa.PrimaryKeyConstraint('id'),
46+
sa.UniqueConstraint('user_id', 'provider', name='uq_oauth_user_provider')
47+
)
48+
# ### end Alembic commands ###
49+
50+
51+
def downgrade() -> None:
52+
# ### commands auto generated by Alembic - please adjust! ###
53+
op.drop_table('oauth')
54+
op.drop_table('user')
55+
# ### end Alembic commands ###

app/core/configs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class ENVIRONMENT(Enum):
1212

1313

1414
class Configs(BaseSettings):
15-
ENV: ENVIRONMENT
15+
ENV: ENVIRONMENT = ENVIRONMENT.TEST
1616

1717
# --------- APP SETTINGS --------- #
1818
PROJECT_NAME: str

0 commit comments

Comments
 (0)