|
| 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) |
0 commit comments