FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
databases/databases/core.py at master · python-study-cxb/databases · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
python-study-cxb
/
databases
Public
forked from
encode/databases
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
databases
/
databases
/
core.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
537 lines (441 loc) · 17.4 KB
Breadcrumbs
databases
/
databases
/
core.py
Copy path
File metadata and controls
537 lines (441 loc) · 17.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import
asyncio
import
contextlib
import
functools
import
logging
import
typing
from
contextvars
import
ContextVar
from
types
import
TracebackType
from
urllib
.
parse
import
SplitResult
,
parse_qsl
,
unquote
,
urlsplit
from
sqlalchemy
import
text
from
sqlalchemy
.
sql
import
ClauseElement
from
databases
.
importer
import
import_from_string
from
databases
.
interfaces
import
DatabaseBackend
,
Record
try
:
# pragma: no cover
import
click
# Extra log info for optional coloured terminal outputs.
LOG_EXTRA
=
{
"color_message"
:
"Query: "
+
click
.
style
(
"%s"
,
bold
=
True
)
+
" Args: %s"
}
CONNECT_EXTRA
=
{
"color_message"
:
"Connected to database "
+
click
.
style
(
"%s"
,
bold
=
True
)
}
DISCONNECT_EXTRA
=
{
"color_message"
:
"Disconnected from database "
+
click
.
style
(
"%s"
,
bold
=
True
)
}
except
ImportError
:
# pragma: no cover
LOG_EXTRA
=
{}
CONNECT_EXTRA
=
{}
DISCONNECT_EXTRA
=
{}
logger
=
logging
.
getLogger
(
"databases"
)
class
Database
:
SUPPORTED_BACKENDS
=
{
"postgresql"
:
"databases.backends.postgres:PostgresBackend"
,
"postgresql+aiopg"
:
"databases.backends.aiopg:AiopgBackend"
,
"postgres"
:
"databases.backends.postgres:PostgresBackend"
,
"mysql"
:
"databases.backends.mysql:MySQLBackend"
,
"mysql+asyncmy"
:
"databases.backends.asyncmy:AsyncMyBackend"
,
"sqlite"
:
"databases.backends.sqlite:SQLiteBackend"
,
}
def
__init__
(
self
,
url
:
typing
.
Union
[
str
,
"DatabaseURL"
],
*
,
force_rollback
:
bool
=
False
,
**
options
:
typing
.
Any
,
):
self
.
url
=
DatabaseURL
(
url
)
self
.
options
=
options
self
.
is_connected
=
False
self
.
_force_rollback
=
force_rollback
backend_str
=
self
.
_get_backend
()
backend_cls
=
import_from_string
(
backend_str
)
assert
issubclass
(
backend_cls
,
DatabaseBackend
)
self
.
_backend
=
backend_cls
(
self
.
url
,
**
self
.
options
)
# Connections are stored as task-local state.
self
.
_connection_context
=
ContextVar
(
"connection_context"
)
# type: ContextVar
# When `force_rollback=True` is used, we use a single global
# connection, within a transaction that always rolls back.
self
.
_global_connection
=
None
# type: typing.Optional[Connection]
self
.
_global_transaction
=
None
# type: typing.Optional[Transaction]
async
def
connect
(
self
)
->
None
:
"""
Establish the connection pool.
"""
if
self
.
is_connected
:
logger
.
debug
(
"Already connected, skipping connection"
)
return
None
await
self
.
_backend
.
connect
()
logger
.
info
(
"Connected to database %s"
,
self
.
url
.
obscure_password
,
extra
=
CONNECT_EXTRA
)
self
.
is_connected
=
True
if
self
.
_force_rollback
:
assert
self
.
_global_connection
is
None
assert
self
.
_global_transaction
is
None
self
.
_global_connection
=
Connection
(
self
.
_backend
)
self
.
_global_transaction
=
self
.
_global_connection
.
transaction
(
force_rollback
=
True
)
await
self
.
_global_transaction
.
__aenter__
()
async
def
disconnect
(
self
)
->
None
:
"""
Close all connections in the connection pool.
"""
if
not
self
.
is_connected
:
logger
.
debug
(
"Already disconnected, skipping disconnection"
)
return
None
if
self
.
_force_rollback
:
assert
self
.
_global_connection
is
not
None
assert
self
.
_global_transaction
is
not
None
await
self
.
_global_transaction
.
__aexit__
()
self
.
_global_transaction
=
None
self
.
_global_connection
=
None
else
:
self
.
_connection_context
=
ContextVar
(
"connection_context"
)
await
self
.
_backend
.
disconnect
()
logger
.
info
(
"Disconnected from database %s"
,
self
.
url
.
obscure_password
,
extra
=
DISCONNECT_EXTRA
,
)
self
.
is_connected
=
False
async
def
__aenter__
(
self
)
->
"Database"
:
await
self
.
connect
()
return
self
async
def
__aexit__
(
self
,
exc_type
:
typing
.
Type
[
BaseException
]
=
None
,
exc_value
:
BaseException
=
None
,
traceback
:
TracebackType
=
None
,
)
->
None
:
await
self
.
disconnect
()
async
def
fetch_all
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
typing
.
List
[
Record
]:
async
with
self
.
connection
()
as
connection
:
return
await
connection
.
fetch_all
(
query
,
values
)
async
def
fetch_one
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
typing
.
Optional
[
Record
]:
async
with
self
.
connection
()
as
connection
:
return
await
connection
.
fetch_one
(
query
,
values
)
async
def
fetch_val
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
,
column
:
typing
.
Any
=
0
,
)
->
typing
.
Any
:
async
with
self
.
connection
()
as
connection
:
return
await
connection
.
fetch_val
(
query
,
values
,
column
=
column
)
async
def
execute
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
typing
.
Any
:
async
with
self
.
connection
()
as
connection
:
return
await
connection
.
execute
(
query
,
values
)
async
def
execute_many
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
list
)
->
None
:
async
with
self
.
connection
()
as
connection
:
return
await
connection
.
execute_many
(
query
,
values
)
async
def
iterate
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
typing
.
AsyncGenerator
[
typing
.
Mapping
,
None
]:
async
with
self
.
connection
()
as
connection
:
async
for
record
in
connection
.
iterate
(
query
,
values
):
yield
record
def
connection
(
self
)
->
"Connection"
:
if
self
.
_global_connection
is
not
None
:
return
self
.
_global_connection
try
:
return
self
.
_connection_context
.
get
()
except
LookupError
:
connection
=
Connection
(
self
.
_backend
)
self
.
_connection_context
.
set
(
connection
)
return
connection
def
transaction
(
self
,
*
,
force_rollback
:
bool
=
False
,
**
kwargs
:
typing
.
Any
)
->
"Transaction"
:
return
Transaction
(
self
.
connection
,
force_rollback
=
force_rollback
,
**
kwargs
)
@
contextlib
.
contextmanager
def
force_rollback
(
self
)
->
typing
.
Iterator
[
None
]:
initial
=
self
.
_force_rollback
self
.
_force_rollback
=
True
try
:
yield
finally
:
self
.
_force_rollback
=
initial
def
_get_backend
(
self
)
->
str
:
return
self
.
SUPPORTED_BACKENDS
.
get
(
self
.
url
.
scheme
,
self
.
SUPPORTED_BACKENDS
[
self
.
url
.
dialect
]
)
class
Connection
:
def
__init__
(
self
,
backend
:
DatabaseBackend
)
->
None
:
self
.
_backend
=
backend
self
.
_connection_lock
=
asyncio
.
Lock
()
self
.
_connection
=
self
.
_backend
.
connection
()
self
.
_connection_counter
=
0
self
.
_transaction_lock
=
asyncio
.
Lock
()
self
.
_transaction_stack
=
[]
# type: typing.List[Transaction]
self
.
_query_lock
=
asyncio
.
Lock
()
async
def
__aenter__
(
self
)
->
"Connection"
:
async
with
self
.
_connection_lock
:
self
.
_connection_counter
+=
1
try
:
if
self
.
_connection_counter
==
1
:
await
self
.
_connection
.
acquire
()
except
BaseException
as
e
:
self
.
_connection_counter
-=
1
raise
e
return
self
async
def
__aexit__
(
self
,
exc_type
:
typing
.
Type
[
BaseException
]
=
None
,
exc_value
:
BaseException
=
None
,
traceback
:
TracebackType
=
None
,
)
->
None
:
async
with
self
.
_connection_lock
:
assert
self
.
_connection
is
not
None
self
.
_connection_counter
-=
1
if
self
.
_connection_counter
==
0
:
await
self
.
_connection
.
release
()
async
def
fetch_all
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
typing
.
List
[
Record
]:
built_query
=
self
.
_build_query
(
query
,
values
)
async
with
self
.
_query_lock
:
return
await
self
.
_connection
.
fetch_all
(
built_query
)
async
def
fetch_one
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
typing
.
Optional
[
Record
]:
built_query
=
self
.
_build_query
(
query
,
values
)
async
with
self
.
_query_lock
:
return
await
self
.
_connection
.
fetch_one
(
built_query
)
async
def
fetch_val
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
,
column
:
typing
.
Any
=
0
,
)
->
typing
.
Any
:
built_query
=
self
.
_build_query
(
query
,
values
)
async
with
self
.
_query_lock
:
return
await
self
.
_connection
.
fetch_val
(
built_query
,
column
)
async
def
execute
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
typing
.
Any
:
built_query
=
self
.
_build_query
(
query
,
values
)
async
with
self
.
_query_lock
:
return
await
self
.
_connection
.
execute
(
built_query
)
async
def
execute_many
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
list
)
->
None
:
queries
=
[
self
.
_build_query
(
query
,
values_set
)
for
values_set
in
values
]
async
with
self
.
_query_lock
:
await
self
.
_connection
.
execute_many
(
queries
)
async
def
iterate
(
self
,
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
typing
.
AsyncGenerator
[
typing
.
Any
,
None
]:
built_query
=
self
.
_build_query
(
query
,
values
)
async
with
self
.
transaction
():
async
with
self
.
_query_lock
:
async
for
record
in
self
.
_connection
.
iterate
(
built_query
):
yield
record
def
transaction
(
self
,
*
,
force_rollback
:
bool
=
False
,
**
kwargs
:
typing
.
Any
)
->
"Transaction"
:
def
connection_callable
()
->
Connection
:
return
self
return
Transaction
(
connection_callable
,
force_rollback
,
**
kwargs
)
@
property
def
raw_connection
(
self
)
->
typing
.
Any
:
return
self
.
_connection
.
raw_connection
@
staticmethod
def
_build_query
(
query
:
typing
.
Union
[
ClauseElement
,
str
],
values
:
dict
=
None
)
->
ClauseElement
:
if
isinstance
(
query
,
str
):
query
=
text
(
query
)
return
query
.
bindparams
(
**
values
)
if
values
is
not
None
else
query
elif
values
:
return
query
.
values
(
**
values
)
return
query
_CallableType
=
typing
.
TypeVar
(
"_CallableType"
,
bound
=
typing
.
Callable
)
class
Transaction
:
def
__init__
(
self
,
connection_callable
:
typing
.
Callable
[[],
Connection
],
force_rollback
:
bool
,
**
kwargs
:
typing
.
Any
,
)
->
None
:
self
.
_connection_callable
=
connection_callable
self
.
_force_rollback
=
force_rollback
self
.
_extra_options
=
kwargs
async
def
__aenter__
(
self
)
->
"Transaction"
:
"""
Called when entering `async with database.transaction()`
"""
await
self
.
start
()
return
self
async
def
__aexit__
(
self
,
exc_type
:
typing
.
Type
[
BaseException
]
=
None
,
exc_value
:
BaseException
=
None
,
traceback
:
TracebackType
=
None
,
)
->
None
:
"""
Called when exiting `async with database.transaction()`
"""
if
exc_type
is
not
None
or
self
.
_force_rollback
:
await
self
.
rollback
()
else
:
await
self
.
commit
()
def
__await__
(
self
)
->
typing
.
Generator
[
None
,
None
,
"Transaction"
]:
"""
Called if using the low-level `transaction = await database.transaction()`
"""
return
self
.
start
().
__await__
()
def
__call__
(
self
,
func
:
_CallableType
)
->
_CallableType
:
"""
Called if using `@database.transaction()` as a decorator.
"""
@
functools
.
wraps
(
func
)
async
def
wrapper
(
*
args
:
typing
.
Any
,
**
kwargs
:
typing
.
Any
)
->
typing
.
Any
:
async
with
self
:
return
await
func
(
*
args
,
**
kwargs
)
return
wrapper
# type: ignore
async
def
start
(
self
)
->
"Transaction"
:
self
.
_connection
=
self
.
_connection_callable
()
self
.
_transaction
=
self
.
_connection
.
_connection
.
transaction
()
async
with
self
.
_connection
.
_transaction_lock
:
is_root
=
not
self
.
_connection
.
_transaction_stack
await
self
.
_connection
.
__aenter__
()
await
self
.
_transaction
.
start
(
is_root
=
is_root
,
extra_options
=
self
.
_extra_options
)
self
.
_connection
.
_transaction_stack
.
append
(
self
)
return
self
async
def
commit
(
self
)
->
None
:
async
with
self
.
_connection
.
_transaction_lock
:
assert
self
.
_connection
.
_transaction_stack
[
-
1
]
is
self
self
.
_connection
.
_transaction_stack
.
pop
()
await
self
.
_transaction
.
commit
()
await
self
.
_connection
.
__aexit__
()
async
def
rollback
(
self
)
->
None
:
async
with
self
.
_connection
.
_transaction_lock
:
assert
self
.
_connection
.
_transaction_stack
[
-
1
]
is
self
self
.
_connection
.
_transaction_stack
.
pop
()
await
self
.
_transaction
.
rollback
()
await
self
.
_connection
.
__aexit__
()
class
_EmptyNetloc
(
str
):
def
__bool__
(
self
)
->
bool
:
return
True
class
DatabaseURL
:
def
__init__
(
self
,
url
:
typing
.
Union
[
str
,
"DatabaseURL"
]):
if
isinstance
(
url
,
DatabaseURL
):
self
.
_url
:
str
=
url
.
_url
elif
isinstance
(
url
,
str
):
self
.
_url
=
url
else
:
raise
TypeError
(
f"Invalid type for DatabaseURL. Expected str or DatabaseURL, got
{
type
(
url
)
}
"
)
@
property
def
components
(
self
)
->
SplitResult
:
if
not
hasattr
(
self
,
"_components"
):
self
.
_components
=
urlsplit
(
self
.
_url
)
return
self
.
_components
@
property
def
scheme
(
self
)
->
str
:
return
self
.
components
.
scheme
@
property
def
dialect
(
self
)
->
str
:
return
self
.
components
.
scheme
.
split
(
"+"
)[
0
]
@
property
def
driver
(
self
)
->
str
:
if
"+"
not
in
self
.
components
.
scheme
:
return
""
return
self
.
components
.
scheme
.
split
(
"+"
,
1
)[
1
]
@
property
def
userinfo
(
self
)
->
typing
.
Optional
[
bytes
]:
if
self
.
components
.
username
:
info
=
self
.
components
.
username
if
self
.
components
.
password
:
info
+=
":"
+
self
.
components
.
password
return
info
.
encode
(
"utf-8"
)
return
None
@
property
def
username
(
self
)
->
typing
.
Optional
[
str
]:
if
self
.
components
.
username
is
None
:
return
None
return
unquote
(
self
.
components
.
username
)
@
property
def
password
(
self
)
->
typing
.
Optional
[
str
]:
if
self
.
components
.
password
is
None
:
return
None
return
unquote
(
self
.
components
.
password
)
@
property
def
hostname
(
self
)
->
typing
.
Optional
[
str
]:
return
(
self
.
components
.
hostname
or
self
.
options
.
get
(
"host"
)
or
self
.
options
.
get
(
"unix_sock"
)
)
@
property
def
port
(
self
)
->
typing
.
Optional
[
int
]:
return
self
.
components
.
port
@
property
def
netloc
(
self
)
->
typing
.
Optional
[
str
]:
return
self
.
components
.
netloc
@
property
def
database
(
self
)
->
str
:
path
=
self
.
components
.
path
if
path
.
startswith
(
"/"
):
path
=
path
[
1
:]
return
unquote
(
path
)
@
property
def
options
(
self
)
->
dict
:
if
not
hasattr
(
self
,
"_options"
):
self
.
_options
=
dict
(
parse_qsl
(
self
.
components
.
query
))
return
self
.
_options
def
replace
(
self
,
**
kwargs
:
typing
.
Any
)
->
"DatabaseURL"
:
if
(
"username"
in
kwargs
or
"password"
in
kwargs
or
"hostname"
in
kwargs
or
"port"
in
kwargs
):
hostname
=
kwargs
.
pop
(
"hostname"
,
self
.
hostname
)
port
=
kwargs
.
pop
(
"port"
,
self
.
port
)
username
=
kwargs
.
pop
(
"username"
,
self
.
components
.
username
)
password
=
kwargs
.
pop
(
"password"
,
self
.
components
.
password
)
netloc
=
hostname
if
port
is
not
None
:
netloc
+=
f":
{
port
}
"
if
username
is
not
None
:
userpass
=
username
if
password
is
not
None
:
userpass
+=
f":
{
password
}
"
netloc
=
f"
{
userpass
}
@
{
netloc
}
"
kwargs
[
"netloc"
]
=
netloc
if
"database"
in
kwargs
:
kwargs
[
"path"
]
=
"/"
+
kwargs
.
pop
(
"database"
)
if
"dialect"
in
kwargs
or
"driver"
in
kwargs
:
dialect
=
kwargs
.
pop
(
"dialect"
,
self
.
dialect
)
driver
=
kwargs
.
pop
(
"driver"
,
self
.
driver
)
kwargs
[
"scheme"
]
=
f"
{
dialect
}
+
{
driver
}
"
if
driver
else
dialect
if
not
kwargs
.
get
(
"netloc"
,
self
.
netloc
):
# Using an empty string that evaluates as True means we end up
# with URLs like `sqlite:///database` instead of `sqlite:/database`
kwargs
[
"netloc"
]
=
_EmptyNetloc
()
components
=
self
.
components
.
_replace
(
**
kwargs
)
return
self
.
__class__
(
components
.
geturl
())
@
property
def
obscure_password
(
self
)
->
str
:
if
self
.
password
:
return
self
.
replace
(
password
=
"********"
).
_url
return
self
.
_url
def
__str__
(
self
)
->
str
:
return
self
.
_url
def
__repr__
(
self
)
->
str
:
return
f"
{
self
.
__class__
.
__name__
}
(
{
repr
(
self
.
obscure_password
)
}
)"
def
__eq__
(
self
,
other
:
typing
.
Any
)
->
bool
:
return
str
(
self
)
==
str
(
other
)
Back
|
FazBrowse Home
|
New Git URL