Skip to content

Commit 9bfb5f0

Browse files
committed
transactions wip
1 parent aa4b82a commit 9bfb5f0

File tree

9 files changed

+31
-41
lines changed

9 files changed

+31
-41
lines changed

aragorm/engine/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from .base import Engine
2+
from .postgres import PostgresEngine
3+
4+
5+
__all__ = ['Engine', 'PostgresEngine']

aragorm/engine/base.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
class Engine():
2+
pass
Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import asyncio
21
import typing as t
32

43
import asyncpg
54
from asyncpg.pool import Pool
65

6+
from .base import Engine
77

8-
class Engine():
8+
9+
class PostgresEngine(Engine):
910
"""
1011
Currently when using run ... it sets up a connection each time.
1112
@@ -14,12 +15,10 @@ class Engine():
1415
Needs to be a singleton that's shared by all the tables.
1516
"""
1617

17-
pool: t.Optional[Pool] = None
18-
1918
def __init__(self, config: t.Dict[str, t.Any]) -> None:
2019
self.config = config
2120

22-
async def get_pool(self):
21+
async def get_pool(self) -> Pool:
2322
if not self.pool:
2423
self.pool = await asyncpg.create_pool(
2524
**self.config
@@ -29,12 +28,12 @@ async def get_pool(self):
2928
async def run(self, query: str):
3029
pool = await self.get_pool()
3130

32-
async with pool.acquire() as connection:
33-
response = connection.fetch(query)
31+
connection = await pool.acquire()
32+
try:
33+
response = await connection.fetch(query)
34+
except Exception:
35+
pass
36+
finally:
37+
await pool.release(connection)
3438

3539
return response
36-
37-
def run_sync(self, query: str):
38-
return asyncio.run(
39-
self.run(query)
40-
)

aragorm/migration.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import click
1212
import asyncpg
1313

14+
from aragorm.engine import PostgresEngine
1415
from aragorm.migrations.template import TEMPLATE
1516
from aragorm.migrations.table import Migration
1617

@@ -129,7 +130,7 @@ def forwards():
129130
print('Running migrations ...')
130131
sys.path.insert(0, os.getcwd())
131132

132-
Migration.Meta.db = _get_config()
133+
Migration.Meta.db = PostgresEngine(_get_config())
133134

134135
_create_migration_table()
135136

@@ -172,7 +173,7 @@ def backwards(migration_name: str):
172173
_get_config() # Just required for path manipulation - needs changing
173174
_get_migration_modules()
174175

175-
Migration.Meta.db = _get_config()
176+
Migration.Meta.db = PostgresEngine(_get_config())
176177

177178
_create_migration_table()
178179

aragorm/query/base.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,14 @@ def __init__(self, table: 'Table', base: str = '', *args,
1717
self.table = table
1818
super().__init__()
1919

20-
async def run(self, as_dict=True, credentials=None):
21-
"""
22-
Should use an engine.
23-
"""
24-
if not credentials:
25-
credentials = getattr(self.table.Meta, 'db', None)
26-
if not credentials:
20+
async def run(self, as_dict=True):
21+
engine = getattr(self.table.Meta, 'db', None)
22+
if not engine:
2723
raise ValueError(
2824
f'Table {self.table.Meta.tablename} has no db defined in Meta'
2925
)
3026

31-
conn = await asyncpg.connect(**credentials)
32-
results = await conn.fetch(self.__str__())
33-
await conn.close()
27+
results = await engine.run(self.__str__())
3428

3529
if results:
3630
keys = results[0].keys()

aragorm/table.py

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import typing as t
33

44
from .alter import Alter
5+
from .engine import Engine
56
from .columns import Column, PrimaryKey, ForeignKey
67
from .query import (
78
Create,
@@ -18,17 +19,6 @@
1819
from .utils import _camel_to_snake
1920

2021

21-
class Database(object):
22-
23-
async def run(*queries):
24-
"""
25-
Use asyncio.gather here ...
26-
27-
I think I'll call it Engine instead ...
28-
"""
29-
pass
30-
31-
3222
class TableMeta(type):
3323

3424
def __new__(cls, name, bases, namespace, **kwds):
@@ -67,7 +57,7 @@ class Table(metaclass=TableMeta):
6757
class Meta:
6858
tablename = None
6959
columns: t.List[Column] = []
70-
db: t.Optional[t.Dict[t.Any, t.Any]] = None
60+
db: t.Optional[Engine] = None
7161

7262
def __init__(self, **kwargs):
7363
"""

tests/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class DBTestCase(TestCase):
1010

1111
def run_sync(self, query):
1212
async def _run():
13-
connection = await asyncpg.connect(**Pokemon.Meta.db)
13+
connection = await asyncpg.connect(**Pokemon.Meta.db.config)
1414
await connection.execute(query)
1515
await connection.close()
1616

tests/example_project/tables.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
from aragorm import table
22
from aragorm import columns
3+
from aragorm.engine import PostgresEngine
34

45

5-
DB = {
6+
DB = PostgresEngine({
67
'host': 'localhost',
78
'database': 'aragorm',
89
'user': 'aragorm',
910
'password': 'aragorm'
10-
}
11+
})
1112

1213

1314
###############################################################################

tests/test_migration.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
import asyncio
21
from unittest import TestCase
32

4-
import asyncpg
53
from aragorm.migrations.table import Migration
64

75
from .example_project.tables import DB

0 commit comments

Comments
 (0)