API Reference¶
Auto-generated from source via mkdocstrings. For the hand-written API contract and design rationale (handler rules, source modes, semantics), see the canonical Python API Spec.
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/bindings.py
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 | |
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/bindings.py
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 | |
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/bindings.py
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 | |
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/bindings.py
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/bindings.py
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/out.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/out.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.