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
+38-36Lines changed: 38 additions & 36 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,40 +1,42 @@
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 the [Azure portal](https://portal.azure.com/), the [JavaScript query API in Azure Cosmos DB](javascript-query-api.md), and the [Azure Cosmos DB for NoSQL 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
-
> [Note]
35
-
> When it comes to stored procedure, Cosmos DB has different charging policy. Since, stored can essentially execute code and consume any number of RUs, we do upfront charging for each stored procedure execution. This is a defense mechanism in backend to ensure stored procedure scripts do not impact out backend services. The amount which is charged upfront is the average charge consumed by the script in previous invocations. If the stored procedure has varied RUs per invocation i.e., lot of variance around the mean then the client may not be able to fully utilize the budget as we always reserve the average RU per operations before we start the execution. As an alternative we would suggest the client to use batch or bulk requests instead of stored procedures to avoid the variance around the RU charging.
36
-
>
37
-
Here is a simple stored procedure that returns a "Hello World" response.
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.
35
+
36
+
> [!NOTE]
37
+
> Azure Cosmos DB has a different charging policy for stored procedures. Because stored procedures can execute code and consume any number of request units (RUs), each execution requires an upfront charge. This ensures that stored procedure scripts don't impact backend services. The amount charged upfront equals the average charge consumed by the script in previous invocations. The average RUs per operation is reserved before execution. If the invocations have a lot of variance in RUs, your budget utilization might be affected. As an alternative, you should use batch or bulk requests instead of stored procedures to avoid variance around RU charges.
38
+
39
+
Here's a simple stored procedure that returns a "Hello World" response.
38
40
39
41
```javascript
40
42
var helloWorldStoredProc = {
@@ -50,15 +52,15 @@ var helloWorldStoredProc = {
50
52
51
53
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.
52
54
53
-
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.
55
+
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).
54
56
55
-
### <aid="create-an-item"></a>Create an item using stored procedure
57
+
### <aid="create-an-item"></a>Create items using stored procedures
56
58
57
-
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.
59
+
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.
58
60
59
-
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.
61
+
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.
60
62
61
-
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)
63
+
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).
62
64
63
65
```javascript
64
66
functioncreateToDoItems(items) {
@@ -99,7 +101,7 @@ function createToDoItems(items) {
99
101
100
102
### Arrays as input parameters for stored procedures
101
103
102
-
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:
104
+
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:
103
105
104
106
```javascript
105
107
functionsample(arr) {
@@ -114,7 +116,7 @@ function sample(arr) {
114
116
115
117
### <aid="transactions"></a>Transactions within stored procedures
116
118
117
-
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.
119
+
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.
118
120
119
121
```javascript
120
122
// JavaScript source code
@@ -235,9 +237,9 @@ function bulkImport(items) {
235
237
}
236
238
```
237
239
238
-
### <aid="async-promises"></a>Asyncawait with stored procedures
240
+
### <aid="async-promises"></a>Async/await with stored procedures
239
241
240
-
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.
242
+
The following stored procedure example uses `async/await` with *Promises* using a helper function. The stored procedure queries for an item and replaces it.
241
243
242
244
```javascript
243
245
functionasync_sample() {
@@ -287,11 +289,11 @@ function async_sample() {
287
289
288
290
## <aid="triggers"></a>How to write triggers
289
291
290
-
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.
292
+
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.
291
293
292
294
### <aid="pre-triggers"></a>Pre-triggers
293
295
294
-
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.
296
+
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.
295
297
296
298
```javascript
297
299
functionvalidateToDoItemTimestamp() {
@@ -312,11 +314,11 @@ function validateToDoItemTimestamp() {
312
314
}
313
315
```
314
316
315
-
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.
317
+
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.
316
318
317
-
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.
319
+
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 that using the trigger in a replace operation isn't permitted.
318
320
319
-
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.
321
+
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).
320
322
321
323
### <aid="post-triggers"></a>Post-triggers
322
324
@@ -359,23 +361,23 @@ function updateMetadata() {
359
361
}
360
362
```
361
363
362
-
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.
364
+
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 is rolled back and an exception is returned.
363
365
364
-
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.
366
+
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).
365
367
366
368
## <aid="udfs"></a>How to write user-defined functions
367
369
368
-
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:
370
+
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:
369
371
370
372
```json
371
373
{
372
-
"name": "Satya Nadella",
374
+
"name": "Daniel Elfyn",
373
375
"country": "USA",
374
376
"income": 70000
375
377
}
376
378
```
377
379
378
-
The following is a function definition to calculate income tax for various income brackets:
380
+
The following function definition calculates income tax for various income brackets:
379
381
380
382
```javascript
381
383
functiontax(income) {
@@ -391,11 +393,11 @@ function tax(income) {
391
393
}
392
394
```
393
395
394
-
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.
396
+
For examples of how to register and use a UDF, see [How to work with user-defined functions in Azure Cosmos DB](how-to-use-stored-procedures-triggers-udfs.md#how-to-work-with-user-defined-functions).
395
397
396
398
## Logging
397
399
398
-
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:
400
+
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