Skip to content

Latest commit

 

History

History
583 lines (431 loc) · 21.5 KB

functions-bindings-storage-table-output.md

File metadata and controls

583 lines (431 loc) · 21.5 KB
titledescriptionms.topicms.datems.devlangms.customzone_pivot_groups
Azure Tables output bindings for Azure Functions
Understand how to use Azure Tables output bindings in Azure Functions.
reference
11/11/2022
csharp
devx-track-csharp, devx-track-python, devx-track-extended-java, devx-track-js, devx-track-ts
programming-languages-set-functions

Azure Tables output bindings for Azure Functions

Use an Azure Tables output binding to write entities to a table in Azure Cosmos DB for Table or Azure Table Storage.

For information on setup and configuration details, see the overview

Note

This output binding only supports creating new entities in a table. If you need to update an existing entity from your function code, instead use an Azure Tables SDK directly.

::: zone pivot="programming-language-javascript,programming-language-typescript" [!INCLUDE functions-nodejs-model-tabs-description] ::: zone-end

Example

::: zone pivot="programming-language-csharp"

[!INCLUDE functions-bindings-csharp-intro]

[!INCLUDE functions-in-process-model-retirement-note]

The following MyTableData class represents a row of data in the table:

publicclassMyTableData:Azure.Data.Tables.ITableEntity{publicstringText{get;set;}publicstringPartitionKey{get;set;}publicstringRowKey{get;set;}publicDateTimeOffset?Timestamp{get;set;}publicETagETag{get;set;}}

The following function, which is started by a Queue Storage trigger, writes a new MyDataTable entity to a table named OutputTable.

[Function("TableFunction")][TableOutput("OutputTable",Connection="AzureWebJobsStorage")]publicstaticMyTableDataRun([QueueTrigger("table-items")]stringinput,[TableInput("MyTable","<PartitionKey>","{queueTrigger}")]MyTableDatatableInput,FunctionContextcontext){varlogger=context.GetLogger("TableFunction");logger.LogInformation($"PK={tableInput.PartitionKey}, RK={tableInput.RowKey}, Text={tableInput.Text}");returnnewMyTableData(){PartitionKey="queue",RowKey=Guid.NewGuid().ToString(),Text=$"Output record with rowkey {input} created at {DateTime.Now}"};}

The following example shows a C# function that uses an HTTP trigger to write a single table row.

publicclassTableStorage{publicclassMyPoco{publicstringPartitionKey{get;set;}publicstringRowKey{get;set;}publicstringText{get;set;}}[FunctionName("TableOutput")][return:Table("MyTable")]publicstaticMyPocoTableOutput([HttpTrigger]dynamicinput,ILoggerlog){log.LogInformation($"C# http trigger function processed: {input.Text}");returnnewMyPoco{PartitionKey="Http",RowKey=Guid.NewGuid().ToString(),Text=input.Text};}}

::: zone-end ::: zone pivot="programming-language-java"

The following example shows a Java function that uses an HTTP trigger to write a single table row.

publicclassPerson { privateStringPartitionKey; privateStringRowKey; privateStringName; publicStringgetPartitionKey() {returnthis.PartitionKey;} publicvoidsetPartitionKey(Stringkey) {this.PartitionKey = key; } publicStringgetRowKey() {returnthis.RowKey;} publicvoidsetRowKey(Stringkey) {this.RowKey = key; } publicStringgetName() {returnthis.Name;} publicvoidsetName(Stringname) {this.Name = name; } } publicclassAddPerson { @FunctionName("addPerson") publicHttpResponseMessageget( @HttpTrigger(name = "postPerson", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION, route="persons/{partitionKey}/{rowKey}") HttpRequestMessage<Optional<Person>> request, @BindingName("partitionKey") StringpartitionKey, @BindingName("rowKey") StringrowKey, @TableOutput(name="person", partitionKey="{partitionKey}", rowKey = "{rowKey}", tableName="%MyTableName%", connection="MyConnectionString") OutputBinding<Person> person, finalExecutionContextcontext) { PersonoutPerson = newPerson(); outPerson.setPartitionKey(partitionKey); outPerson.setRowKey(rowKey); outPerson.setName(request.getBody().get().getName()); person.setValue(outPerson); returnrequest.createResponseBuilder(HttpStatus.OK) .header("Content-Type", "application/json") .body(outPerson) .build(); } }

The following example shows a Java function that uses an HTTP trigger to write multiple table rows.

publicclassPerson { privateStringPartitionKey; privateStringRowKey; privateStringName; publicStringgetPartitionKey() {returnthis.PartitionKey;} publicvoidsetPartitionKey(Stringkey) {this.PartitionKey = key; } publicStringgetRowKey() {returnthis.RowKey;} publicvoidsetRowKey(Stringkey) {this.RowKey = key; } publicStringgetName() {returnthis.Name;} publicvoidsetName(Stringname) {this.Name = name; } } publicclassAddPersons { @FunctionName("addPersons") publicHttpResponseMessageget( @HttpTrigger(name = "postPersons", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION, route="persons/") HttpRequestMessage<Optional<Person[]>> request, @TableOutput(name="person", tableName="%MyTableName%", connection="MyConnectionString") OutputBinding<Person[]> persons, finalExecutionContextcontext) { persons.setValue(request.getBody().get()); returnrequest.createResponseBuilder(HttpStatus.OK) .header("Content-Type", "application/json") .body(request.getBody().get()) .build(); } }

