Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.

Commit 101ab4f

Browse files
committed
Refactoring: using properties instead of methods
1 parent 555e4bf commit 101ab4f

File tree

6 files changed

+87
-91
lines changed

6 files changed

+87
-91
lines changed

databases/backends/mysql.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,6 @@ async def iterate(
149149
finally:
150150
await cursor.close()
151151

152-
async def raw_connection(self) -> aiomysql.connection.Connection:
153-
assert self._connection is not None, "Connection is not acquired"
154-
return self._connection
155-
156152
def transaction(self) -> TransactionBackend:
157153
return MySQLTransaction(self)
158154

@@ -176,6 +172,11 @@ def _compile(
176172
logger.debug("Query: %s\nArgs: %s", compiled.string, args)
177173
return compiled.string, args, CompilationContext(execution_context)
178174

175+
@property
176+
def raw_connection(self) -> aiomysql.connection.Connection:
177+
assert self._connection is not None, "Connection is not acquired"
178+
return self._connection
179+
179180

180181
class MySQLTransaction(TransactionBackend):
181182
def __init__(self, connection: MySQLConnection):

databases/backends/postgres.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,10 +150,6 @@ async def iterate(
150150
async for row in self._connection.cursor(query, *args):
151151
yield Record(row, result_columns, self._dialect)
152152

153-
async def raw_connection(self) -> asyncpg.connection.Connection:
154-
assert self._connection is not None, "Connection is not acquired"
155-
return self._connection
156-
157153
def transaction(self) -> TransactionBackend:
158154
return PostgresTransaction(connection=self)
159155

@@ -175,6 +171,11 @@ def _compile(self, query: ClauseElement) -> typing.Tuple[str, list, tuple]:
175171
logger.debug("Query: %s\nArgs: %s", compiled_query, args)
176172
return compiled_query, args, compiled._result_columns
177173

174+
@property
175+
def raw_connection(self) -> asyncpg.connection.Connection:
176+
assert self._connection is not None, "Connection is not acquired"
177+
return self._connection
178+
178179

179180
class PostgresTransaction(TransactionBackend):
180181
def __init__(self, connection: PostgresConnection):

databases/backends/sqlite.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,6 @@ async def execute_many(self, query: ClauseElement, values: list) -> None:
116116
for value in values:
117117
await self.execute(query, value)
118118

119-
async def raw_connection(self) -> aiosqlite.core.Connection:
120-
assert self._connection is not None, "Connection is not acquired"
121-
return self._connection
122-
123119
async def iterate(
124120
self, query: ClauseElement
125121
) -> typing.AsyncGenerator[typing.Any, None]:
@@ -157,6 +153,11 @@ def _compile(
157153
logger.debug("Query: %s\nArgs: %s", compiled.string, args)
158154
return compiled.string, args, CompilationContext(execution_context)
159155

156+
@property
157+
def raw_connection(self) -> aiosqlite.core.Connection:
158+
assert self._connection is not None, "Connection is not acquired"
159+
return self._connection
160+
160161

161162
class SQLiteTransaction(TransactionBackend):
162163
def __init__(self, connection: SQLiteConnection):

databases/core.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,6 @@ async def iterate(
111111
async for record in connection.iterate(query):
112112
yield record
113113

114-
async def raw_connection(self) -> typing.Any:
115-
async with self.connection() as connection:
116-
return await connection.raw_connection()
117-
118114
def connection(self) -> "Connection":
119115
if self._global_connection is not None:
120116
return self._global_connection
@@ -172,9 +168,6 @@ async def execute(self, query: ClauseElement, values: dict = None) -> typing.Any
172168
async def execute_many(self, query: ClauseElement, values: list) -> None:
173169
await self._connection.execute_many(query, values)
174170

175-
async def raw_connection(self) -> typing.Any:
176-
return await self._connection.raw_connection()
177-
178171
async def iterate(
179172
self, query: ClauseElement
180173
) -> typing.AsyncGenerator[typing.Any, None]:
@@ -184,6 +177,10 @@ async def iterate(
184177
def transaction(self, *, force_rollback: bool = False) -> "Transaction":
185178
return Transaction(self, force_rollback)
186179

180+
@property
181+
def raw_connection(self) -> typing.Any:
182+
return self._connection.raw_connection
183+
187184

188185
class Transaction:
189186
def __init__(self, connection: Connection, force_rollback: bool) -> None:

databases/interfaces.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,11 @@ async def iterate(
4141
# https://github.com/python/mypy/issues/5385#issuecomment-407281656
4242
yield True # pragma: no cover
4343

44-
async def raw_connection(self) -> typing.Any:
44+
def transaction(self) -> "TransactionBackend":
4545
raise NotImplementedError() # pragma: no cover
4646

47-
def transaction(self) -> "TransactionBackend":
47+
@property
48+
def raw_connection(self) -> typing.Any:
4849
raise NotImplementedError() # pragma: no cover
4950

5051

tests/test_databases.py

Lines changed: 65 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -526,13 +526,7 @@ async def test_connection_context_with_raw_connection(database_url):
526526
async with database.connection() as connection_1:
527527
async with database.connection() as connection_2:
528528
assert connection_1 is connection_2
529-
530-
raw_connection_0 = await database.raw_connection()
531-
raw_connection_1 = await connection_1.raw_connection()
532-
raw_connection_2 = await connection_2.raw_connection()
533-
534-
assert raw_connection_0 is raw_connection_1 is raw_connection_2
535-
assert raw_connection_0 is connection_1._connection._connection
529+
assert connection_1.raw_connection is connection_2.raw_connection
536530

537531

538532
@pytest.mark.parametrize("database_url", DATABASE_URLS)
@@ -543,66 +537,67 @@ async def test_queries_with_expose_backend_connection(database_url):
543537
`fetch_one()` using the raw driver interface.
544538
"""
545539
async with Database(database_url) as database:
546-
async with database.transaction(force_rollback=True):
547-
# Get the raw connection
548-
con = await database.raw_connection()
549-
550-
# Insert query
551-
if str(database_url).startswith("mysql"):
552-
insert_query = "INSERT INTO notes (text, completed) VALUES (%s, %s)"
553-
else:
554-
insert_query = "INSERT INTO notes (text, completed) VALUES ($1, $2)"
555-
556-
# execute()
557-
values = ("example1", True)
558-
559-
if str(database_url).startswith("postgresql"):
560-
await con.execute(insert_query, *values)
561-
elif str(database_url).startswith("mysql"):
562-
cursor = await con.cursor()
563-
await cursor.execute(insert_query, values)
564-
elif str(database_url).startswith("sqlite"):
565-
await con.execute(insert_query, values)
566-
567-
# execute_many()
568-
values = [("example2", False), ("example3", True)]
569-
570-
if str(database_url).startswith("mysql"):
571-
cursor = await con.cursor()
572-
await cursor.executemany(insert_query, values)
573-
else:
574-
await con.executemany(insert_query, values)
575-
576-
# Select query
577-
select_query = "SELECT notes.id, notes.text, notes.completed FROM notes"
578-
579-
# fetch_all()
580-
if str(database_url).startswith("postgresql"):
581-
results = await con.fetch(select_query)
582-
elif str(database_url).startswith("mysql"):
583-
cursor = await con.cursor()
584-
await cursor.execute(select_query)
585-
results = await cursor.fetchall()
586-
elif str(database_url).startswith("sqlite"):
587-
results = await con.execute_fetchall(select_query)
588-
589-
assert len(results) == 3
590-
# Raw output for the raw request
591-
assert results[0][1] == "example1"
592-
assert results[0][2] == True
593-
assert results[1][1] == "example2"
594-
assert results[1][2] == False
595-
assert results[2][1] == "example3"
596-
assert results[2][2] == True
597-
598-
# fetch_one()
599-
if str(database_url).startswith("postgresql"):
600-
result = await con.fetchrow(select_query)
601-
else:
602-
cursor = await con.cursor()
603-
await cursor.execute(select_query)
604-
result = await cursor.fetchone()
605-
606-
# Raw output for the raw request
607-
assert result[1] == "example1"
608-
assert result[2] == True
540+
async with database.connection() as connection:
541+
async with database.transaction(force_rollback=True):
542+
# Get the raw connection
543+
raw_connection = connection.raw_connection
544+
545+
# Insert query
546+
if str(database_url).startswith("mysql"):
547+
insert_query = "INSERT INTO notes (text, completed) VALUES (%s, %s)"
548+
else:
549+
insert_query = "INSERT INTO notes (text, completed) VALUES ($1, $2)"
550+
551+
# execute()
552+
values = ("example1", True)
553+
554+
if str(database_url).startswith("postgresql"):
555+
await raw_connection.execute(insert_query, *values)
556+
elif str(database_url).startswith("mysql"):
557+
cursor = await raw_connection.cursor()
558+
await cursor.execute(insert_query, values)
559+
elif str(database_url).startswith("sqlite"):
560+
await raw_connection.execute(insert_query, values)
561+
562+
# execute_many()
563+
values = [("example2", False), ("example3", True)]
564+
565+
if str(database_url).startswith("mysql"):
566+
cursor = await raw_connection.cursor()
567+
await cursor.executemany(insert_query, values)
568+
else:
569+
await raw_connection.executemany(insert_query, values)
570+
571+
# Select query
572+
select_query = "SELECT notes.id, notes.text, notes.completed FROM notes"
573+
574+
# fetch_all()
575+
if str(database_url).startswith("postgresql"):
576+
results = await raw_connection.fetch(select_query)
577+
elif str(database_url).startswith("mysql"):
578+
cursor = await raw_connection.cursor()
579+
await cursor.execute(select_query)
580+
results = await cursor.fetchall()
581+
elif str(database_url).startswith("sqlite"):
582+
results = await raw_connection.execute_fetchall(select_query)
583+
584+
assert len(results) == 3
585+
# Raw output for the raw request
586+
assert results[0][1] == "example1"
587+
assert results[0][2] == True
588+
assert results[1][1] == "example2"
589+
assert results[1][2] == False
590+
assert results[2][1] == "example3"
591+
assert results[2][2] == True
592+
593+
# fetch_one()
594+
if str(database_url).startswith("postgresql"):
595+
result = await raw_connection.fetchrow(select_query)
596+
else:
597+
cursor = await raw_connection.cursor()
598+
await cursor.execute(select_query)
599+
result = await cursor.fetchone()
600+
601+
# Raw output for the raw request
602+
assert result[1] == "example1"
603+
assert result[2] == True

0 commit comments

Comments
 (0)