Skip to content

Commit 08a65a3

Browse files
committed
replaced sqlite with PostgreSQL and Alembic
1 parent 98c5418 commit 08a65a3

18 files changed

Lines changed: 477 additions & 10 deletions

.env.example

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
POSTGRES_USER=your_user
2+
POSTGRES_PASSWORD=your_password
3+
POSTGRES_DB=your_db
4+
POSTGRES_PORT=5432

alembic.ini

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# A generic, single database configuration.
2+
3+
[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
8+
script_location = %(here)s/alembic
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.
74+
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 =
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

alembic/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.

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 pool
5+
from sqlalchemy.engine import Connection
6+
from sqlalchemy.ext.asyncio import async_engine_from_config
7+
8+
from alembic import context
9+
import models
10+
from config import settings
11+
from database import Base
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+
config.set_main_option("sqlalchemy.url", settings.database_url)
17+
18+
# Interpret the config file for Python logging.
19+
# This line sets up loggers basically.
20+
if config.config_file_name is not None:
21+
fileConfig(config.config_file_name)
22+
23+
# add your model's MetaData object here
24+
# for 'autogenerate' support
25+
# from myapp import mymodel
26+
# target_metadata = mymodel.Base.metadata
27+
target_metadata = Base.metadata
28+
29+
# other values from the config, defined by the needs of env.py,
30+
# can be acquired:
31+
# my_important_option = config.get_main_option("my_important_option")
32+
# ... etc.
33+
34+
35+
def run_migrations_offline() -> None:
36+
"""Run migrations in 'offline' mode.
37+
38+
This configures the context with just a URL
39+
and not an Engine, though an Engine is acceptable
40+
here as well. By skipping the Engine creation
41+
we don't even need a DBAPI to be available.
42+
43+
Calls to context.execute() here emit the given string to the
44+
script output.
45+
46+
"""
47+
url = config.get_main_option("sqlalchemy.url")
48+
context.configure(
49+
url=url,
50+
target_metadata=target_metadata,
51+
literal_binds=True,
52+
dialect_opts={"paramstyle": "named"},
53+
)
54+
55+
with context.begin_transaction():
56+
context.run_migrations()
57+
58+
59+
def do_run_migrations(connection: Connection) -> None:
60+
context.configure(connection=connection, target_metadata=target_metadata)
61+
62+
with context.begin_transaction():
63+
context.run_migrations()
64+
65+
66+
async def run_async_migrations() -> None:
67+
"""In this scenario we need to create an Engine
68+
and associate a connection with the context.
69+
70+
"""
71+
72+
connectable = async_engine_from_config(
73+
config.get_section(config.config_ini_section, {}),
74+
prefix="sqlalchemy.",
75+
poolclass=pool.NullPool,
76+
)
77+
78+
async with connectable.connect() as connection:
79+
await connection.run_sync(do_run_migrations)
80+
81+
await connectable.dispose()
82+
83+
84+
def run_migrations_online() -> None:
85+
"""Run migrations in 'online' mode."""
86+
87+
asyncio.run(run_async_migrations())
88+
89+
90+
if context.is_offline_mode():
91+
run_migrations_offline()
92+
else:
93+
run_migrations_online()

alembic/script.py.mako

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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, 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)}
19+
20+
21+
def upgrade() -> None:
22+
"""Upgrade schema."""
23+
${upgrades if upgrades else "pass"}
24+
25+
26+
def downgrade() -> None:
27+
"""Downgrade schema."""
28+
${downgrades if downgrades else "pass"}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""initial schema
2+
3+
Revision ID: 5d49d2f24111
4+
Revises:
5+
Create Date: 2026-04-14 22:18:15.636554
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 = '5d49d2f24111'
16+
down_revision: Union[str, Sequence[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+
"""Upgrade schema."""
23+
# ### commands auto generated by Alembic - please adjust! ###
24+
op.create_table('users',
25+
sa.Column('id', sa.Integer(), nullable=False),
26+
sa.Column('username', sa.String(length=50), nullable=False),
27+
sa.Column('email', sa.String(length=120), nullable=False),
28+
sa.Column('password_hash', sa.String(length=200), nullable=False),
29+
sa.Column('image_file', sa.String(length=200), nullable=True),
30+
sa.PrimaryKeyConstraint('id'),
31+
sa.UniqueConstraint('email'),
32+
sa.UniqueConstraint('username')
33+
)
34+
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
35+
op.create_table('password_reset_tokens',
36+
sa.Column('id', sa.Integer(), nullable=False),
37+
sa.Column('user_id', sa.Integer(), nullable=False),
38+
sa.Column('token_hash', sa.String(length=64), nullable=False),
39+
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
40+
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
41+
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
42+
sa.PrimaryKeyConstraint('id'),
43+
sa.UniqueConstraint('token_hash')
44+
)
45+
op.create_index(op.f('ix_password_reset_tokens_id'), 'password_reset_tokens', ['id'], unique=False)
46+
op.create_table('posts',
47+
sa.Column('id', sa.Integer(), nullable=False),
48+
sa.Column('title', sa.String(length=100), nullable=False),
49+
sa.Column('content', sa.Text(), nullable=False),
50+
sa.Column('user_id', sa.Integer(), nullable=False),
51+
sa.Column('date_posted', sa.DateTime(timezone=True), nullable=False),
52+
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
53+
sa.PrimaryKeyConstraint('id')
54+
)
55+
op.create_index(op.f('ix_posts_id'), 'posts', ['id'], unique=False)
56+
op.create_index(op.f('ix_posts_user_id'), 'posts', ['user_id'], unique=False)
57+
# ### end Alembic commands ###
58+
59+
60+
def downgrade() -> None:
61+
"""Downgrade schema."""
62+
# ### commands auto generated by Alembic - please adjust! ###
63+
op.drop_index(op.f('ix_posts_user_id'), table_name='posts')
64+
op.drop_index(op.f('ix_posts_id'), table_name='posts')
65+
op.drop_table('posts')
66+
op.drop_index(op.f('ix_password_reset_tokens_id'), table_name='password_reset_tokens')
67+
op.drop_table('password_reset_tokens')
68+
op.drop_index(op.f('ix_users_id'), table_name='users')
69+
op.drop_table('users')
70+
# ### end Alembic commands ###
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""add likes column to posts table
2+
3+
Revision ID: 78fd98ea52cc
4+
Revises: 5d49d2f24111
5+
Create Date: 2026-04-14 22:43:31.571998
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 = '78fd98ea52cc'
16+
down_revision: Union[str, Sequence[str], None] = '5d49d2f24111'
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+
"""Upgrade schema."""
23+
# ### commands auto generated by Alembic - please adjust! ###
24+
op.add_column('posts', sa.Column('likes', sa.Integer(), server_default='0', nullable=False))
25+
# ### end Alembic commands ###
26+
27+
28+
def downgrade() -> None:
29+
"""Downgrade schema."""
30+
# ### commands auto generated by Alembic - please adjust! ###
31+
op.drop_column('posts', 'likes')
32+
# ### end Alembic commands ###

config.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@
44
class Settings(BaseSettings):
55
model_config = SettingsConfigDict(
66
env_file=".env",
7-
env_file_encoding="utf-8"
7+
env_file_encoding="utf-8",
8+
extra="ignore"
89
)
910

11+
database_url: str
12+
1013
secret_key: SecretStr
1114
algorithm: str = "HS256"
1215
access_token_expire_minutes: int = 30

0 commit comments

Comments
 (0)