Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 12 additions & 14 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,40 +14,37 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.9]
python-version: ['3.10']

steps:
- name: Checkout the repository
uses: actions/checkout@v2
uses: actions/checkout@v5

- name: Setup Python
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
uses: astral-sh/ruff-action@v3

- name: Install package
run: |
pip install mypy
pip install black
pip install isort
- name: Run pre-checks
run: |
mypy fastapi_asyncpg/
isort -c -rc fastapi_asyncpg/
black -l 80 --check --verbose fastapi_asyncpg/
ruff check .
ruff format --check .

# Job to run tests
tests:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.7, 3.8, 3.9]
python-version: ['3.9','3.10']
# Set environment variables
steps:
- name: Checkout the repository
uses: actions/checkout@v2
uses: actions/checkout@v5

- name: Setup Python
uses: actions/setup-python@v1
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}

Expand All @@ -60,6 +57,7 @@ jobs:
pytest -vs tests/

- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
uses: codecov/codecov-action@v5
with:
file: ./coverage.xml
files: ./coverage.xml

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ pyvenv.cfg
*.profraw
*.py?
*.swp
.venv
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.10
19 changes: 8 additions & 11 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
.PHONY: isort black flake8 mypy

lint: isort black flake8 mypy

isort:
isort fastapi_asyncpg

black:
black fastapi_asyncpg/ -l 80

flake8:
flake8 fastapi_asyncpg
lint:
uv run --python 3.10 --extra dev ruff check . --fix
uv run --python 3.10 --extra dev ruff format .

mypy:
mypy fastapi_asyncpg
uv run --python 3.10 --extra dev mypy fastapi_asyncpg

test:
uv run --python 3.9 --extra test pytest tests
uv run --python 3.10 --extra test pytest tests
10 changes: 4 additions & 6 deletions fastapi_asyncpg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def __init__(
app: FastAPI,
dsn: str,
*,
init_db: typing.Callable = None, # callable for running sql on init
init_db: typing.Optional[typing.Callable] = None, # callable for running sql on init
pool=None, # usable on testing
**options,
):
Expand Down Expand Up @@ -117,7 +117,7 @@ class SingleConnectionTestingPool:
def __init__(
self,
conn: asyncpg.Connection,
initialize: typing.Callable = None,
initialize: typing.Optional[typing.Callable] = None,
add_logger_postgres: bool = False,
):
self._conn = conn
Expand Down Expand Up @@ -154,16 +154,14 @@ def __getattr__(self, key):
async def create_pool_test(
dsn: str,
*,
initialize: typing.Callable = None,
initialize: typing.Optional[typing.Callable] = None,
add_logger_postgres: bool = False,
):
"""This part is only used for testing,
we create a fake "pool" that just starts a connecion,
that does a transaction inside it"""
conn = await asyncpg.connect(dsn=dsn)
pool = SingleConnectionTestingPool(
conn, initialize=initialize, add_logger_postgres=add_logger_postgres
)
pool = SingleConnectionTestingPool(conn, initialize=initialize, add_logger_postgres=add_logger_postgres)
return pool


Expand Down
8 changes: 2 additions & 6 deletions fastapi_asyncpg/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ async def select(conn, table, condition="1 = 1", args=None, fields="*"):

async def count(conn, table, where="1=1", args=None):
args = args or []
return await conn.fetchval(
f"select count(*) from {table} WHERE {where}", *args
)
return await conn.fetchval(f"select count(*) from {table} WHERE {where}", *args)


async def insert(conn, table, values):
Expand All @@ -45,9 +43,7 @@ async def update(conn, table, conditions: dict, values: dict):
vals.append(f"{column}=${counter}")
params.append(value)
counter += 1
sql = qs.format(
table=table, columns=" ,".join(vals), cond=" AND ".join(cond)
)
sql = qs.format(table=table, columns=" ,".join(vals), cond=" AND ".join(cond))
return await conn.fetchrow(sql, *params)


Expand Down
69 changes: 69 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
[build-system]
requires = ["setuptools>=45", "setuptools-scm[toml]>=6.2"]
build-backend = "setuptools.build_meta"

