Skip to content

Commit bcdf4bc

Browse files
committed
docs: Add example
1 parent 383d107 commit bcdf4bc

File tree

5 files changed

+75
-2
lines changed

5 files changed

+75
-2
lines changed

example/__init__.py

Whitespace-only changes.

example/connection.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from sqlalchemy.ext.asyncio import create_async_engine
2+
from sqlalchemy.orm import DeclarativeBase
3+
4+
from sqlalchemy_tx_context import SQLAlchemyTransactionContext
5+
6+
connect_args = dict(
7+
max_cached_statement_lifetime=0,
8+
statement_cache_size=5000,
9+
server_settings={
10+
'application_name': 'test'
11+
}
12+
)
13+
14+
15+
engine = create_async_engine(
16+
'postgresql+asyncpg://test:[email protected]:5432/test',
17+
connect_args=connect_args,
18+
pool_size=1,
19+
max_overflow=0
20+
)
21+
22+
db = SQLAlchemyTransactionContext(engine)
23+
24+
25+
class Base(DeclarativeBase):
26+
__abstract__ = True

example/models.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from sqlalchemy import String
2+
from sqlalchemy.orm import Mapped, mapped_column
3+
4+
from example.connection import Base
5+
6+
7+
class Test(Base):
8+
__tablename__ = 'test'
9+
10+
id: Mapped[int] = mapped_column(primary_key=True)
11+
name: Mapped[str] = mapped_column(String(36), unique=True)
12+
13+
def get_id(self):
14+
return self.id

example/queries.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import asyncio
2+
3+
from example.connection import db
4+
from example.models import Test
5+
6+
7+
async def test():
8+
delete_result = await db.delete(Test).rowcount()
9+
10+
print('Delete result', delete_result)
11+
12+
insert_result = await db.insert(Test).values(id=1, name='test 1').execute()
13+
print(
14+
'Inserted count',
15+
insert_result.rowcount,
16+
type(insert_result)
17+
)
18+
19+
select_result = await db.select(Test.__table__).where(Test.id == 1).mapped_all()
20+
print('Select all', select_result)
21+
22+
update_result = await db.update(Test)\
23+
.where(Test.id == 1)\
24+
.values(name='test 2')\
25+
.returning(Test.__table__)\
26+
.mapped_one()
27+
print('Updated dict', dict(**update_result))
28+
29+
30+
if __name__ == '__main__':
31+
asyncio.run(test())
32+
33+
34+

sqlalchemy_tx_context/SQLAlchemyTransactionContext.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,5 @@ async def get_current_transaction(self) -> typing.ContextManager[AsyncSession]:
140140

141141
def _proxy_sqlalchemy_query_factory(self, method: typing.Any) -> typing.Any:
142142
def wrapper(*args, **kwargs):
143-
query = method(*args, **kwargs)
144-
return ProxyQuery(query, self)
143+
return ProxyQuery(method(*args, **kwargs), self)
145144
return wrapper

0 commit comments

Comments
 (0)