Database¶
Database is Saffier's database connection wrapper.
Most applications interact with it indirectly through a Registry, but the
class is still important because it defines connection lifecycle, transaction
management, and the SQLAlchemy async engine used by queries and schema helpers.
Typical usage¶
database = saffier.Database(
"postgresql+asyncpg://postgres:postgres@localhost:5432/app"
)
models = saffier.Registry(database=database)
What to know in practice¶
- prefer
saffier.Database, not thedatabasespackage object - registry lifecycle usually controls
connect()anddisconnect() - synchronous reflection paths use the wrapped sync engine derived from the async engine
saffier.Database
¶
Database(
url=None,
*,
force_rollback=None,
config=None,
full_isolation=None,
poll_interval=None,
**options,
)
An abstraction on the top of the EncodeORM databases.Database object.
This object allows to pass also a configuration dictionary in the format of
DATABASEZ_CONFIG = { "connection": { "credentials": { "scheme": 'sqlite', "postgres"... "host": ..., "port": ..., "user": ..., "password": ..., "database": ..., "options": { "driver": ... "ssl": ... } } } }
Source code in databasez/core/database.py
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 | |
_current_task
property
¶
_current_task
Return the currently running asyncio task.
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If no task is active. |
_connection
property
writable
¶
_connection
Return the connection bound to the current task, if any.
__copy__
¶
__copy__()
Create a shallow copy of the database (preserving backend state).
| RETURNS | DESCRIPTION |
|---|---|
Database
|
A new Database instance sharing the same backend.
TYPE:
|
Source code in databasez/core/database.py
329 330 331 332 333 334 335 | |
inc_refcount
async
¶
inc_refcount()
Internal method to bump the ref_count.
Return True if ref_count is 0, False otherwise.
Should not be used outside of tests. Use connect and hooks instead. Not multithreading safe!
Source code in databasez/core/database.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | |
decr_refcount
async
¶
decr_refcount()
Internal method to decrease the ref_count.
Return True if ref_count drops to 0, False otherwise.
Should not be used outside of tests. Use disconnect and hooks instead. Not multithreading safe!
Source code in databasez/core/database.py
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
connect_hook
async
¶
connect_hook()
Hook called before engine setup on first connect.
Override this in subclasses to perform custom initialisation logic,
such as creating test databases. Protected by the ref-counter so
it runs only on the first connect() call.
Source code in databasez/core/database.py
399 400 401 402 403 404 405 | |
connect
async
¶
connect()
Establish the connection pool.
If called from a different event loop than the one the database was originally connected on, a sub-database is transparently created for the current loop.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
TYPE:
|
Source code in databasez/core/database.py
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 | |
disconnect_hook
async
¶
disconnect_hook()
Hook called after engine teardown on last disconnect.
Override this in subclasses to perform custom cleanup logic.
Protected by the ref-counter so it runs only on the last
disconnect() call.
Source code in databasez/core/database.py
459 460 461 462 463 464 465 | |
disconnect
async
¶
disconnect(force=False, *, parent_database=None)
Close all connections in the connection pool.
| PARAMETER | DESCRIPTION |
|---|---|
force
|
If
TYPE:
|
parent_database
|
Injected by :func:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
TYPE:
|
Source code in databasez/core/database.py
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 | |
fetch_all
async
¶
fetch_all(query, values=None, timeout=None)
Execute query and return all result rows.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
SQL string or clause element.
TYPE:
|
values
|
Optional bind parameters.
TYPE:
|
timeout
|
Optional timeout in seconds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[Record]
|
list[interfaces.Record]: All result rows. |
Source code in databasez/core/database.py
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 | |
fetch_one
async
¶
fetch_one(query, values=None, pos=0, timeout=None)
Execute query and return a single row.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
SQL string or clause element.
TYPE:
|
values
|
Optional bind parameters.
TYPE:
|
pos
|
Row position (0-based,
TYPE:
|
timeout
|
Optional timeout in seconds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Record | None
|
interfaces.Record | None: The row, or |
Source code in databasez/core/database.py
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | |
fetch_val
async
¶
fetch_val(
query, values=None, column=0, pos=0, timeout=None
)
Execute query and return a single scalar value.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
SQL string or clause element.
TYPE:
|
values
|
Optional bind parameters.
TYPE:
|
column
|
Column index or name.
TYPE:
|
pos
|
Row position.
TYPE:
|
timeout
|
Optional timeout in seconds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
The scalar value, or
TYPE:
|
Source code in databasez/core/database.py
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | |
execute
async
¶
execute(query, values=None, timeout=None)
Execute a statement and return a concise result.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
SQL string or clause element.
TYPE:
|
values
|
Optional bind parameters.
TYPE:
|
timeout
|
Optional timeout in seconds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Record | int
|
interfaces.Record | int: Primary-key row / rowcount. |
Source code in databasez/core/database.py
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 | |
execute_many
async
¶
execute_many(query, values=None, timeout=None)
Execute a statement with multiple parameter sets.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
SQL string or clause element.
TYPE:
|
values
|
A sequence of parameter mappings.
TYPE:
|
timeout
|
Optional timeout in seconds.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Sequence[Record] | int
|
Sequence[interfaces.Record] | int: Primary-key rows / rowcount. |
Source code in databasez/core/database.py
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 | |
iterate
async
¶
iterate(query, values=None, chunk_size=None, timeout=None)
Execute query and yield rows one by one.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
SQL string or clause element.
TYPE:
|
values
|
Optional bind parameters.
TYPE:
|
chunk_size
|
Backend batch-size hint.
TYPE:
|
timeout
|
Per-row timeout in seconds.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
AsyncGenerator[Record, None]
|
interfaces.Record: Result rows. |
Source code in databasez/core/database.py
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 | |
batched_iterate
async
¶
batched_iterate(
query,
values=None,
batch_size=None,
batch_wrapper=tuple,
timeout=None,
)
Execute query and yield rows in batches.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
SQL string or clause element.
TYPE:
|
values
|
Optional bind parameters.
TYPE:
|
batch_size
|
Rows per batch.
TYPE:
|
batch_wrapper
|
Callable to transform each batch.
TYPE:
|
timeout
|
Per-batch timeout in seconds.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
BatchCallableResult
|
Batches of result rows.
TYPE::
|
Source code in databasez/core/database.py
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 | |
transaction
¶
transaction(*, force_rollback=False, **kwargs)
Create a new :class:Transaction on the current connection.
| PARAMETER | DESCRIPTION |
|---|---|
force_rollback
|
If
TYPE:
|
**kwargs
|
Extra options forwarded to the transaction backend.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Transaction
|
A new transaction instance.
TYPE:
|
Source code in databasez/core/database.py
707 708 709 710 711 712 713 714 715 716 717 | |
run_sync
async
¶
run_sync(fn, *args, timeout=None, **kwargs)
Run a synchronous callable on the current connection.
| PARAMETER | DESCRIPTION |
|---|---|
fn
|
A synchronous function.
TYPE:
|
*args
|
Positional arguments.
TYPE:
|
timeout
|
Optional timeout in seconds.
TYPE:
|
**kwargs
|
Keyword arguments.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Any
|
The return value of fn.
TYPE:
|
Source code in databasez/core/database.py
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | |
create_all
async
¶
create_all(meta, timeout=None, **kwargs)
Create all tables defined in meta.
| PARAMETER | DESCRIPTION |
|---|---|
meta
|
A SQLAlchemy :class:
TYPE:
|
timeout
|
Optional timeout in seconds.
TYPE:
|
**kwargs
|
Extra arguments for
TYPE:
|
Source code in databasez/core/database.py
740 741 742 743 744 745 746 747 748 749 750 751 | |
drop_all
async
¶
drop_all(meta, timeout=None, **kwargs)
Drop all tables defined in meta.
| PARAMETER | DESCRIPTION |
|---|---|
meta
|
A SQLAlchemy :class:
TYPE:
|
timeout
|
Optional timeout in seconds.
TYPE:
|
**kwargs
|
Extra arguments for
TYPE:
|
Source code in databasez/core/database.py
753 754 755 756 757 758 759 760 761 762 | |
_non_global_connection
¶
_non_global_connection(timeout=None)
Return or create the per-task connection (non-global).
| RETURNS | DESCRIPTION |
|---|---|
Connection
|
The connection for the current task.
TYPE:
|
Source code in databasez/core/database.py
764 765 766 767 768 769 770 771 772 773 774 775 776 777 | |
connection
¶
connection(timeout=None)
Return a connection suitable for the current context.
In force-rollback mode the global connection is returned; otherwise a per-task connection is returned (created on demand).
| PARAMETER | DESCRIPTION |
|---|---|
timeout
|
Optional timeout for cross-loop proxying.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Connection
|
The active connection.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the database is not connected. |
Source code in databasez/core/database.py
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 | |
asgi
¶
asgi(
app: None, handle_lifespan: bool = False
) -> Callable[[ASGIApp], ASGIApp]
asgi(
app: ASGIApp, handle_lifespan: bool = False
) -> ASGIApp
asgi(app=None, handle_lifespan=False)
Return wrapper for asgi integration.
Source code in databasez/core/database.py
820 821 822 823 824 825 826 827 828 829 830 831 832 833 | |
get_backends
classmethod
¶
get_backends(
scheme="",
*,
overwrite_paths=("databasez.overwrites",),
database_name="Database",
connection_name="Connection",
transaction_name="Transaction",
database_class=None,
connection_class=None,
transaction_class=None,
)
Discover backend classes for the given scheme.
Searches overwrite_paths for modules that export Database,
Connection, and Transaction classes matching the scheme.
Falls back to the supplied defaults.
| PARAMETER | DESCRIPTION |
|---|---|
scheme
|
The dialect scheme (e.g.
TYPE:
|
overwrite_paths
|
Module paths searched for overwrite modules.
TYPE:
|
database_name
|
Attribute name for the database backend class.
TYPE:
|
connection_name
|
Attribute name for the connection backend class.
TYPE:
|
transaction_name
|
Attribute name for the transaction backend class.
TYPE:
|
database_class
|
Fallback database backend class.
TYPE:
|
connection_class
|
Fallback connection backend class.
TYPE:
|
transaction_class
|
Fallback transaction backend class.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If a discovered class does not subclass its expected abstract base. |
Source code in databasez/core/database.py
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 | |
apply_database_url_and_options
classmethod
¶
apply_database_url_and_options(
url,
*,
overwrite_paths=("databasez.overwrites",),
**options,
)
Build a backend instance and normalise URL + options.
Discovers the correct backend classes for the URL's scheme,
instantiates the database backend, and calls
:meth:~DatabaseBackend.extract_options to normalise the URL and
merge query-string options.
| PARAMETER | DESCRIPTION |
|---|---|
url
|
The original database URL.
TYPE:
|
overwrite_paths
|
Module paths searched for overwrite modules.
TYPE:
|
**options
|
Additional caller-supplied engine options.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If the resolved dialect is not async. |
Source code in databasez/core/database.py
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 | |