Skip to content

Commit f925da7

Browse files
authored
Merge pull request #4 from script-logic/feature/database-implementation
feat: database implementation
2 parents 136ff44 + 375a736 commit f925da7

26 files changed

Lines changed: 2201 additions & 87 deletions

.dockerignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ env/
4848
.env
4949
.env.local
5050
.env.*.local
51+
scan_project.py
52+
project_scan_output.txt
5153

5254
# IDEs
5355
.vscode/

.env.example

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ REDIS__DB=0
1919
APPLICATION__DEBUG=False
2020
APPLICATION__API_V1_PREFIX=/api/v1
2121
APPLICATION__PROJECT_NAME=Deribit Price Tracker API
22-
APPLICATION__VERSION=0.2.0
22+
APPLICATION__VERSION=0.3.0
2323

2424
# CORS Configuration
2525
CORS__ORIGINS=["http://localhost:8000","http://127.0.0.1:8000"]

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ credentials/
1212
# pytest
1313
.pytest_cache/
1414
.cache/
15+
scan_project.py
16+
project_scan_output.txt
1517

1618
# coverage
1719
.coverage

.secrets.baseline

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,10 @@
9090
{
9191
"path": "detect_secrets.filters.allowlist.is_line_allowlisted"
9292
},
93+
{
94+
"path": "detect_secrets.filters.common.is_baseline_file",
95+
"filename": ".secrets.baseline"
96+
},
9397
{
9498
"path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
9599
"min_level": 2
@@ -139,6 +143,24 @@
139143
"line_number": 103
140144
}
141145
],
146+
"alembic.ini": [
147+
{
148+
"type": "Basic Auth Credentials",
149+
"filename": "alembic.ini",
150+
"hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8",
151+
"is_verified": false,
152+
"line_number": 89
153+
}
154+
],
155+
"alembic\\versions\\b1494e573776_create_price_ticks_table.py": [
156+
{
157+
"type": "Hex High Entropy String",
158+
"filename": "alembic\\versions\\b1494e573776_create_price_ticks_table.py",
159+
"hashed_secret": "365aef3fd6fec3397a72177f4930f4bb20510b88",
160+
"is_verified": false,
161+
"line_number": 16
162+
}
163+
],
142164
"app\\core\\config.py": [
143165
{
144166
"type": "Basic Auth Credentials",
@@ -207,5 +229,5 @@
207229
}
208230
]
209231
},
210-
"generated_at": "2026-01-23T18:44:37Z"
232+
"generated_at": "2026-01-24T19:55:12Z"
211233
}

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 = postgresql://user:password@host:port/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/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: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
"""
2+
Alembic environment configuration using synchronous engine.
3+
"""
4+
5+
import sys
6+
from logging.config import fileConfig
7+
from pathlib import Path
8+
9+
from sqlalchemy import engine_from_config, pool
10+
11+
from alembic import context # type: ignore
12+
13+
sys.path.append(str(Path(__file__).parent.parent))
14+
15+
from app.core import settings
16+
from app.database import Base
17+
from app.database.models import PriceTick # noqa
18+
19+
config = context.config
20+
21+
if config.config_file_name is not None:
22+
fileConfig(config.config_file_name)
23+
24+
db_password = settings.database.password.get_secret_value()
25+
db_host = settings.database.host
26+
config.set_main_option(
27+
"sqlalchemy.url",
28+
f"postgresql://{settings.database.user}:{db_password}@"
29+
f"{db_host}:{settings.database.port}/{settings.database.db}",
30+
)
31+
32+
target_metadata = Base.metadata
33+
34+
35+
def run_migrations_offline() -> None:
36+
url = config.get_main_option("sqlalchemy.url")
37+
38+
if url and url.startswith("postgresql+asyncpg://"):
39+
url = url.replace("postgresql+asyncpg://", "postgresql://")
40+
41+
context.configure(
42+
url=url,
43+
target_metadata=target_metadata,
44+
literal_binds=True,
45+
dialect_opts={"paramstyle": "named"},
46+
)
47+
48+
with context.begin_transaction():
49+
context.run_migrations()
50+
51+
52+
def run_migrations_online() -> None:
53+
configuration = config.get_section(config.config_ini_section, {})
54+
55+
url = configuration.get("sqlalchemy.url", "")
56+
if url.startswith("postgresql+asyncpg://"):
57+
configuration["sqlalchemy.url"] = url.replace(
58+
"postgresql+asyncpg://", "postgresql://"
59+
)
60+
61+
connectable = engine_from_config(
62+
configuration,
63+
prefix="sqlalchemy.",
64+
poolclass=pool.NullPool,
65+
)
66+
67+
with connectable.connect() as connection:
68+
context.configure(
69+
connection=connection,
70+
target_metadata=target_metadata,
71+
)
72+
73+
with context.begin_transaction():
74+
context.run_migrations()
75+
76+
77+
if context.is_offline_mode():
78+
run_migrations_offline()
79+
else:
80+
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: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""Create price_ticks table
2+
3+
Revision ID: b1494e573776
4+
Revises:
5+
Create Date: 2026-01-24 21:27:51.504960
6+
7+
"""
8+
9+
from collections.abc import Sequence
10+
11+
import sqlalchemy as sa
12+
13+
from alembic import op # type: ignore
14+
15+
# revision identifiers, used by Alembic.
16+
revision: str = "b1494e573776"
17+
down_revision: str | Sequence[str] | None = None
18+
branch_labels: str | Sequence[str] | None = None
19+
depends_on: str | Sequence[str] | None = None
20+
21+
22+
def upgrade() -> None:
23+
"""Upgrade schema."""
24+
# ### commands auto generated by Alembic - please adjust! ###
25+
op.create_table(
26+
"price_ticks",
27+
sa.Column("id", sa.BigInteger(), nullable=False),
28+
sa.Column("ticker", sa.String(length=20), nullable=False),
29+
sa.Column("price", sa.Float(), nullable=False),
30+
sa.Column("timestamp", sa.BigInteger(), nullable=False),
31+
sa.Column(
32+
"created_at",
33+
sa.DateTime(timezone=True),
34+
server_default=sa.text("now()"),
35+
nullable=False,
36+
),
37+
sa.PrimaryKeyConstraint("id"),
38+
)
39+
op.create_index(
40+
op.f("ix_price_ticks_ticker"),
41+
"price_ticks",
42+
["ticker"],
43+
unique=False,
44+
)
45+
op.create_index(
46+
op.f("ix_price_ticks_timestamp"),
47+
"price_ticks",
48+
["timestamp"],
49+
unique=False,
50+
)
51+
# ### end Alembic commands ###
52+
53+
54+
def downgrade() -> None:
55+
"""Downgrade schema."""
56+
# ### commands auto generated by Alembic - please adjust! ###
57+
op.drop_index(op.f("ix_price_ticks_timestamp"), table_name="price_ticks")
58+
op.drop_index(op.f("ix_price_ticks_ticker"), table_name="price_ticks")
59+
op.drop_table("price_ticks")
60+
# ### end Alembic commands ###

0 commit comments

Comments
 (0)