You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: articles/cosmos-db/nosql/how-to-write-stored-procedures-triggers-udfs.md
+34-33Lines changed: 34 additions & 33 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,38 +1,39 @@
1
1
---
2
2
title: Write stored procedures, triggers, and UDFs in Azure Cosmos DB
3
-
description: Learn how to define stored procedures, triggers, and user-defined functions in Azure Cosmos DB
3
+
description: Learn how to define stored procedures, triggers, and user-defined functions by using the API for NoSQL in Azure Cosmos DB.
4
4
author: seesharprun
5
5
ms.service: cosmos-db
6
6
ms.subservice: nosql
7
7
ms.topic: how-to
8
-
ms.date: 10/05/2021
8
+
ms.date: 03/01/2023
9
9
ms.author: sidandrews
10
10
ms.reviewer: jucocchi
11
11
ms.devlang: javascript
12
12
ms.custom: devx-track-js
13
13
---
14
14
15
15
# How to write stored procedures, triggers, and user-defined functions in Azure Cosmos DB
16
+
16
17
[!INCLUDE[NoSQL](../includes/appliesto-nosql.md)]
17
18
18
-
Azure Cosmos DB provides language-integrated, transactional execution of JavaScript that lets you write **stored procedures**, **triggers**, and **user-defined functions (UDFs)**. When using the API for NoSQL in Azure Cosmos DB, you can define the stored procedures, triggers, and UDFs in JavaScript language. You can write your logic in JavaScript and execute it inside the database engine. You can create and execute triggers, stored procedures, and UDFs by using [Azure portal](https://portal.azure.com/), the [JavaScript language integrated query API in Azure Cosmos DB](javascript-query-api.md) and the [Azure Cosmos DB for NoSQL client SDKs](samples-dotnet.md).
19
+
Azure Cosmos DB provides language-integrated, transactional execution of JavaScript that lets you write *stored procedures*, *triggers*, and *user-defined functions (UDFs)*. When you use the API for NoSQL in Azure Cosmos DB, you can define the stored procedures, triggers, and UDFs using JavaScript. You can write your logic in JavaScript and execute it inside the database engine. You can create and execute triggers, stored procedures, and UDFs by using [Azure portal](https://portal.azure.com/), the [JavaScript language integrated query API in Azure Cosmos DB](javascript-query-api.md), and the [Azure Cosmos DB for NoSQL client SDKs](samples-dotnet.md).
19
20
20
-
To call a stored procedure, trigger, and user-defined function, you need to register it. For more information, see [How to work with stored procedures, triggers, user-defined functions in Azure Cosmos DB](how-to-use-stored-procedures-triggers-udfs.md).
21
+
To call a stored procedure, trigger, or UDF, you need to register it. For more information, see [How to work with stored procedures, triggers, and user-defined functions in Azure Cosmos DB](how-to-use-stored-procedures-triggers-udfs.md).
21
22
22
23
> [!NOTE]
23
-
> For partitioned containers, when executing a stored procedure, a partition key value must be provided in the request options. Stored procedures are always scoped to a partition key. Items that have a different partition key value will not be visible to the stored procedure. This also applied to triggers as well.
24
+
> For partitioned containers, when executing a stored procedure, a partition key value must be provided in the request options. Stored procedures are always scoped to a partition key. Items that have a different partition key value aren't visible to the stored procedure. This also applies to triggers.
24
25
25
26
> [!NOTE]
26
-
> Server-side JavaScript features including stored procedures, triggers, and user-defined functions do not support importing modules.
27
+
> Server-side JavaScript features, including stored procedures, triggers, and UDFs, don't support importing modules.
27
28
28
29
> [!TIP]
29
-
> Azure Cosmos DB supports deploying containers with stored procedures, triggers and user-defined functions. For more information see [Create an Azure Cosmos DB container with server-side functionality.](./manage-with-templates.md#create-sproc)
30
+
> Azure Cosmos DB supports deploying containers with stored procedures, triggers, and UDFs. For more information, see [Create an Azure Cosmos DB container with server-side functionality.](./manage-with-templates.md#create-sproc)
30
31
31
32
## <aid="stored-procedures"></a>How to write stored procedures
32
33
33
-
Stored procedures are written using JavaScript, they can create, update, read, query, and delete items inside an Azure Cosmos DB container. Stored procedures are registered per collection, and can operate on any document or an attachment present in that collection.
34
+
Stored procedures are written using JavaScript, and they can create, update, read, query, and delete items inside an Azure Cosmos DB container. Stored procedures are registered per collection, and can operate on any document or an attachment present in that collection.
34
35
35
-
Here is a simple stored procedure that returns a "Hello World" response.
36
+
Here's a simple stored procedure that returns a "Hello World" response.
36
37
37
38
```javascript
38
39
var helloWorldStoredProc = {
@@ -48,15 +49,15 @@ var helloWorldStoredProc = {
48
49
49
50
The context object provides access to all operations that can be performed in Azure Cosmos DB, as well as access to the request and response objects. In this case, you use the response object to set the body of the response to be sent back to the client.
50
51
51
-
Once written, the stored procedure must be registered with a collection. To learn more, see [How to use stored procedures in Azure Cosmos DB](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-stored-procedures) article.
52
+
Once written, the stored procedure must be registered with a collection. To learn more, see [How to use stored procedures in Azure Cosmos DB](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-stored-procedures).
52
53
53
-
### <aid="create-an-item"></a>Create an item using stored procedure
54
+
### <aid="create-an-item"></a>Create items using stored procedures
54
55
55
-
When you create an item by using stored procedure, the item is inserted into the Azure Cosmos DB container and an ID for the newly created item is returned. Creating an item is an asynchronous operation and depends on the JavaScript callback functions. The callback function has two parameters - one for the error object in case the operation fails and another for a return value; in this case, the created object. Inside the callback, you can either handle the exception or throw an error. In case a callback is not provided and there is an error, the Azure Cosmos DB runtime will throw an error.
56
+
When you create an item by using a stored procedure, the item is inserted into the Azure Cosmos DB container and an ID for the newly created item is returned. Creating an item is an asynchronous operation and depends on the JavaScript callback functions. The callback function has two parameters: one for the error object in case the operation fails, and another for a return value, in this case, the created object. Inside the callback, you can either handle the exception or throw an error. If a callback isn't provided and there's an error, the Azure Cosmos DB runtime throws an error.
56
57
57
-
The stored procedure also includes a parameter to set the description, it's a boolean value. When the parameter is set to true and the description is missing, the stored procedure will throw an exception. Otherwise, the rest of the stored procedure continues to run.
58
+
The stored procedure also includes a parameter to set the description as a boolean value. When the parameter is set to true and the description is missing, the stored procedure throws an exception. Otherwise, the rest of the stored procedure continues to run.
58
59
59
-
The following example stored procedure takes an array of new Azure Cosmos DB items as input, inserts it into the Azure Cosmos DB container and returns the count of the items inserted. In this example, we are leveraging the ToDoList sample from the [Quickstart .NET API for NoSQL](quickstart-dotnet.md)
60
+
The following example of a stored procedure takes an array of new Azure Cosmos DB items as input, inserts it into the Azure Cosmos DB container and returns the count of the items inserted. In this example, we're using the ToDoList sample from the [Quickstart .NET API for NoSQL](quickstart-dotnet.md).
60
61
61
62
```javascript
62
63
functioncreateToDoItems(items) {
@@ -97,7 +98,7 @@ function createToDoItems(items) {
97
98
98
99
### Arrays as input parameters for stored procedures
99
100
100
-
When defining a stored procedure in Azure portal, input parameters are always sent as a string to the stored procedure. Even if you pass an array of strings as an input, the array is converted to string and sent to the stored procedure. To work around this, you can define a function within your stored procedure to parse the string as an array. The following code shows how to parse a string input parameter as an array:
101
+
When you define a stored procedure in Azure portal, input parameters are always sent as a string to the stored procedure. Even if you pass an array of strings as an input, the array is converted to a string and sent to the stored procedure. To work around this, you can define a function within your stored procedure to parse the string as an array. The following code shows how to parse a string input parameter as an array:
101
102
102
103
```javascript
103
104
functionsample(arr) {
@@ -112,7 +113,7 @@ function sample(arr) {
112
113
113
114
### <aid="transactions"></a>Transactions within stored procedures
114
115
115
-
You can implement transactions on items within a container by using a stored procedure. The following example uses transactions within a fantasy football gaming app to trade players between two teams in a single operation. The stored procedure attempts to read the two Azure Cosmos DB items each corresponding to the player IDs passed in as an argument. If both players are found, then the stored procedure updates the items by swapping their teams. If any errors are encountered along the way, the stored procedure throws a JavaScript exception that implicitly aborts the transaction.
116
+
You can implement transactions on items within a container by using a stored procedure. The following example uses transactions within a fantasy football gaming app to trade players between two teams in a single operation. The stored procedure attempts to read the two Azure Cosmos DB items, each corresponding to the player IDs passed in as an argument. If both players are found, then the stored procedure updates the items by swapping their teams. If any errors are encountered along the way, the stored procedure throws a JavaScript exception that implicitly aborts the transaction.
116
117
117
118
```javascript
118
119
// JavaScript source code
@@ -233,9 +234,9 @@ function bulkImport(items) {
233
234
}
234
235
```
235
236
236
-
### <aid="async-promises"></a>Asyncawait with stored procedures
237
+
### <aid="async-promises"></a>Async/await with stored procedures
237
238
238
-
The following is an example of a stored procedure that uses async-await with Promises using a helper function. The stored procedure queries for an item and replaces it.
239
+
The following stored procedure example uses `async/await` with *Promises* using a helper function. The stored procedure queries for an item and replaces it.
239
240
240
241
```javascript
241
242
functionasync_sample() {
@@ -285,11 +286,11 @@ function async_sample() {
285
286
286
287
## <aid="triggers"></a>How to write triggers
287
288
288
-
Azure Cosmos DB supports pre-triggers and post-triggers. Pre-triggers are executed before modifying a database item and post-triggers are executed after modifying a database item. Triggers are not automatically executed, they must be specified for each database operation where you want them to execute. After you define a trigger, you should [register and call a pre-trigger](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-pre-triggers) by using the Azure Cosmos DB SDKs.
289
+
Azure Cosmos DB supports pre-triggers and post-triggers. Pre-triggers are executed before modifying a database item, and post-triggers are executed after modifying a database item. Triggers aren't automatically executed. They must be specified for each database operation where you want them to execute. After you define a trigger, you should [register and call a pre-trigger](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-pre-triggers) by using the Azure Cosmos DB SDKs.
289
290
290
291
### <aid="pre-triggers"></a>Pre-triggers
291
292
292
-
The following example shows how a pre-trigger is used to validate the properties of an Azure Cosmos DB item that is being created. In this example, we are leveraging the ToDoList sample from the [Quickstart .NET API for NoSQL](quickstart-dotnet.md), to add a timestamp property to a newly added item if it doesn't contain one.
293
+
The following example shows how a pre-trigger is used to validate the properties of an Azure Cosmos DB item that's being created. This example uses the ToDoList sample from the [Quickstart .NET API for NoSQL](quickstart-dotnet.md) to add a timestamp property to a newly added item if it doesn't contain one.
293
294
294
295
```javascript
295
296
functionvalidateToDoItemTimestamp() {
@@ -310,11 +311,11 @@ function validateToDoItemTimestamp() {
310
311
}
311
312
```
312
313
313
-
Pre-triggers cannot have any input parameters. The request object in the trigger is used to manipulate the request message associated with the operation. In the previous example, the pre-trigger is run when creating an Azure Cosmos DB item, and the request message body contains the item to be created in JSON format.
314
+
Pre-triggers can't have any input parameters. The request object in the trigger is used to manipulate the request message associated with the operation. In the previous example, the pre-trigger is run when creating an Azure Cosmos DB item, and the request message body contains the item to be created in JSON format.
314
315
315
-
When triggers are registered, you can specify the operations that it can run with. This trigger should be created with a `TriggerOperation` value of `TriggerOperation.Create`, which means using the trigger in a replace operation as shown in the following code is not permitted.
316
+
When triggers are registered, you can specify the operations that it can run with. This trigger should be created with a `TriggerOperation` value of `TriggerOperation.Create`, which means using the trigger in a replace operation isn't permitted.
316
317
317
-
For examples of how to register and call a pre-trigger, see [pre-triggers](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-pre-triggers) and [post-triggers](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-post-triggers) articles.
318
+
For examples of how to register and call a pre-trigger, see [pre-triggers](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-pre-triggers) and [post-triggers](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-post-triggers).
318
319
319
320
### <aid="post-triggers"></a>Post-triggers
320
321
@@ -357,23 +358,23 @@ function updateMetadata() {
357
358
}
358
359
```
359
360
360
-
One thing that is important to note is the transactional execution of triggers in Azure Cosmos DB. The post-trigger runs as part of the same transaction for the underlying item itself. An exception during the post-trigger execution will fail the whole transaction. Anything committed will be rolled back and an exception returned.
361
+
One thing that's important to note is the transactional execution of triggers in Azure Cosmos DB. The post-trigger runs as part of the same transaction for the underlying item itself. An exception during the post-trigger execution fails the whole transaction. Anything committed will be rolled back and an exception returned.
361
362
362
-
For examples of how to register and call a pre-trigger, see [pre-triggers](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-pre-triggers) and [post-triggers](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-post-triggers) articles.
363
+
For examples of how to register and call a pre-trigger, see [pre-triggers](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-pre-triggers) and [post-triggers](how-to-use-stored-procedures-triggers-udfs.md#how-to-run-post-triggers).
363
364
364
365
## <aid="udfs"></a>How to write user-defined functions
365
366
366
-
The following sample creates a UDF to calculate income tax for various income brackets. This user-defined function would then be used inside a query. For the purposes of this example assume there is a container called "Incomes" with properties as follows:
367
+
The following sample creates a UDF to calculate income tax for various income brackets. This user-defined function would then be used inside a query. For the purposes of this example, assume there's a container called *Incomes* with properties as follows:
367
368
368
369
```json
369
370
{
370
-
"name": "Satya Nadella",
371
+
"name": "Daniel Elfyn",
371
372
"country": "USA",
372
373
"income": 70000
373
374
}
374
375
```
375
376
376
-
The following is a function definition to calculate income tax for various income brackets:
377
+
The following function definition calculates income tax for various income brackets:
377
378
378
379
```javascript
379
380
functiontax(income) {
@@ -389,11 +390,11 @@ function tax(income) {
389
390
}
390
391
```
391
392
392
-
For examples of how to register and use a user-defined function, see [How to use user-defined functions in Azure Cosmos DB](how-to-use-stored-procedures-triggers-udfs.md#how-to-work-with-user-defined-functions) article.
393
+
For examples of how to register and use a UDF, see [How to use user-defined functions in Azure Cosmos DB](how-to-use-stored-procedures-triggers-udfs.md#how-to-work-with-user-defined-functions).
393
394
394
395
## Logging
395
396
396
-
When using stored procedure, triggers or user-defined functions, you can log the steps by enabling the script logging. A string for debugging is generated when `EnableScriptLogging` is set to true as shown in the following examples:
397
+
When using stored procedure, triggers, or UDFs, you can log the steps by enabling script logging. A string for debugging is generated when `EnableScriptLogging` is set to *true*, as shown in the following examples:
0 commit comments