Skip to content

Commit 6bc6445

Browse files
committed
local database setup
1 parent ceb8f87 commit 6bc6445

File tree

9 files changed

+68
-9
lines changed

9 files changed

+68
-9
lines changed

backend/README.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
## Alembic database init
44

5-
Please edit `alembic.ini` and specify your database URI in the parameter `sqlalchemy.url = postgresql://<username>:<password>@<host>/<database_name>`.
5+
~~Please edit `alembic.ini` and specify your database URI in the parameter `sqlalchemy.url = postgresql://<username>:<password>@<host>/<database_name>`.~~
6+
7+
set the DATABASE_URI environment variable to the database URI, alembic will upgrade automatically on startup.
68

79
## REST Server Configuration
810

@@ -15,3 +17,10 @@ DATABASE_URI="postgresql://<username>:<password>@<host>/<database_name>"
1517
BACKEND_CORS_ORIGINS=["http://localhost", "http://localhost:4200", "http://localhost:3000", "http://localhost:8080", "https://localhost", "https://localhost:4200", "https://localhost:3000", "https://localhost:8080", "http://dev.ocgpt.laion.ai", "https://stag.ocgpt.laion.ai", "https://ocgpt.laion.ai"]
1618
1719
```
20+
21+
## Running the REST Server locally for development
22+
23+
Run two terminals (note the working directory for each):
24+
25+
- Terminal 1, to go `backend/scripts` and run `docker-compose up`. This will start postgres.
26+
- Terminal 2, to go `backend` and run `scripts/run-local.sh`. This will start the REST server.

backend/alembic.ini

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
[alembic]
44
# path to migration scripts
5-
script_location = alembic
5+
script_location = %(here)s/alembic
66

77
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
88
# Uncomment the line below if you want the files to be prepended with date and time
@@ -55,7 +55,7 @@ version_path_separator = os # Use os.pathsep. Default configuration used for ne
5555
# are written from script.py.mako
5656
# output_encoding = utf-8
5757

58-
sqlalchemy.url = postgresql://<username>:<password>@<host>/<database_name>
58+
# sqlalchemy.url = postgresql://<username>:<password>@<host>/<database_name>
5959

6060

6161
[post_write_hooks]
@@ -64,9 +64,9 @@ sqlalchemy.url = postgresql://<username>:<password>@<host>/<database_name>
6464
# detail and examples
6565

6666
# format using "black" - use the console_scripts runner, against the "black" entrypoint
67-
# hooks = black
68-
# black.type = console_scripts
69-
# black.entrypoint = black
67+
hooks = black
68+
black.type = console_scripts
69+
black.entrypoint = black
7070
# black.options = -l 79 REVISION_SCRIPT_FILENAME
7171

7272
# Logging configuration

backend/alembic/env.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
# -*- coding: utf-8 -*-
22
from logging.config import fileConfig
33

4+
import sqlmodel
45
from alembic import context
6+
from app import models # noqa: F401
57
from sqlalchemy import engine_from_config, pool
68

79
# this is the Alembic Config object, which provides
@@ -17,7 +19,7 @@
1719
# for 'autogenerate' support
1820
# from myapp import mymodel
1921
# target_metadata = mymodel.Base.metadata
20-
target_metadata = None
22+
target_metadata = sqlmodel.SQLModel.metadata
2123

2224
# other values from the config, defined by the needs of env.py,
2325
# can be acquired:

backend/app/config.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ class Settings(BaseSettings):
1111
DATABASE_URI: Optional[PostgresDsn] = None
1212

1313
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
14+
UPDATE_ALEMBIC: bool = True
15+
16+
PORT: int = 8000
17+
FASTAPI_RELOAD: bool = False
18+
UVICONR_WOWKERS: int = 1
1419

1520
@validator("BACKEND_CORS_ORIGINS", pre=True)
1621
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:

backend/app/database.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,7 @@
22
from app.config import settings
33
from sqlmodel import create_engine
44

5+
if settings.DATABASE_URI is None:
6+
raise ValueError("DATABASE_URI is not set")
7+
58
engine = create_engine(settings.DATABASE_URI)

backend/app/main.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
# -*- coding: utf-8 -*-
2+
from pathlib import Path
3+
4+
import alembic.command
5+
import alembic.config
6+
import fastapi
27
from app.api.v1.api import api_router
38
from app.config import settings
4-
from fastapi import FastAPI
9+
from loguru import logger
510
from starlette.middleware.cors import CORSMiddleware
611

7-
app = FastAPI(title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json")
12+
app = fastapi.FastAPI(title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json")
813

914
# Set all CORS enabled origins
1015
if settings.BACKEND_CORS_ORIGINS:
@@ -16,4 +21,19 @@
1621
allow_headers=["*"],
1722
)
1823

24+
if settings.UPDATE_ALEMBIC:
25+
26+
@app.on_event("startup")
27+
def alembic_upgrade():
28+
logger.info("Attempting to upgrade alembic on startup")
29+
try:
30+
alembic_ini_path = Path(__file__).parent.parent / "alembic.ini"
31+
alembic_cfg = alembic.config.Config(str(alembic_ini_path))
32+
alembic_cfg.set_main_option("sqlalchemy.url", settings.DATABASE_URI)
33+
alembic.command.upgrade(alembic_cfg, "head")
34+
logger.info("Successfully upgraded alembic on startup")
35+
except Exception:
36+
logger.exception("Alembic upgrade failed on startup")
37+
38+
1939
app.include_router(api_router, prefix=settings.API_V1_STR)

backend/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
alembic==1.8.1
22
fastapi==0.88.0
3+
loguru==0.6.0
34
psycopg2-binary==2.9.5
45
pydantic==1.9.1
56
python-dotenv==0.21.0

backend/scripts/docker-compose.yaml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
version: "3.7"
2+
3+
services:
4+
db:
5+
image: postgres
6+
restart: always
7+
ports:
8+
- 5432:5432
9+
environment:
10+
POSTGRES_USER: postgres
11+
POSTGRES_PASSWORD: postgres
12+
13+
adminer:
14+
image: adminer
15+
restart: always
16+
ports:
17+
- 8089:8080

backend/scripts/run-local.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
#!/usr/bin/env bash
22

3+
export DATABASE_URI=postgresql://postgres:postgres@localhost:5432/postgres
4+
35
uvicorn app.main:app --reload

0 commit comments

Comments
 (0)