::: zone-end
::: zone pivot="programming-language-javascript,programming-language-typescript"

The following example shows a table output binding that writes multiple table entities.

::: zone-end ::: zone pivot="programming-language-typescript"

:::code language="typescript" source="~/azure-functions-nodejs-v4/ts/src/functions/tableOutput1.ts" :::

TypeScript samples are not documented for model v3.


::: zone-end ::: zone pivot="programming-language-javascript"

:::code language="javascript" source="~/azure-functions-nodejs-v4/js/src/functions/tableOutput1.js" :::

Here's the function.json file:

{ "bindings": [ { "name": "input", "type": "manualTrigger", "direction": "in" }, { "tableName": "Person", "connection": "MyStorageConnectionAppSetting", "name": "tableBinding", "type": "table", "direction": "out" } ], "disabled": false }

The configuration section explains these properties.

Here's the JavaScript code:

module.exports=asyncfunction(context){context.bindings.tableBinding=[];for(vari=1;i<10;i++){context.bindings.tableBinding.push({PartitionKey: "Test",RowKey: i.toString(),Name: "Name "+i});}};

::: zone-end
::: zone pivot="programming-language-powershell"

The following example demonstrates how to write multiple entities to a table from a function.

Binding configuration in function.json:

{ "bindings": [ { "name": "InputData", "type": "manualTrigger", "direction": "in" }, { "tableName": "Person", "connection": "MyStorageConnectionAppSetting", "name": "TableBinding", "type": "table", "direction": "out" } ], "disabled": false }

PowerShell code in run.ps1:

param($InputData,$TriggerMetadata) foreach ($iin1..10) { Push-OutputBinding-Name TableBinding -Value @{ PartitionKey='Test'RowKey="$i"Name="Name $i" } }

::: zone-end
::: zone pivot="programming-language-python"

The following example demonstrates how to use the Table storage output binding. Configure the table binding in the function.json by assigning values to name, tableName, partitionKey, and connection:

{ "scriptFile": "__init__.py", "bindings": [ { "name": "message", "type": "table", "tableName": "messages", "partitionKey": "message", "connection": "AzureWebJobsStorage", "direction": "out" }, { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "$return" } ] }

The following function generates a unique UUI for the rowKey value and persists the message into Table storage.

importloggingimportuuidimportjsonimportazure.functionsasfuncdefmain(req: func.HttpRequest, message: func.Out[str]) ->func.HttpResponse: rowKey=str(uuid.uuid4()) data= { "Name": "Output binding message", "PartitionKey": "message", "RowKey": rowKey } message.set(json.dumps(data)) returnfunc.HttpResponse(f"Message created with the rowKey: {rowKey}")

::: zone-end
::: zone pivot="programming-language-csharp"

Attributes

Both in-process and isolated worker process C# libraries use attributes to define the function. C# script instead uses a function.json configuration file as described in the C# scripting guide.

In C# class libraries, the TableInputAttribute supports the following properties:

Attribute propertyDescription
TableNameThe name of the table to which to write.
PartitionKeyThe partition key of the table entity to write.
RowKeyThe row key of the table entity to write.
ConnectionThe name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

In C# class libraries, the TableAttribute supports the following properties:

Attribute propertyDescription
TableNameThe name of the table to which to write.
PartitionKeyThe partition key of the table entity to write.
RowKeyThe row key of the table entity to write.
ConnectionThe name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

The attribute's constructor takes the table name. Use the attribute on an out parameter or on the return value of the function, as shown in the following example:

[FunctionName("TableOutput")][return:Table("MyTable")]publicstaticMyPocoTableOutput([HttpTrigger]dynamicinput,ILoggerlog){ ...}

You can set the Connection property to specify a connection to the table service, as shown in the following example:

[FunctionName("TableOutput")][return:Table("MyTable",Connection="StorageConnectionAppSetting")]publicstaticMyPocoTableOutput([HttpTrigger]dynamicinput,ILoggerlog){ ...}

[!INCLUDE functions-bindings-storage-attribute]


::: zone-end
::: zone pivot="programming-language-java"

Annotations

In the Java functions runtime library, use the TableOutput annotation on parameters to write values into your tables. The attribute supports the following elements:

ElementDescription
nameThe variable name used in function code that represents the table or entity.
dataTypeDefines how Functions runtime should treat the parameter value. To learn more, see dataType.
tableNameThe name of the table to which to write.
partitionKeyThe partition key of the table entity to write.
rowKeyThe row key of the table entity to write.
connectionThe name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

::: zone-end
::: zone pivot="programming-language-javascript,programming-language-typescript"

