Skip to content

Commit 405277b

Browse files
authored
Merge pull request #217501 from dzsquared/sqlbindings-trigger
starting sql trigger docs
2 parents 53e1c2c + c141963 commit 405277b

8 files changed

+213
-23
lines changed

articles/azure-functions/TOC.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,9 @@
623623
- name: Overview
624624
href: functions-bindings-azure-sql.md
625625
displayName: Azure SQL
626+
- name: Trigger
627+
href: functions-bindings-azure-sql-trigger.md
628+
displayName: Azure SQL
626629
- name: Input
627630
href: functions-bindings-azure-sql-input.md
628631
displayName: Azure SQL

articles/azure-functions/functions-bindings-azure-sql-input.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ def main(req: func.HttpRequest, todoItems: func.SqlRowList) -> func.HttpResponse
492492
::: zone pivot="programming-language-csharp"
493493
## Attributes
494494

495-
In [C# class libraries](functions-dotnet-class-library.md), use the [Sql](https://github.com/Azure/azure-functions-sql-extension/blob/main/src/SqlAttribute.cs) attribute, which has the following properties:
495+
The [C# library](functions-dotnet-class-library.md) uses the [SqlAttribute](https://github.com/Azure/azure-functions-sql-extension/blob/main/src/SqlAttribute.cs) attribute to declare the SQL bindings on the function, which has the following properties:
496496

497497
| Attribute property |Description|
498498
|---------|---------|
@@ -540,7 +540,7 @@ The following table explains the binding configuration properties that you set i
540540

541541
::: zone pivot="programming-language-csharp,programming-language-javascript,programming-language-python"
542542

543-
The attribute's constructor takes the SQL command text, the command type, parameters, and the connection string setting name. The command can be a Transact-SQL (T-SQL) query with the command type `System.Data.CommandType.Text` or stored procedure name with the command type `System.Data.CommandType.StoredProcedure`. The connection string setting name corresponds to the application setting (in `local.settings.json` for local development) that contains the [connection string](/dotnet/api/microsoft.data.sqlclient.sqlconnection.connectionstring?view=sqlclient-dotnet-core-3.1&preserve-view=true#Microsoft_Data_SqlClient_SqlConnection_ConnectionString) to the Azure SQL or SQL Server instance.
543+
The attribute's constructor takes the SQL command text, the command type, parameters, and the connection string setting name. The command can be a Transact-SQL (T-SQL) query with the command type `System.Data.CommandType.Text` or stored procedure name with the command type `System.Data.CommandType.StoredProcedure`. The connection string setting name corresponds to the application setting (in `local.settings.json` for local development) that contains the [connection string](/dotnet/api/microsoft.data.sqlclient.sqlconnection.connectionstring?view=sqlclient-dotnet-core-5.0&preserve-view=true#Microsoft_Data_SqlClient_SqlConnection_ConnectionString) to the Azure SQL or SQL Server instance.
544544

545545
Queries executed by the input binding are [parameterized](/dotnet/api/microsoft.data.sqlclient.sqlparameter) in Microsoft.Data.SqlClient to reduce the risk of [SQL injection](/sql/relational-databases/security/sql-injection) from the parameter values passed into the binding.
546546

@@ -550,4 +550,5 @@ Queries executed by the input binding are [parameterized](/dotnet/api/microsoft.
550550
## Next steps
551551

552552
- [Save data to a database (Output binding)](./functions-bindings-azure-sql-output.md)
553+
- [Run a function when data is changed in a SQL table (Trigger)](./functions-bindings-azure-sql-trigger.md)
553554
- [Review ToDo API sample with Azure SQL bindings](/samples/azure-samples/azure-sql-binding-func-dotnet-todo/todo-backend-dotnet-azure-sql-bindings-azure-functions/)

articles/azure-functions/functions-bindings-azure-sql-output.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -501,7 +501,7 @@ def main(req: func.HttpRequest, todoItems: func.Out[func.SqlRow], requestLog: fu
501501
::: zone pivot="programming-language-csharp"
502502
## Attributes
503503

504-
In [C# class libraries](functions-dotnet-class-library.md), use the [Sql](https://github.com/Azure/azure-functions-sql-extension/blob/main/src/SqlAttribute.cs) attribute, which has the following properties:
504+
The [C# library](functions-dotnet-class-library.md) uses the [SqlAttribute](https://github.com/Azure/azure-functions-sql-extension/blob/main/src/SqlAttribute.cs) attribute to declare the SQL bindings on the function, which has the following properties:
505505

506506
| Attribute property |Description|
507507
|---------|---------|
@@ -544,13 +544,14 @@ The following table explains the binding configuration properties that you set i
544544
## Usage
545545

546546
::: zone pivot="programming-language-csharp,programming-language-javascript,programming-language-python"
547-
The `CommandText` property is the name of the table where the data is to be stored. The connection string setting name corresponds to the application setting that contains the [connection string](/dotnet/api/microsoft.data.sqlclient.sqlconnection.connectionstring?view=sqlclient-dotnet-core-3.1&preserve-view=true#Microsoft_Data_SqlClient_SqlConnection_ConnectionString) to the Azure SQL or SQL Server instance.
547+
The `CommandText` property is the name of the table where the data is to be stored. The connection string setting name corresponds to the application setting that contains the [connection string](/dotnet/api/microsoft.data.sqlclient.sqlconnection.connectionstring?view=sqlclient-dotnet-core-5.0&preserve-view=true#Microsoft_Data_SqlClient_SqlConnection_ConnectionString) to the Azure SQL or SQL Server instance.
548548

549-
The output bindings uses the T-SQL [MERGE](/sql/t-sql/statements/merge-transact-sql) statement which requires [SELECT](/sql/t-sql/statements/merge-transact-sql#permissions) permissions on the target database.
549+
The output bindings use the T-SQL [MERGE](/sql/t-sql/statements/merge-transact-sql) statement which requires [SELECT](/sql/t-sql/statements/merge-transact-sql#permissions) permissions on the target database.
550550

551551
::: zone-end
552552

553553
## Next steps
554554

555555
- [Read data from a database (Input binding)](./functions-bindings-azure-sql-input.md)
556+
- [Run a function when data is changed in a SQL table (Trigger)](./functions-bindings-azure-sql-trigger.md)
556557
- [Review ToDo API sample with Azure SQL bindings](/samples/azure-samples/azure-sql-binding-func-dotnet-todo/todo-backend-dotnet-azure-sql-bindings-azure-functions/)
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
---
2+
title: Azure SQL trigger for Functions
3+
description: Learn to use the Azure SQL trigger in Azure Functions.
4+
author: dzsquared
5+
ms.topic: reference
6+
ms.date: 11/10/2022
7+
ms.author: drskwier
8+
ms.reviewer: glenga
9+
zone_pivot_groups: programming-languages-set-functions-lang-workers
10+
---
11+
12+
# Azure SQL trigger for Functions (preview)
13+
14+
The Azure SQL trigger uses [SQL change tracking](/sql/relational-databases/track-changes/about-change-tracking-sql-server) functionality to monitor a SQL table for changes and trigger a function when a row is created, updated, or deleted.
15+
16+
For configuration details for change tracking for use with the Azure SQL trigger, see [Set up change tracking](#set-up-change-tracking-required). For information on setup details of the Azure SQL extension for Azure Functions, see the [SQL binding overview](./functions-bindings-azure-sql.md).
17+
18+
## Example usage
19+
<a id="example"></a>
20+
21+
::: zone pivot="programming-language-csharp"
22+
23+
More samples for the Azure SQL trigger are available in the [GitHub repository](https://github.com/Azure/azure-functions-sql-extension/tree/main/samples/samples-csharp).
24+
25+
26+
The example refers to a `ToDoItem` class and a corresponding database table:
27+
28+
:::code language="csharp" source="~/functions-sql-todo-sample/ToDoModel.cs" range="6-14":::
29+
30+
:::code language="sql" source="~/functions-sql-todo-sample/sql/create.sql" range="1-7":::
31+
32+
[Change tracking](#set-up-change-tracking-required) is enabled on the database and on the table:
33+
34+
```sql
35+
ALTER DATABASE [SampleDatabase]
36+
SET CHANGE_TRACKING = ON
37+
(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);
38+
39+
ALTER TABLE [dbo].[ToDo]
40+
ENABLE CHANGE_TRACKING;
41+
```
42+
43+
The SQL trigger binds to a `IReadOnlyList<SqlChange<T>>`, a list of `SqlChange` objects each with 2 properties:
44+
- **Item:** the item that was changed. The type of the item should follow the table schema as seen in the `ToDoItem` class.
45+
- **Operation:** a value from `SqlChangeOperation` enum. The possible values are `Insert`, `Update`, and `Delete`.
46+
47+
# [In-process](#tab/in-process)
48+
49+
The following example shows a [C# function](functions-dotnet-class-library.md) that is invoked when there are changes to the `ToDo` table:
50+
51+
```cs
52+
using System.Collections.Generic;
53+
using Microsoft.Azure.WebJobs;
54+
using Microsoft.Extensions.Logging;
55+
using Microsoft.Azure.WebJobs.Extensions.Sql;
56+
57+
namespace AzureSQL.ToDo
58+
{
59+
public static class ToDoTrigger
60+
{
61+
[FunctionName("ToDoTrigger")]
62+
public static void Run(
63+
[SqlTrigger("[dbo].[ToDo]", ConnectionStringSetting = "SqlConnectionString")]
64+
IReadOnlyList<SqlChange<ToDoItem>> changes,
65+
ILogger logger)
66+
{
67+
foreach (SqlChange<ToDoItem> change in changes)
68+
{
69+
ToDoItem toDoItem = change.Item;
70+
logger.LogInformation($"Change operation: {change.Operation}");
71+
logger.LogInformation($"Id: {toDoItem.Id}, Title: {toDoItem.title}, Url: {toDoItem.url}, Completed: {toDoItem.completed}");
72+
}
73+
}
74+
}
75+
}
76+
```
77+
78+
# [Isolated process](#tab/isolated-process)
79+
80+
Isolated worker process isn't currently supported.
81+
82+
<!-- Uncomment to support C# script examples.
83+
# [C# Script](#tab/csharp-script)
84+
85+
-->
86+
---
87+
88+
89+
::: zone-end
90+
91+
::: zone pivot="programming-language-java,programming-language-powershell,programming-language-javascript,programming-language-python"
92+
93+
> [!NOTE]
94+
> In the current preview, Azure SQL triggers are only supported by [C# class library functions](functions-dotnet-class-library.md)
95+
96+
::: zone-end
97+
98+
99+
::: zone pivot="programming-language-csharp"
100+
## Attributes
101+
102+
The [C# library](functions-dotnet-class-library.md) uses the [SqlTrigger](https://github.com/Azure/azure-functions-sql-extension/blob/main/src/TriggerBinding/SqlTriggerAttribute.cs) attribute to declare the SQL trigger on the function, which has the following properties:
103+
104+
| Attribute property |Description|
105+
|---------|---------|
106+
| **TableName** | Required. The name of the table being monitored by the trigger. |
107+
| **ConnectionStringSetting** | Required. The name of an app setting that contains the connection string for the database which contains the table being monitored for changes. The connection string setting name corresponds to the application setting (in `local.settings.json` for local development) that contains the [connection string](/dotnet/api/microsoft.data.sqlclient.sqlconnection.connectionstring?view=sqlclient-dotnet-core-5.&preserve-view=true#Microsoft_Data_SqlClient_SqlConnection_ConnectionString) to the Azure SQL or SQL Server instance.|
108+
109+
110+
::: zone-end
111+
112+
## Configuration
113+
114+
<!-- ### for another day ###
115+
::: zone pivot="programming-language-java,programming-language-powershell,programming-language-javascript,programming-language-python"
116+
117+
118+
The following table explains the binding configuration properties that you set in the function.json file.
119+
120+
|function.json property | Description|
121+
122+
::: zone-end -->
123+
124+
125+
In addition to the required ConnectionStringSetting [application setting](./functions-how-to-use-azure-function-app-settings.md#settings), the following optional settings can be configured for the SQL trigger:
126+
127+
| App Setting | Description|
128+
|---------|---------|
129+
|**Sql_Trigger_BatchSize** |This controls the number of changes processed at once before being sent to the triggered function. The default value is 100.|
130+
|**Sql_Trigger_PollingIntervalMs**|This controls the delay in milliseconds between processing each batch of changes. The default value is 1000 (1 second).|
131+
|**Sql_Trigger_MaxChangesPerWorker**|This controls the upper limit on the number of pending changes in the user table that are allowed per application-worker. If the count of changes exceeds this limit, it may result in a scale out. The setting only applies for Azure Function Apps with [runtime driven scaling enabled](#enable-runtime-driven-scaling). The default value is 1000.|
132+
133+
134+
[!INCLUDE [app settings to local.settings.json](../../includes/functions-app-settings-local.md)]
135+
136+
## Set up change tracking (required)
137+
138+
Setting up change tracking for use with the Azure SQL trigger requires two steps. These steps can be completed from any SQL tool that supports running queries, including [VS Code](/sql/tools/visual-studio-code/mssql-extensions), [Azure Data Studio](/sql/azure-data-studio/download-azure-data-studio) or [SQL Server Management Studio](/sql/ssms/download-sql-server-management-studio-ssms).
139+
140+
1. Enable change tracking on the SQL database, substituting `your database name` with the name of the database where the table to be monitored is located:
141+
142+
```sql
143+
ALTER DATABASE [your database name]
144+
SET CHANGE_TRACKING = ON
145+
(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);
146+
```
147+
148+
The `CHANGE_RETENTION` option specifies the time period for which change tracking information (change history) is kept. The retention of change history by the SQL database may affect the trigger functionality. For example, if the Azure Function is turned off for several days and then resumed, it will only be able to catch the changes that occurred in past two days with the above query.
149+
150+
The `AUTO_CLEANUP` option is used to enable or disable the clean-up task that removes old change tracking information. If a temporary problem that prevents the trigger from running, turning off auto cleanup can be useful to pause the removal of information older than the retention period until the problem is resolved.
151+
152+
More information on change tracking options is available in the [SQL documentation](/sql/relational-databases/track-changes/enable-and-disable-change-tracking-sql-server).
153+
154+
2. Enable change tracking on the table, substituting `your table name` with the name of the table to be monitored (changing the schema if appropriate):
155+
156+
```sql
157+
ALTER TABLE [dbo].[your table name]
158+
ENABLE CHANGE_TRACKING;
159+
```
160+
161+
The trigger needs to have read access on the table being monitored for changes and to the change tracking system tables. Each function trigger will have associated change tracking table and leases table in a schema `az_func`, which are created by the trigger if they don't yet exist. More information on these data structures is available in the Azure SQL binding library [documentation](https://github.com/Azure/azure-functions-sql-extension/blob/triggerbindings/README.md#internal-state-tables).
162+
163+
164+
## Enable runtime-driven scaling
165+
166+
Optionally, your functions can scale automatically based on the amount of changes that are pending to be processed in the user table. To allow your functions to scale properly on the Premium plan when using SQL triggers, you need to enable runtime scale monitoring.
167+
168+
[!INCLUDE [functions-runtime-scaling](../../includes/functions-runtime-scaling.md)]
169+
170+
171+
## Next steps
172+
173+
- [Read data from a database (Input binding)](./functions-bindings-azure-sql-input.md)
174+
- [Save data to a database (Output binding)](./functions-bindings-azure-sql-output.md)

articles/azure-functions/functions-bindings-azure-sql.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@ zone_pivot_groups: programming-languages-set-functions-lang-workers
1212

1313
# Azure SQL bindings for Azure Functions overview (preview)
1414

15-
This set of articles explains how to work with [Azure SQL](/azure/azure-sql/index) bindings in Azure Functions. Azure Functions supports input and output bindings for the Azure SQL and SQL Server products.
15+
This set of articles explains how to work with [Azure SQL](/azure/azure-sql/index) bindings in Azure Functions. Azure Functions supports input bindings, output bindings, and a function trigger for the Azure SQL and SQL Server products.
1616

1717
| Action | Type |
1818
|---------|---------|
19+
| Trigger a function when a change is detected on a SQL table | [SQL trigger](./functions-bindings-azure-sql-trigger.md) |
1920
| Read data from a database | [Input binding](./functions-bindings-azure-sql-input.md) |
2021
| Save data to a database |[Output binding](./functions-bindings-azure-sql-output.md) |
2122

@@ -156,7 +157,7 @@ Support for Python durable functions with SQL bindings isn't yet available.
156157

157158
## SQL connection string
158159

159-
Azure SQL bindings for Azure Functions have a required property for connection string on both [input](./functions-bindings-azure-sql-input.md) and [output](./functions-bindings-azure-sql-output.md) bindings. SQL bindings passes the connection string to the Microsoft.Data.SqlClient library and supports the connection string as defined in the [SqlClient ConnectionString documentation](/dotnet/api/microsoft.data.sqlclient.sqlconnection.connectionstring?view=sqlclient-dotnet-core-3.1&preserve-view=true). Notable keywords include:
160+
Azure SQL bindings for Azure Functions have a required property for connection string on both [input](./functions-bindings-azure-sql-input.md) and [output](./functions-bindings-azure-sql-output.md) bindings. SQL bindings passes the connection string to the Microsoft.Data.SqlClient library and supports the connection string as defined in the [SqlClient ConnectionString documentation](/dotnet/api/microsoft.data.sqlclient.sqlconnection.connectionstring?view=sqlclient-dotnet-core-5.0&preserve-view=true#Microsoft_Data_SqlClient_SqlConnection_ConnectionString). Notable keywords include:
160161

161162
- `Authentication` allows a function to connect to Azure SQL with Azure Active Directory, including [Active Directory Managed Identity](./functions-identity-access-azure-sql-with-managed-identity.md)
162163
- `Command Timeout` allows a function to wait for specified amount of time in seconds before terminating a query (default 30 seconds)
@@ -165,8 +166,7 @@ Azure SQL bindings for Azure Functions have a required property for connection s
165166

166167
## Considerations
167168

168-
- Because the Azure SQL bindings doesn't have a trigger, you need to use another supported trigger to start a function that reads from or writes to an Azure SQL database.
169-
- Azure SQL binding supports version 2.x and later of the Functions runtime.
169+
- Azure SQL binding supports version 4.x and later of the Functions runtime.
170170
- Source code for the Azure SQL bindings can be found in [this GitHub repository](https://github.com/Azure/azure-functions-sql-extension).
171171
- This binding requires connectivity to an Azure SQL or SQL Server database.
172172
- Output bindings against tables with columns of data types `NTEXT`, `TEXT`, or `IMAGE` aren't supported and data upserts will fail. These types [will be removed](/sql/t-sql/data-types/ntext-text-and-image-transact-sql) in a future version of SQL Server and aren't compatible with the `OPENJSON` function used by this Azure Functions binding.
@@ -176,6 +176,7 @@ Azure SQL bindings for Azure Functions have a required property for connection s
176176

177177
- [Read data from a database (Input binding)](./functions-bindings-azure-sql-input.md)
178178
- [Save data to a database (Output binding)](./functions-bindings-azure-sql-output.md)
179+
- [Run a function when data is changed in a SQL table (Trigger)](./functions-bindings-azure-sql-trigger.md)
179180
- [Review ToDo API sample with Azure SQL bindings](/samples/azure-samples/azure-sql-binding-func-dotnet-todo/todo-backend-dotnet-azure-sql-bindings-azure-functions/)
180181
- [Learn how to connect Azure Function to Azure SQL with managed identity](./functions-identity-access-azure-sql-with-managed-identity.md)
181182
- [Use SQL bindings in Azure Stream Analytics](../stream-analytics/sql-database-upsert.md#option-1-update-by-key-with-the-azure-function-sql-binding)

0 commit comments

Comments
 (0)