Reference¶
Configuration Matrix¶
Create Engine Support Functions by Database Type Confirmed by testing [SQLite, PostgreSQL, MSSQL] To Be Tested [MySQL, Oracle] and should be considered experimental.
| Option | SQLite | PostgreSQL | MySQL | Oracle | MSSQL |
|---|---|---|---|---|---|
| echo | Yes | Yes | Yes | Yes | Yes |
| future | Yes | Yes | Yes | Yes | Yes |
| pool_pre_ping | Yes | Yes | Yes | Yes | Yes |
| pool_size | No | Yes | Yes | Yes | Yes |
| max_overflow | No | Yes | Yes | Yes | Yes |
| pool_recycle | Yes | Yes | Yes | Yes | Yes |
| pool_timeout | No | Yes | Yes | Yes | Yes |
In addition to the dialect-specific options above, the following create_async_engine options are accepted regardless of dialect: connect_args, execution_options, isolation_level, query_cache_size, and hide_parameters. Use connect_args for driver-level options such as SSL/TLS settings or connect timeouts.
dsg_lib.async_database_functions.database_operations
¶
This module provides the DatabaseOperations class for performing CRUD operations on a database using SQLAlchemy's asynchronous session.
The DatabaseOperations class includes the following methods:
- `execute_one`: Executes a single non-read SQL query asynchronously.
- `execute_many`: Executes multiple non-read SQL queries asynchronously within a single transaction.
- 'read_one_record': Retrieves a single record from the database based on the provided query.
- `read_query`: Executes a fetch query on the database and returns a list of records that match the query.
- `read_multi_query`: Executes multiple fetch queries on the database and returns a dictionary of results for each query.
- `count_query`: Counts the number of records that match a given query.
- `paginate_query`: Fetches a page of records together with the total matching count.
- `get_column_details`: Gets the details of the columns in a table.
- `get_primary_keys`: Gets the primary keys of a table.
- `get_table_names`: Gets the names of all tables in the database.
Deprecated Methods:
- `create_one`: [Deprecated] Use `execute_one` with an INSERT query instead.
- `create_many`: [Deprecated] Use `execute_many` with INSERT queries instead.
- `update_one`: [Deprecated] Use `execute_one` with an UPDATE query instead.
- `delete_one`: [Deprecated] Use `execute_one` with a DELETE query instead.
- `delete_many`: [Deprecated] Use `execute_many` with DELETE queries instead.
Each method is designed to handle errors correctly and provide a simple interface for performing database operations.
This module also imports the necessary SQLAlchemy and loguru modules, and the AsyncDatabase class from the local async_database module.
Author: Mike Ryan Date: 2024/11/29 License: MIT
DatabaseErrorResult
¶
Bases: dict
A dict subclass returned by DatabaseOperations methods on failure, always
of the shape {"error": str, "details": str}.
It behaves exactly like the plain dict callers may already check for
(equality, in, .get(), isinstance(result, dict) all work unchanged), so
existing code is unaffected. It exists so new code can reliably tell an error
result apart from a real one with isinstance(result, DatabaseErrorResult)
instead of duck-typing on dict shape, which is ambiguous whenever the real
result is itself a dict (e.g. a multi-column row).
Source code in dsg_lib/async_database_functions/database_operations.py
66 67 68 69 70 71 72 73 74 75 76 77 | |
DatabaseOperations
¶
This class provides methods for performing CRUD operations on a database using SQLAlchemy's asynchronous session.
The methods include:
execute_one: Executes a single non-read SQL query asynchronously.execute_many: Executes multiple non-read SQL queries asynchronously within a single transaction.read_one_record: Retrieves a single record from the database based on the provided query.read_query: Executes a fetch query on the database and returns a list of records that match the query.read_multi_query: Executes multiple fetch queries on the database and returns a dictionary of results for each query.count_query: Counts the number of records that match a given query.paginate_query: Fetches a page of records together with the total matching count.get_column_details: Gets the details of the columns in a table.get_primary_keys: Gets the primary keys of a table.get_table_names: Gets the names of all tables in the database.
Deprecated Methods:
- create_one: [Deprecated] Use execute_one with an INSERT query instead.
- create_many: [Deprecated] Use execute_many with INSERT queries instead.
- update_one: [Deprecated] Use execute_one with an UPDATE query instead.
- delete_one: [Deprecated] Use execute_one with a DELETE query instead.
- delete_many: [Deprecated] Use execute_many with DELETE queries instead.
Examples:
from sqlalchemy import insert, select
from dsg_lib.async_database_functions import (
async_database,
base_schema,
database_config,
database_operations,
)
# Create a DBConfig instance
config = {
"database_uri": "sqlite+aiosqlite:///:memory:?cache=shared",
"echo": False,
"future": True,
"pool_recycle": 3600,
}
# create database configuration
db_config = database_config.DBConfig(config)
# Create an AsyncDatabase instance
async_db = async_database.AsyncDatabase(db_config)
# Create a DatabaseOperations instance
db_ops = database_operations.DatabaseOperations(async_db)
# create one record
query = insert(User).values(name='John Doe')
result = await db_ops.execute_one(query)
# read one record
query = select(User).where(User.name == 'John Doe')
record = await db_ops.read_query(query)
Source code in dsg_lib/async_database_functions/database_operations.py
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 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 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 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 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 916 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 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 | |
__init__(async_db)
¶
Initializes a new instance of the DatabaseOperations class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
async_db
|
AsyncDatabase
|
An instance of the AsyncDatabase class |
required |
See the class docstring above for a complete setup example.
Source code in dsg_lib/async_database_functions/database_operations.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
count_query(query)
async
¶
Executes a count query on the database and returns the number of records that match the query.
This asynchronous method accepts a SQLAlchemy Select query object and
returns the count of records that match the query. This is particularly
useful for getting the total number of records that satisfy certain
conditions without actually fetching the records themselves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
Select
|
A SQLAlchemy |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
The number of records that match the query. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the execution of the query. |
Example
count = await db_ops.count_query(select(User).where(User.age > 30))
Source code in dsg_lib/async_database_functions/database_operations.py
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 | |
create_many(records)
async
¶
This method is deprecated. Use execute_many with INSERT queries instead.
Adds multiple records to the database.
This asynchronous method accepts a list of record objects and adds them to the database. If the operation is successful, it returns the added records. This method is useful for bulk inserting multiple rows into a database table efficiently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
list[Base]
|
A list of instances of the SQLAlchemy |
required |
Returns:
| Type | Description |
|---|---|
|
list[Base]: A list of instances of the records that were added to |
|
|
the database. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the database operation. |
Example
records = await db_ops.create_many([User(name='John Doe'), User(name='Jane Doe')])
Source code in dsg_lib/async_database_functions/database_operations.py
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 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 | |
create_one(record)
async
¶
This method is deprecated. Use execute_one with an INSERT query instead.
Adds a single record to the database.
This asynchronous method accepts a record object and adds it to the database. If the operation is successful, it returns the added record. The method is useful for inserting a new row into a database table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
Base
|
An instance of the SQLAlchemy declarative base class |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Base |
The instance of the record that was added to the database. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the database operation. |
Example
record = await db_ops.create_one(User(name='John Doe'))
Source code in dsg_lib/async_database_functions/database_operations.py
826 827 828 829 830 831 832 833 834 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 | |
delete_many(table, id_column_name='pkid', id_values=None)
async
¶
This method is deprecated. Use execute_many with a DELETE query instead.
Deletes multiple records from the specified table in the database.
This method takes a table, an optional id column name, and a list of id values. It deletes the records in the table where the id column matches any of the id values in the list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
Type[DeclarativeMeta]
|
The table from which to delete records. |
required |
id_column_name
|
str
|
The name of the id column in the table. Defaults to "pkid". |
'pkid'
|
id_values
|
List[int]
|
A list of id values for the records to delete. Defaults to []. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of records deleted from the table. |
Example
deleted_count = await db_ops.delete_many(User, 'id', [1, 2, 3])
Source code in dsg_lib/async_database_functions/database_operations.py
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 | |
delete_one(table, record_id)
async
¶
This method is deprecated. Use execute_one with a DELETE query instead.
Deletes a single record from the database based on the provided table and record ID.
This asynchronous method accepts a SQLAlchemy Table object and a
record ID. It attempts to delete the record with the given ID from the
specified table. If the record is successfully deleted, it returns a
success message. If no record with the given ID is found, it returns an
error message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
Table
|
An instance of the SQLAlchemy |
required |
deleted. record_id
|
str
|
The ID of the record to be deleted. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing a success message if the record was |
|
|
deleted successfully, or an error message if the record was not |
||
|
found or an exception occurred. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the delete operation. |
Example
result = await db_ops.delete_one(User, 1)
Source code in dsg_lib/async_database_functions/database_operations.py
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 | |
execute_many(queries, return_results=False)
async
¶
Executes multiple SQL statements asynchronously within a single transaction.
Supports a mix of SELECT and DML statements.
When return_results=True, returns a list of per-statement results in the order provided.
Each item is either:
- For SELECT: a list of records.
- For DML: a dict containing rowcount, inserted_primary_key (if available),
and any returned rows (when using RETURNING).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queries
|
List[Tuple[ClauseElement, Optional[Dict[str, Any]]]]
|
A list of tuples, each containing
a query and an optional dictionary of parameter values. Each tuple should be of the form
|
required |
Returns:
| Type | Description |
|---|---|
Union[str, List[Any], Dict[str, str]]
|
|
Union[str, List[Any], Dict[str, str]]
|
|
Union[str, List[Any], Dict[str, str]]
|
|
Example
from sqlalchemy import insert
queries = [
(insert(User), {'name': 'User1'}),
(insert(User), {'name': 'User2'}),
(insert(User), {'name': 'User3'}),
]
result = await db_ops.execute_many(queries)
Source code in dsg_lib/async_database_functions/database_operations.py
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 | |
execute_one(query, values=None, return_metadata=False)
async
¶
Executes a single SQL statement asynchronously and returns a meaningful result.
Supports both read (SELECT) and write (INSERT/UPDATE/DELETE) statements.
- For SELECT, returns the fetched records (list of scalars, dicts, or ORM objects).
- For INSERT/UPDATE/DELETE, returns a dict with metadata including rowcount,
inserted_primary_key (if available), and any returned rows when the statement
includes RETURNING.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
ClauseElement
|
An SQLAlchemy query object representing the SQL statement to execute. |
required |
values
|
Optional[Dict[str, Any]]
|
A dictionary of parameter values to bind to the query. Defaults to None. |
None
|
return_metadata
|
bool
|
When True, returns metadata for DML statements. When False (default), returns "complete" for DML statements to preserve legacy behavior. Returns: - For SELECT: List[Any] of records. - For DML (INSERT/UPDATE/DELETE) when return_metadata=True: Dict with keys: { "rowcount": int | None, "inserted_primary_key": List[Any] | None, "rows": List[Any] (if statement returns rows) } - For DML when return_metadata=False: the string "complete". - On error: Dict[str, str] from handle_exceptions. |
False
|
Example
from sqlalchemy import insert
query = insert(User).values(name='John Doe')
result = await db_ops.execute_one(query)
Source code in dsg_lib/async_database_functions/database_operations.py
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 | |
get_columns_details(table)
async
¶
Retrieves the details of the columns of a given table.
This asynchronous method accepts a table object and returns a dictionary. Each key in the dictionary is a column name from the table, and the corresponding value is another dictionary containing details about that column, such as type, if it's nullable, if it's a primary key, if it's unique, its autoincrement status, and its default value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
Table
|
An instance of the SQLAlchemy Table class |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary where each key is a column name, and each value |
|
|
is a dictionary with the column's details. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the database operation. |
Example
columns = await db_ops.get_columns_details(User)
Source code in dsg_lib/async_database_functions/database_operations.py
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 | |
get_primary_keys(table)
async
¶
Retrieves the primary keys of a given table.
This asynchronous method accepts a table object and returns a list containing the names of its primary keys. It is useful for understanding the structure of the table and for operations that require knowledge of the primary keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
Table
|
An instance of the SQLAlchemy Table class |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list containing the names of the primary keys of the table. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the database operation. |
Example
primary_keys = await db_ops.get_primary_keys(User)
Source code in dsg_lib/async_database_functions/database_operations.py
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 | |
get_table_names()
async
¶
Retrieves the names of all tables in the database.
This asynchronous method returns a list containing the names of all tables in the database. It is useful for database introspection, allowing the user to know which tables are available in the current database context.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list containing the names of all tables in the database. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the database operation. |
Example
table_names = await db_ops.get_table_names()
Source code in dsg_lib/async_database_functions/database_operations.py
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 | |
paginate_query(query, page=1, page_size=100)
async
¶
Executes a query with page-based pagination, returning the requested page of records together with the total matching record count.
This combines what would otherwise be a separate count_query call and
a read_query call (each opening their own session) into one method
that counts and fetches the page within a single session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
Select
|
A SQLAlchemy |
required |
page
|
int
|
The 1-indexed page number to fetch. Defaults to 1. |
1
|
page_size
|
int
|
The number of records per page. Defaults to 100. |
100
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Union[Dict[str, Any], DatabaseErrorResult]
|
`{"items": List[Any], "total": int, "page": int, |
Union[Dict[str, Any], DatabaseErrorResult]
|
"page_size": int, "pages": int} |
|
Union[Dict[str, Any], DatabaseErrorResult]
|
of records (scalars, dicts, or ORM objects, as in |
|
Union[Dict[str, Any], DatabaseErrorResult]
|
|
|
DatabaseErrorResult |
Union[Dict[str, Any], DatabaseErrorResult]
|
If |
Union[Dict[str, Any], DatabaseErrorResult]
|
occurs during the query. |
Example
result = await db_ops.paginate_query(select(User).order_by(User.name), page=2, page_size=25)
# result["items"], result["total"], result["pages"]
Source code in dsg_lib/async_database_functions/database_operations.py
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 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 | |
read_multi_query(queries)
async
¶
Executes multiple fetch queries asynchronously and returns a dictionary of results for each query.
This asynchronous method accepts a dictionary where each key is a query name (str)
and each value is a SQLAlchemy Select query object. It executes each query within a single
database session and collects the results. The results are returned as a dictionary mapping
each query name to a list of records that match that query.
The function automatically determines the structure of each result set: - If the query returns a single column, the result will be a list of scalar values. - If the query returns multiple columns, the result will be a list of dictionaries mapping column names to values. - If the result row is an ORM object, it will be returned as-is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queries
|
Dict[str, Select]
|
A dictionary mapping query names to SQLAlchemy |
required |
Returns:
| Type | Description |
|---|---|
|
Dict[str, List[Any]]: A dictionary where each key is a query name and each value is a list of records |
|
|
(scalars, dictionaries, or ORM objects) that match the corresponding query. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the execution of any query, the function logs the error and |
Example
from sqlalchemy import select
queries = {
"adults": select(User).where(User.age >= 18),
"minors": select(User).where(User.age < 18),
}
results = await db_ops.read_multi_query(queries)
# results["adults"] and results["minors"] will contain lists of records
Source code in dsg_lib/async_database_functions/database_operations.py
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 | |
read_one_record(query)
async
¶
Retrieves a single record from the database based on the provided query.
This asynchronous method accepts a SQL query object and returns the first record that matches the query. If no record matches the query, it returns None. This method is useful for fetching specific data when the expected result is a single record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
Select
|
An instance of the SQLAlchemy Select class, |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Result |
The first record that matches the query or None if no record matches. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the database operation. |
Example
record = await db_ops.read_one_record(select(User).where(User.name == 'John Doe'))
Source code in dsg_lib/async_database_functions/database_operations.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 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 613 614 615 616 | |
update_one(table, record_id, new_values)
async
¶
This method is deprecated. Use execute_one with an UPDATE query instead.
Updates a single record in the database identified by its ID.
This asynchronous method takes a SQLAlchemy Table object, a record ID,
and a dictionary of new values to update the record. It updates the
specified record in the given table with the new values. The method does
not allow updating certain fields, such as 'id' or 'date_created'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
Table
|
The SQLAlchemy |
required |
in the database. record_id
|
str
|
The ID of the record to be |
required |
updated. new_values
|
dict
|
A dictionary containing the fields to |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Base |
The updated record if successful; otherwise, an error |
|
|
dictionary. |
Raises:
| Type | Description |
|---|---|
Exception
|
If any error occurs during the update operation. |
Example
record = await db_ops.update_one(User, 1, {'name': 'John Smith'})
Source code in dsg_lib/async_database_functions/database_operations.py
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 | |
handle_exceptions(ex)
¶
Handles exceptions for database operations.
This function checks the type of the exception, logs an appropriate error
message, and returns a DatabaseErrorResult containing the error details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ex
|
Exception
|
The exception to handle. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
DatabaseErrorResult |
DatabaseErrorResult
|
A dict-like object with two keys: 'error' and 'details'. |
Example:
try:
await db_ops.read_query(select(User))
except Exception as ex:
error_details = handle_exceptions(ex)
Source code in dsg_lib/async_database_functions/database_operations.py
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 | |