Skip to content

Commit 82b13d9

Browse files
ImTotemclaude
andcommitted
feat(infra): PostgreSQL as primary DB, Sheets as view-only backup
- Phase 1: SQLAlchemy Core + Alembic setup (database.py, tables.py, 10 tables) - Phase 2: PgMemberRepository, PgLinkRepository replacing Sheets repos - DI swap in dependencies.py (get_conn, PG-backed repos) - member/service get_filters reads enum tables from PG - track.py queries PG instead of Sheets - redirect.py: remove BackgroundTasks (PG INSERT is sub-ms), redirect to /expired on Gone instead of JSON error - Phase 3: sync/router.py with GET /v1/internal/dump/{table} and POST /v1/internal/expire-links for n8n cron - sync/seed.py for one-time Sheets→PG data migration - PG is now required at startup (no silent fallback) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 988c5a7 commit 82b13d9

21 files changed

Lines changed: 811 additions & 49 deletions

.env.example

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,13 @@ COOKIE_SECURE=false
2626
POSTGRES_USER=bcsd
2727
POSTGRES_PASSWORD=change-me
2828
POSTGRES_DB=bcsd
29+
POSTGRES_HOST=postgres
2930
POSTGRES_PORT=5432
3031
POSTGRES_VOLUME_PATH=/home/ubuntu/bcsd-data/postgres
3132

33+
# 내부 API 인증 (n8n → API 동기화용)
34+
SYNC_TOKEN=change-me-random-string
35+
3236
REDIS_PASSWORD=change-me
3337
REDIS_PORT=6379
3438
REDIS_VOLUME_PATH=/home/ubuntu/bcsd-data/redis

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+
24+
# timezone to use when rendering the date within the migration file
25+
# as well as the filename.
26+
# If specified, requires the tzdata library which can be installed by adding
27+
# `alembic[tz]` to the pip requirements.
28+
# string value is passed to ZoneInfo()
29+
# leave blank for localtime
30+
# timezone =
31+
32+
# max length of characters to apply to the "slug" field
33+
# truncate_slug_length = 40
34+
35+
# set to 'true' to run the environment during
36+
# the 'revision' command, regardless of autogenerate
37+
# revision_environment = false
38+
39+
# set to 'true' to allow .pyc and .pyo files without
40+
# a source .py file to be detected as revisions in the
41+
# versions/ directory
42+
# sourceless = false
43+
44+
# version location specification; This defaults
45+
# to <script_location>/versions. When using multiple version
46+
# directories, initial revisions must be specified with --version-path.
47+
# The path separator used here should be the separator specified by "path_separator"
48+
# below.
49+
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
50+
51+
# path_separator; This indicates what character is used to split lists of file
52+
# paths, including version_locations and prepend_sys_path within configparser
53+
# files such as alembic.ini.
54+
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
55+
# to provide os-dependent path splitting.
56+
#
57+
# Note that in order to support legacy alembic.ini files, this default does NOT
58+
# take place if path_separator is not present in alembic.ini. If this
59+
# option is omitted entirely, fallback logic is as follows:
60+
#
61+
# 1. Parsing of the version_locations option falls back to using the legacy
62+
# "version_path_separator" key, which if absent then falls back to the legacy
63+
# behavior of splitting on spaces and/or commas.
64+
# 2. Parsing of the prepend_sys_path option falls back to the legacy
65+
# behavior of splitting on spaces, commas, or colons.
66+
#
67+
# Valid values for path_separator are:
68+
#
69+
# path_separator = :
70+
# path_separator = ;
71+
# path_separator = space
72+
# path_separator = newline
73+
#
74+
# Use os.pathsep. Default configuration used for new projects.
75+
path_separator = os
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

alembic/env.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from logging.config import fileConfig
2+
3+
from sqlalchemy import pool
4+
from sqlalchemy import engine_from_config
5+
6+
from alembic import context
7+
8+
from bcsd_api.config import Settings
9+
from bcsd_api.database import metadata
10+
import bcsd_api.tables # noqa: F401 — registers tables on metadata
11+
12+
config = context.config
13+
14+
if config.config_file_name is not None:
15+
fileConfig(config.config_file_name)
16+
17+
settings = Settings()
18+
config.set_main_option("sqlalchemy.url", settings.database_url)
19+
20+
target_metadata = metadata
21+
22+
23+
def run_migrations_offline() -> None:
24+
url = config.get_main_option("sqlalchemy.url")
25+
context.configure(
26+
url=url,
27+
target_metadata=target_metadata,
28+
literal_binds=True,
29+
dialect_opts={"paramstyle": "named"},
30+
)
31+
with context.begin_transaction():
32+
context.run_migrations()
33+
34+
35+
def run_migrations_online() -> None:
36+
connectable = engine_from_config(
37+
config.get_section(config.config_ini_section, {}),
38+
prefix="sqlalchemy.",
39+
poolclass=pool.NullPool,
40+
)
41+
with connectable.connect() as connection:
42+
context.configure(
43+
connection=connection,
44+
target_metadata=target_metadata,
45+
)
46+
with context.begin_transaction():
47+
context.run_migrations()
48+
49+
50+
if context.is_offline_mode():
51+
run_migrations_offline()
52+
else:
53+
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"}

