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
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
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()
¶
Release resources held by this writer.
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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
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 | |
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.
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.