API Reference¶
azure_functions_db
¶
SqlAlchemySource(*, url, table=None, schema=None, query=None, cursor_column, pk_columns, where=None, parameters=None, strategy='cursor', operation_mode='upsert_only', engine_provider=None)
¶
SQLAlchemy-based source adapter for cursor-based change polling.
Implements the SourceAdapter protocol defined in
azure_functions_db.trigger.runner.
Parameters¶
url:
SQLAlchemy connection URL. Supports %VAR% env-var substitution.
table:
Table name to poll. Mutually exclusive with query.
schema:
Optional schema qualifier for table.
query:
Raw SQL query to poll. Mutually exclusive with table.
cursor_column:
Column used for cursor-based ordering.
pk_columns:
Primary-key column(s) for tie-breaking within the same cursor value.
where:
Optional extra SQL WHERE clause fragment (appended with AND).
parameters:
Optional bind parameters for where or query.
strategy:
Polling strategy. Only "cursor" is supported.
operation_mode:
Operation mode. Only "upsert_only" is supported.
Source code in src/azure_functions_db/adapter/sqlalchemy.py
fetch(cursor, batch_size)
¶
Fetch a batch of records newer than cursor.
Returns an empty sequence when no new records are available.
Source code in src/azure_functions_db/adapter/sqlalchemy.py
dispose()
¶
Dispose the underlying engine and release connection pool.
Source code in src/azure_functions_db/adapter/sqlalchemy.py
DbReader(*, url, table=None, schema=None, engine_provider=None)
¶
Imperative input binding for reading database rows.
Provides get() for single-row lookup by primary key and query()
for arbitrary SQL queries. Uses SQLAlchemy Core under the hood and
integrates with :class:EngineProvider for shared connection pooling.
Thread Safety¶
Instances are not safe to share across concurrent threads or
async invocations. Create a separate DbReader per function
invocation, or use a with block to scope the lifecycle.
Parameters¶
url:
SQLAlchemy connection URL. Supports %VAR% env-var substitution.
table:
Table name for get() operations. Optional if only query()
is used.
schema:
Optional schema qualifier for table.
engine_provider:
Optional shared :class:EngineProvider. When provided, the reader
uses a pooled engine instead of creating its own.
Source code in src/azure_functions_db/binding/reader.py
get(*, pk)
¶
Look up a single row by primary key.
Requires table to have been set in the constructor.
Parameters¶
pk: Mapping of primary-key column name to value. All keys must be actual primary key columns of the table.
Returns¶
dict or None
The matching row as a dict, or None if no row matches.
Raises¶
ConfigurationError If table was not set, or pk contains unknown columns. QueryError If more than one row matches the provided key.
Source code in src/azure_functions_db/binding/reader.py
query(sql, *, params=None)
¶
Execute a raw SQL query and return all matching rows.
Always use :name parameter placeholders and params instead of
string formatting to prevent SQL injection. True read-only
enforcement should be done at the database role/permission level.
Parameters¶
sql:
SQL query string. Use :name placeholders for parameters.
params:
Optional mapping of parameter names to values.
Returns¶
list[dict] List of rows, each as a dict. Empty list if no rows match.
Raises¶
QueryError If the query execution fails.
Source code in src/azure_functions_db/binding/reader.py
scalar(sql, *, params=None)
¶
Execute a SQL query and return a single scalar value.
Convenience wrapper around :meth:query for queries such as
SELECT COUNT(*) FROM ... or SELECT MAX(updated_at) FROM ....
Returns the first column of the first row, or None if no rows
match. Raises :class:QueryError if the query returns more than
one row.
Parameters¶
sql:
SQL query string. Use :name placeholders for parameters.
params:
Optional mapping of parameter names to values.
Returns¶
object or None
The single scalar value, or None if no rows match.
Raises¶
QueryError If the query execution fails or returns multiple rows.
Source code in src/azure_functions_db/binding/reader.py
one(sql, *, params=None)
¶
Execute a SQL query and return exactly one row.
Convenience wrapper around :meth:query for queries that must
return a single row.
Parameters¶
sql:
SQL query string. Use :name placeholders for parameters.
params:
Optional mapping of parameter names to values.
Returns¶
dict The single matching row as a dict.
Raises¶
QueryError If the query execution fails, returns zero rows, or returns more than one row.
Source code in src/azure_functions_db/binding/reader.py
one_or_none(sql, *, params=None)
¶
Execute a SQL query and return one row or None.
Convenience wrapper around :meth:query for queries that must
return zero or one row.
Parameters¶
sql:
SQL query string. Use :name placeholders for parameters.
params:
Optional mapping of parameter names to values.
Returns¶
dict or None
The single matching row as a dict, or None if no rows
match.
Raises¶
QueryError If the query execution fails or returns more than one row.
Source code in src/azure_functions_db/binding/reader.py
close()
¶
Release resources held by this reader.
If the reader owns its engine (no engine_provider was given),
the engine is disposed. If using a shared engine via
engine_provider, only the reader's internal state is reset.
Source code in src/azure_functions_db/binding/reader.py
DbWriter(*, url, table, schema=None, engine_provider=None)
¶
Imperative output binding for writing database rows.
Provides insert(), upsert(), update(), delete() for
single-row operations and insert_many() / upsert_many() for
batch operations. Uses SQLAlchemy Core under the hood.
Thread Safety¶
Instances are not safe to share across concurrent threads or
async invocations. Create a separate DbWriter per function
invocation, or use a with block to scope the lifecycle.
Source code in src/azure_functions_db/binding/writer.py
transaction()
¶
Group multiple write operations into a single SQL transaction.
Inside the with block, every call to insert, insert_many,
upsert, upsert_many, update, and delete executes on
the same connection and shares one transaction. The transaction is
committed on normal exit and rolled back if any exception leaves
the block.
Nested transaction() calls on the same writer are not supported
and raise :class:WriteError.
Example¶
with writer.transaction(): ... writer.insert(data={"id": 1, "status": "pending"}) ... writer.update(data={"status": "shipped"}, pk={"id": 1})
Raises¶
WriteError If a transaction is already active on this writer, if the connection cannot be acquired, or if commit fails. The original exception is preserved as the cause when applicable.
Source code in src/azure_functions_db/binding/writer.py
insert(*, data)
¶
Insert a single row.
Raises :class:WriteError on constraint violations or other
database errors.
Source code in src/azure_functions_db/binding/writer.py
insert_many(*, rows)
¶
Insert multiple rows in a single transaction (all-or-nothing).
Source code in src/azure_functions_db/binding/writer.py
upsert(*, data, conflict_columns)
¶
Insert or update a single row using dialect-specific upsert.
Supported dialects: PostgreSQL, SQLite, MySQL. Other dialects
raise :class:ConfigurationError.
Source code in src/azure_functions_db/binding/writer.py
upsert_many(*, rows, conflict_columns)
¶
Upsert multiple rows in a single transaction (all-or-nothing).
Source code in src/azure_functions_db/binding/writer.py
update(*, data, pk)
¶
Update a single row identified by primary key.
This is a no-op if no row matches the given pk (idempotent).
Source code in src/azure_functions_db/binding/writer.py
delete(*, pk)
¶
Delete a single row identified by primary key.
This is a no-op if no row matches the given pk (idempotent).
Source code in src/azure_functions_db/binding/writer.py
close()
¶
Tear down resources held by this writer.
If called while a transaction() with block is still active,
the transaction is rolled back, the connection is released, and a
sentinel is set so that any subsequent write call inside the same
with block raises :class:WriteError. The surrounding context
manager's __exit__ observes the teardown and skips its own
commit/rollback. Rollback failures are logged at WARNING and do
not prevent connection close or engine disposal.
.. warning::
Do not continue using the same writer inside that
transaction() block after calling close(). The writer
has been torn down and any further insert / upsert /
update / delete call will raise :class:WriteError.
If you need to keep writing, exit the with block first
and start a new transaction() on a fresh writer instance.
Source code in src/azure_functions_db/binding/writer.py
DbBindings
¶
Azure Functions-style decorator API for database integration.
Provides trigger, input, output, inject_reader,
and inject_writer decorator methods that wrap the imperative API
(PollTrigger, DbReader, DbWriter) in an Azure Functions-native
decorator experience.
Data injection (input / output):
input injects query results into handler parameters.
output injects a :class:DbOut instance; call .set()
to write data explicitly.
Client injection (inject_reader / inject_writer):
Handlers receive DbReader / DbWriter instances for
imperative control.
Decorator order contract
Decorator composition rules:
- Azure decorators outermost, db decorators closest to the function
- trigger + output can be combined (process events and write results)
- trigger + inject_writer can be combined (imperative write in trigger handler)
- input + output can be combined (read data, write results)
- input and inject_reader are mutually exclusive
- output and inject_writer are mutually exclusive
- No decorator can be applied twice to the same handler
Valid combinations::
@app.schedule(...)
@db.trigger(...) # Azure trigger outermost
@db.output("out", ...) # db output innermost
def handler(events, out: DbOut) -> None:
out.set([...])
@db.input("user", ...)
@db.output("out", ...)
def handler(user, out: DbOut) -> dict:
out.set({...})
return user
Note: This is a pseudo-trigger implementation. trigger requires
an actual Azure Functions trigger (e.g. @app.schedule) to fire.
It does not register a native Azure Functions binding.
trigger(*, arg_name, source, checkpoint_store, name=None, normalizer=None, batch_size=100, max_batches_per_tick=1, lease_ttl_seconds=120, retry_policy=None, metrics=None)
¶
Decorator for database change detection (pseudo-trigger).
Wraps a handler function so that on each invocation it polls the database source for new/changed rows and passes them to the handler.
The decorated function's arg_name parameter will receive the
list of :class:RowChange events. An optional parameter named
context will receive the :class:PollContext.
Must be used together with an actual Azure Functions trigger
(e.g. @app.schedule(...)).
Parameters¶
arg_name:
Name of the handler parameter that receives the events list.
source:
Database source adapter (e.g. SqlAlchemySource).
checkpoint_store:
State store for checkpointing (e.g. BlobCheckpointStore).
name:
Trigger name for logging/metrics. Defaults to the function name.
.. note::
Only synchronous handlers are supported. Async handlers will raise
ConfigurationError at decoration time. This is because
PollTrigger.run is synchronous.
Source code in src/azure_functions_db/decorator.py
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 | |
input(arg_name, *, url, table=None, schema=None, pk=None, query=None, params=None, model=None, on_not_found='none', engine_provider=None)
¶
Decorator that injects query results into the handler.
The handler parameter named arg_name will receive the actual
data from the database, not a DbReader instance. Exactly one
of pk or query must be provided.
PK mode (single row):
The parameter receives dict[str, object] | None. Use a
static dict for fixed lookups or a callable for dynamic
resolution from other handler parameters::
@db.input("user", url=..., table="users",
pk=lambda req: {"id": req.params["id"]})
def handler(req, user): ...
Query mode (multiple rows):
The parameter receives list[dict[str, object]]::
@db.input("users", url=...,
query="SELECT * FROM users WHERE active = :active",
params={"active": True})
def handler(users): ...
Parameters¶
arg_name:
Name of the handler parameter that receives the data.
url:
SQLAlchemy connection URL. Supports %VAR% env-var substitution.
table:
Table name. Required when using pk.
schema:
Optional schema qualifier.
pk:
Primary key for single-row lookup. Either a static dict or a
callable whose parameter names match other handler parameters.
query:
SQL query string for multi-row results. Use :name
placeholders for parameters.
params:
Parameters for query. Either a static dict or a callable.
on_not_found:
Behavior when pk lookup returns no row. "none" (default)
injects None; "raise" raises NotFoundError.
engine_provider:
Optional shared EngineProvider for connection pooling.
Supports both sync and async handlers. For async handlers, blocking
database I/O is automatically offloaded via asyncio.to_thread().
Source code in src/azure_functions_db/decorator.py
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 | |
output(arg_name, *, url, table, schema=None, action='insert', conflict_columns=None, engine_provider=None)
¶
Decorator that injects a :class:DbOut instance into the handler.
Follows the native Azure Functions output binding pattern
(func.Out[T] with .set()). The handler parameter named
arg_name will receive a DbOut instance for sync handlers
or an _AsyncDbOutProxy for async handlers.
The handler's return value is not intercepted — use
out.set(data) to write explicitly.
Parameters¶
arg_name:
Name of the handler parameter that receives the DbOut.
url:
SQLAlchemy connection URL. Supports %VAR% env-var substitution.
table:
Table name for write operations.
schema:
Optional schema qualifier.
action:
Write action: "insert" (default) or "upsert".
conflict_columns:
Columns for upsert conflict resolution. Required when
action="upsert".
engine_provider:
Optional shared EngineProvider for connection pooling.
Supports both sync and async handlers. For async handlers, blocking
database I/O is automatically offloaded via asyncio.to_thread().
Source code in src/azure_functions_db/decorator.py
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 | |
inject_reader(arg_name, *, url, table=None, schema=None, engine_provider=None)
¶
Decorator that injects a :class:DbReader instance into the handler.
Use this when you need imperative control over reads (multiple
queries, dynamic SQL, etc.). For simple data injection, prefer
:meth:input.
The handler parameter named arg_name will receive a pre-configured
DbReader instance. The reader is created fresh per invocation and
closed automatically after the handler returns.
Parameters¶
arg_name:
Name of the handler parameter that receives the DbReader.
url:
SQLAlchemy connection URL. Supports %VAR% env-var substitution.
table:
Optional table name for get() operations.
schema:
Optional schema qualifier.
engine_provider:
Optional shared EngineProvider for connection pooling.
Supports both sync and async handlers. For async handlers, blocking
database I/O is automatically offloaded via asyncio.to_thread().
Source code in src/azure_functions_db/decorator.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 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 | |
inject_writer(arg_name, *, url, table, schema=None, engine_provider=None)
¶
Decorator that injects a :class:DbWriter instance into the handler.
Use this when you need imperative control over writes (multiple
operations, transactions, update/delete, etc.). For simple
auto-write, prefer :meth:output.
The handler parameter named arg_name will receive a pre-configured
DbWriter instance. The writer is created fresh per invocation and
closed automatically after the handler returns.
Parameters¶
arg_name:
Name of the handler parameter that receives the DbWriter.
url:
SQLAlchemy connection URL. Supports %VAR% env-var substitution.
table:
Table name for write operations.
schema:
Optional schema qualifier.
engine_provider:
Optional shared EngineProvider for connection pooling.
Supports both sync and async handlers. For async handlers, blocking
database I/O is automatically offloaded via asyncio.to_thread().
Source code in src/azure_functions_db/decorator.py
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 | |
DbOut(*, url, table, schema, action, conflict_columns, engine_provider)
¶
Output binding parameter injected by the output decorator.
Mirrors the native Azure Functions func.Out[T] pattern.
The handler calls .set() to write data to the database explicitly,
leaving the handler's return value free for other purposes (e.g.
HttpResponse).
Example::
@db.output("order", url="%DB_URL%", table="orders")
def create_order(req, order: DbOut) -> func.HttpResponse:
order.set({"id": 1, "status": "pending"})
return func.HttpResponse("Created", status_code=201)
Accepted types for .set():
- dict — single-row write
- list[dict] — batch write
- BaseModel / list[BaseModel] — auto-dumped to dict
- None — no-op (skip write)
Source code in src/azure_functions_db/decorator.py
set(data)
¶
Write data to the configured table.
Parameters¶
data:
dict for single row, list[dict] for batch,
BaseModel / list[BaseModel] for Pydantic models,
or None to skip. Tuples and other non-list sequences
are rejected with :class:ConfigurationError.
Source code in src/azure_functions_db/decorator.py
BlobCheckpointStore(*, container_client, source_fingerprint)
¶
StateStore implementation backed by Azure Blob Storage.
Uses a single JSON blob per poller with ETag-based CAS (compare-and-swap) for all state mutations. Lease ownership is verified via owner_id and monotonically-increasing fencing tokens.
Source code in src/azure_functions_db/state/blob.py
acquire_lease(poller_name, ttl_seconds)
¶
Acquire a lease on the poller's state blob.
Creates the blob if it does not exist. If the blob exists and the
lease has expired (past expires_at + grace), the lease is stolen
with an incremented fencing token.
Returns a lease_id string in the format {owner_id}:{fencing_token}.
Raises LeaseConflictError when a lease is already active or
another instance won the CAS race.
Source code in src/azure_functions_db/state/blob.py
renew_lease(poller_name, lease_id, ttl_seconds)
¶
Renew an existing lease by extending its expiry.
Raises LostLeaseError if the lease is not held by this caller
or the CAS write fails.
Source code in src/azure_functions_db/state/blob.py
release_lease(poller_name, lease_id)
¶
Release the lease by setting expires_at to now.
Preserves the fencing token so the next acquisition increments it. Only owner_id and fencing_token are verified — expiry is intentionally skipped so that a holder can still release a lease that has nominally expired but has not yet been stolen.
Raises LostLeaseError if owner/token do not match or CAS fails.
Source code in src/azure_functions_db/state/blob.py
load_checkpoint(poller_name)
¶
Load the checkpoint for the given poller.
Returns an empty dict if the state blob does not exist. This method is read-only and has no side effects.
Source code in src/azure_functions_db/state/blob.py
commit_checkpoint(poller_name, checkpoint, lease_id)
¶
Commit a new checkpoint under the protection of the current lease.
Raises LostLeaseError if the lease is not held by this caller
or the CAS write fails.
Source code in src/azure_functions_db/state/blob.py
get_db_metadata(func)
¶
Return db metadata if the function was decorated with DbBindings decorators.
Returns None if the function has no db metadata attached.