Configuration

The following table explains the properties that you can set on the options object passed to the output.table() method.

PropertyDescription
tableNameThe name of the table to which to write.
partitionKeyThe partition key of the table entity to write.
rowKeyThe row key of the table entity to write.
connectionThe name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

The following table explains the binding configuration properties that you set in the function.json file.

PropertyDescription
typeMust be set to table. This property is set automatically when you create the binding in the Azure portal.
directionMust be set to out. This property is set automatically when you create the binding in the Azure portal.
nameThe variable name used in function code that represents the table or entity. Set to $return to reference the function return value.
tableNameThe name of the table to which to write.
partitionKeyThe partition key of the table entity to write.
rowKeyThe row key of the table entity to write.
connectionThe name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

::: zone-end ::: zone pivot="programming-language-powershell,programming-language-python"

Configuration

The following table explains the binding configuration properties that you set in the function.json file.

function.json propertyDescription
typeMust be set to table. This property is set automatically when you create the binding in the Azure portal.
directionMust be set to out. This property is set automatically when you create the binding in the Azure portal.
nameThe variable name used in function code that represents the table or entity. Set to $return to reference the function return value.
tableNameThe name of the table to which to write.
partitionKeyThe partition key of the table entity to write.
rowKeyThe row key of the table entity to write.
connectionThe name of an app setting or setting collection that specifies how to connect to the table service. See Connections.

[!INCLUDE app settings to local.settings.json] ::: zone-end

[!INCLUDE functions-table-connections]

Usage

::: zone pivot="programming-language-csharp"

The usage of the binding depends on the extension package version, and the C# modality used in your function app, which can be one of the following:

An isolated worker process class library compiled C# function runs in a process isolated from the runtime.

An in-process class library is a compiled C# function runs in the same process as the Functions runtime.


Choose a version to see usage details for the mode and version.

The following types are supported for out parameters and return types:

  • A plain-old CLR object (POCO) that includes the PartitionKey and RowKey properties. You can accompany these properties by implementing ITableEntity.
  • ICollector<T> or IAsyncCollector<T> where T includes the PartitionKey and RowKey properties. You can accompany these properties by implementing ITableEntity.

You can also bind to TableClientfrom the Azure SDK. You can then use that object to write to the table.

The following types are supported for out parameters and return types:

  • A plain-old CLR object (POCO) that includes the PartitionKey and RowKey properties. You can accompany these properties by implementing ITableEntity or inheriting TableEntity.
  • ICollector<T> or IAsyncCollector<T> where T includes the PartitionKey and RowKey properties. You can accompany these properties by implementing ITableEntity or inheriting TableEntity.

You can also bind to CloudTablefrom the Storage SDK as a method parameter. You can then use that object to write to the table.

The following types are supported for out parameters and return types:

  • A plain-old CLR object (POCO) that includes the PartitionKey and RowKey properties. You can accompany these properties by implementing ITableEntity or inheriting TableEntity.
  • ICollector<T> or IAsyncCollector<T> where T includes the PartitionKey and RowKey properties. You can accompany these properties by implementing ITableEntity or inheriting TableEntity.

You can also bind to CloudTablefrom the Storage SDK as a method parameter. You can then use that object to write to the table.

[!INCLUDE functions-bindings-table-output-dotnet-isolated-types]

Return a plain-old CLR object (POCO) with properties that can be mapped to the table entity.

Functions version 1.x doesn't support isolated worker process.


::: zone-end
::: zone pivot="programming-language-java" There are two options for outputting a Table storage row from a function by using the TableStorageOutput annotation:

OptionsDescription
Return valueBy applying the annotation to the function itself, the return value of the function persists as a Table storage row.
ImperativeTo explicitly set the table row, apply the annotation to a specific parameter of the type OutputBinding<T>, where T includes the PartitionKey and RowKey properties. You can accompany these properties by implementing ITableEntity or inheriting TableEntity.

::: zone-end
::: zone pivot="programming-language-javascript,programming-language-typescript"

Set the output row data by returning the value or using context.extraOutputs.set().

Set the output row data by using context.bindings.<name> where <name> is the value specified in the name property of function.json.


::: zone-end ::: zone pivot="programming-language-powershell"
To write to table data, use the Push-OutputBinding cmdlet, set the -Name TableBinding parameter and -Value parameter equal to the row data. See the PowerShell example for more detail.

::: zone-end
::: zone pivot="programming-language-python"
There are two options for outputting a Table storage row message from a function:

OptionsDescription
Return valueSet the name property in function.json to $return. With this configuration, the function's return value persists as a Table storage row.
ImperativePass a value to the set method of the parameter declared as an Out type. The value passed to set is persisted as table row.
::: zone-end

For specific usage details, see Example.

Exceptions and return codes

BindingReference
TableTable Error Codes
Blob, Table, QueueStorage Error Codes
Blob, Table, QueueTroubleshooting

Next steps

[!div class="nextstepaction"] Learn more about Azure functions triggers and bindings

close