Skip to content

Commit 1ef602f

Browse files
committed
progress on a handrolled repository
1 parent 074a177 commit 1ef602f

5 files changed

Lines changed: 58 additions & 14 deletions

File tree

‎adapters/orm.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
1-
from sqlalchemy import Table, MetaData, Column, Integer, String, Date, ForeignKey
1+
from sqlalchemy import (
2+
Column,
3+
Date,
4+
ForeignKey,
5+
Integer,
6+
MetaData,
7+
String,
8+
Table,
9+
UniqueConstraint,
10+
)
211
from sqlalchemy.orm import mapper, relationship
312

413
from domain import model
@@ -13,13 +22,14 @@
1322
Column("sku", String(255)),
1423
Column("qty", Integer, nullable=False),
1524
Column("orderid", String(255)),
25+
UniqueConstraint("orderid", "sku", "qty"),
1626
)
1727

1828
batches = Table(
1929
"batches",
2030
metadata,
2131
Column("id", Integer, primary_key=True, autoincrement=True),
22-
Column("reference", String(255)),
32+
Column("ref", String(255)),
2333
Column("sku", String(255)),
2434
Column("_purchased_quantity", Integer, nullable=False),
2535
Column("eta", Date, nullable=True),
@@ -31,4 +41,5 @@
3141
Column("id", Integer, primary_key=True, autoincrement=True),
3242
Column("orderline_id", ForeignKey("order_lines.id")),
3343
Column("batch_id", ForeignKey("batches.id")),
44+
UniqueConstraint("orderline_id", "batch_id")
3445
)

‎adapters/repository.py‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import abc
22
from domain import model
3+
from typing import Iterable
34

45

56
class AbstractRepository(abc.ABC):
@@ -14,10 +15,41 @@ def get(self, reference) -> model.Batch:
1415

1516
class SqlAlchemyRepository(AbstractRepository):
1617
def __init__(self, session):
17-
self.session = session
18-
19-
def add(self, batch):
20-
self.session.add(batch)
18+
self._session = session
19+
20+
async def add(self, batch):
21+
batch_id = await self._add_batch(batch)
22+
await self._add_allocations(batch_id, batch._allocations)
23+
24+
async def _add_batch(self, batch: model.Batch):
25+
async with self._session as session:
26+
async with session.begin():
27+
result = await session.execute(
28+
"""
29+
INSERT INTO batches (ref, sku, _purchased_quantity, eta)
30+
VALUES ( :ref, :sku, :_purchased_quantity, :eta )
31+
RETURNING id
32+
""",
33+
dict(ref=batch.ref, sku=batch.sku, _purchased_quantity=batch._purchased_quantity, eta=batch.eta),
34+
35+
)
36+
[batch_id] = result
37+
return batch_id
38+
39+
async def _add_allocations(self, batch_id: int, allocations: Iterable[model.OrderLine]):
40+
return
41+
# for line in allocations:
42+
# async with self._session as session:
43+
# await session.execute(
44+
# """
45+
# INSERT INTO order_lines (orderline_id, batch_id)
46+
# VALUES ( %{orderline_id}d, %{batch_id}d )
47+
# ON CONFLICT DO UPDATE SET
48+
# orderline_id=%{orderline_id}d,
49+
# batchid=%{batch_id}d,
50+
# """,
51+
# dict(batch_id=batch_id, orderline_id=
52+
# )
2153

2254
def get(self, reference):
2355
return self.session.query(model.Batch).filter_by(reference=reference).one()

‎requirements.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ psycopg2-binary
55
requests
66
mypy
77
black
8+
aiosqlite

‎tests/conftest.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from pathlib import Path
44

55
import pytest
6+
import pytest_asyncio
67
import requests
78
from requests.exceptions import ConnectionError
89
from typing import Callable
@@ -19,17 +20,17 @@
1920
import config
2021

2122

22-
@pytest.fixture
23+
@pytest_asyncio.fixture
2324
async def in_memory_db() -> AsyncEngine:
24-
engine = create_async_engine("sqlite:///:memory:")
25+
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
2526
async with engine.begin() as conn:
2627
await conn.run_sync(metadata.create_all)
2728
return engine
2829

2930

30-
@pytest.fixture
31-
def session_maker(in_memory_db: AsyncEngine):
32-
yield sessionmaker(bind=in_memory_db, class_=AsyncSession)
31+
@pytest_asyncio.fixture
32+
async def session_maker(in_memory_db: AsyncEngine):
33+
return sessionmaker(bind=in_memory_db, class_=AsyncSession)
3334

3435

3536
def wait_for_postgres_to_come_up(engine):

‎tests/integration/test_repository.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,11 @@ async def test_repository_can_save_a_batch(session_maker):
1111
async with session_maker() as session:
1212
repo = repository.SqlAlchemyRepository(session)
1313
await repo.add(batch)
14-
await repo.commit()
1514

1615
async with session_maker() as session:
1716
async with session.begin():
18-
rows = session.execute(
19-
'SELECT reference, sku, _purchased_quantity, eta FROM "batches"'
17+
rows = await session.execute(
18+
'SELECT ref, sku, _purchased_quantity, eta FROM "batches"'
2019
)
2120
assert list(rows) == [("batch1", "RUSTY-SOAPDISH", 100, None)]
2221

0 commit comments

Comments
 (0)