alembic/versions/001_initial.py

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
"""initial schema
2+
3+
Revision ID: 001
4+
Revises:
5+
Create Date: 2026-03-17
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
13+
revision: str = "001"
14+
down_revision: Union[str, Sequence[str], None] = None
15+
branch_labels: Union[str, Sequence[str], None] = None
16+
depends_on: Union[str, Sequence[str], None] = None
17+
18+
19+
def upgrade() -> None:
20+
op.create_table(
21+
"members",
22+
sa.Column("id", sa.String, primary_key=True),
23+
sa.Column("name", sa.String, nullable=False),
24+
sa.Column("email", sa.String, nullable=False, unique=True),
25+
sa.Column("department", sa.String),
26+
sa.Column("student_id", sa.String),
27+
sa.Column("school_email", sa.String),
28+
sa.Column("phone", sa.String),
29+
sa.Column("status", sa.String, nullable=False, server_default="Beginner"),
30+
sa.Column("track", sa.String),
31+
sa.Column("team", sa.String),
32+
sa.Column("role", sa.String),
33+
sa.Column("join_date", sa.String),
34+
sa.Column("payment_status", sa.String, server_default="Unpaid"),
35+
sa.Column("last_updated", sa.String),
36+
)
37+
38+
op.create_table(
39+
"tracks",
40+
sa.Column("name", sa.String, primary_key=True),
41+
)
42+
43+
op.create_table(
44+
"statuses",
45+
sa.Column("name", sa.String, primary_key=True),
46+
)
47+
48+
op.create_table(
49+
"payment_statuses",
50+
sa.Column("name", sa.String, primary_key=True),
51+
)
52+
53+
op.create_table(
54+
"groups",
55+
sa.Column("id", sa.String, primary_key=True),
56+
sa.Column("name", sa.String),
57+
sa.Column("type", sa.String),
58+
sa.Column("parent_id", sa.String),
59+
sa.Column("size", sa.Integer),
60+
sa.Column("leader_email", sa.String),
61+
sa.Column("last_updated", sa.String),
62+
)
63+
64+
op.create_table(
65+
"events",
66+
sa.Column("id", sa.String, primary_key=True),
67+
sa.Column("title", sa.String),
68+
sa.Column("date", sa.String),
69+
sa.Column("type", sa.String),
70+
sa.Column("organizer", sa.String),
71+
sa.Column("attendees", sa.Text),
72+
sa.Column("notes", sa.Text),
73+
)
74+
75+
op.create_table(
76+
"workflow_logs",
77+
sa.Column("timestamp", sa.String, primary_key=True),
78+
sa.Column("workflow_name", sa.String, primary_key=True),
79+
sa.Column("status", sa.String),
80+
sa.Column("input_data", sa.Text),
81+
sa.Column("output_data", sa.Text),
82+
sa.Column("error_message", sa.Text),
83+
)
84+
85+
op.create_table(
86+
"fees",
87+
sa.Column("id", sa.String, primary_key=True),
88+
sa.Column("member_id", sa.String, sa.ForeignKey("members.id")),
89+
sa.Column("amount", sa.Integer),
90+
sa.Column("paid_date", sa.String),
91+
sa.Column("payment_method", sa.String),
92+
sa.Column("notes", sa.Text),
93+
sa.Column("semester", sa.String),
94+
sa.Column("last_updated", sa.String),
95+
)
96+
97+
op.create_table(
98+
"links",
99+
sa.Column("id", sa.String, primary_key=True),
100+
sa.Column("code", sa.String, nullable=False, unique=True),
101+
sa.Column("title", sa.String, nullable=False),
102+
sa.Column("description", sa.Text),
103+
sa.Column("url", sa.Text, nullable=False),
104+
sa.Column("creator_id", sa.String, sa.ForeignKey("members.id")),
105+
sa.Column("created_at", sa.String),
106+
sa.Column("expires_at", sa.String),
107+
sa.Column("expired_at", sa.String),
108+
sa.Column("updated_at", sa.String),
109+
)
110+
111+
op.create_table(
112+
"link_clicks",
113+
sa.Column("id", sa.String, primary_key=True),
114+
sa.Column(
115+
"link_id",
116+
sa.String,
117+
sa.ForeignKey("links.id", ondelete="CASCADE"),
118+
),
119+
sa.Column("clicked_at", sa.String),
120+
sa.Column("referer", sa.Text),
121+
sa.Column("user_agent", sa.Text),
122+
)
123+
124+
125+
def downgrade() -> None:
126+
op.drop_table("link_clicks")
127+
op.drop_table("links")
128+
op.drop_table("fees")
129+
op.drop_table("workflow_logs")
130+
op.drop_table("events")
131+
op.drop_table("groups")
132+
op.drop_table("payment_statuses")
133+
op.drop_table("statuses")
134+
op.drop_table("tracks")
135+
op.drop_table("members")

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ dependencies = [
1717

1818
"resend>=2.0.0",
1919
"authzed>=1.0.0",
20+
"sqlalchemy>=2.0",
21+
"psycopg[binary]>=3.1",
22+
"alembic>=1.13",
2023
]
2124

2225
[project.optional-dependencies]

0 commit comments

Comments
 (0)