[project]
name = "fastapi_asyncpg"
version = "1.0.1"
description = "FastAPI integration for asyncpg"
readme = "README.md"
requires-python = ">=3.9,<3.11"
license = {text = "MIT"}
authors = [
{name = "Jordi collell", email = "jordic@gmail.com"}
]
classifiers = [
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
]
dependencies = [
"fastapi",
"asyncpg",
]

[project.optional-dependencies]
dev = [
"ruff",
"mypy"
]
docs = [
"sphinx",
"recommonmark",
]
test = [
"pytest-docker-fixtures[pg]",
"pytest",
"async_asgi_testclient",
"pytest-asyncio",
]
publish = [
"twine",
]

[project.urls]
Homepage = "https://github.com/jordic/fastapi_asyncpg"

[tool.setuptools]
packages = {find = {exclude = ["tests"]}}

[tool.setuptools.package-data]
fastapi = ["py.typed"]

[tool.ruff]
line-length = 120
exclude = [".git", "__pycache__", "docs/source/conf.py", "old", "build", "dist"]

[tool.ruff.lint]
ignore = ["E302", "W391", "E701", "F901", "E252", "E203"]

[tool.ruff.format]
line-ending = "auto"

[tool.mypy]
namespace_packages = true

[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
18 changes: 0 additions & 18 deletions setup.cfg

This file was deleted.

48 changes: 0 additions & 48 deletions setup.py

This file was deleted.

12 changes: 4 additions & 8 deletions tests/test_con_rollback.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@

dir = Path(__file__).parent

images.configure(
"postgresql", "postgres", "11.1", env={"POSTGRES_DB": "test_db"}
)
images.configure("postgresql", "postgres", "11.1", env={"POSTGRES_DB": "test_db"})


@pytest.fixture
Expand Down Expand Up @@ -48,7 +46,7 @@ async def test_the_db_is_empty_again(pool):


async def test_sql(pool):
""" sql.py contains poor man sql helpers to work with sql and asyncpg """
"""sql.py contains poor man sql helpers to work with sql and asyncpg"""
async with pool.acquire() as db:
res = await sql.insert(db, "test", {"item": "test", "val": "value"})
result = await sql.get(db, "test", "id=$1", args=[res["id"]])
Expand Down Expand Up @@ -104,13 +102,11 @@ class Schema(pd.BaseModel):

item: str
val: str
id: typing.Optional[int]
id: typing.Optional[int] = None

async def save(self, db):
if self.id is None:
result = await sql.insert(
db, self.__tablename__, self.dict(exclude_unset=True)
)
result = await sql.insert(db, self.__tablename__, self.dict(exclude_unset=True))
self.id = result["id"]
else:
result = await sql.update_by(
Expand Down
16 changes: 4 additions & 12 deletions tests/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
import pytest
import asyncio

images.configure(
"postgresql", "postgres", "11.1", env={"POSTGRES_DB": "test_db"}
)
images.configure("postgresql", "postgres", "11.1", env={"POSTGRES_DB": "test_db"})

pytestmark = pytest.mark.asyncio

Expand Down Expand Up @@ -56,13 +54,9 @@ async def add_resource(data: KeyVal, db=Depends(bdd.connection)):
return dict(result)

@app.get("/transaction")
async def with_transaction(
q: Optional[int] = 0, db=Depends(bdd.transaction)
):
async def with_transaction(q: Optional[int] = 0, db=Depends(bdd.transaction)):
for i in range(10):
await db.execute(
"INSERT INTO keyval values ($1, $2)", f"t{i}", f"t{i}"
)
await db.execute("INSERT INTO keyval values ($1, $2)", f"t{i}", f"t{i}")
if q == 1:
raise HTTPException(412)
return dict(result="ok")
Expand Down Expand Up @@ -121,7 +115,5 @@ async def test_pool_releases_connections(asgiapp):

await asyncio.gather(*tasks)
async with app.state.pool.acquire() as db:
result = await db.fetchval(
"SELECT sum(numbackends) FROM pg_stat_database;"
)
result = await db.fetchval("SELECT sum(numbackends) FROM pg_stat_database;")
assert result == 2
6 changes: 0 additions & 6 deletions tox.ini

This file was deleted.

Loading
Loading