DocumentDB教程
DocumentDB SQL

SQL JavaScript 集成

如今 JavaScript 无处不在,而不仅仅是在浏览器中。 DocumentDB 将 JavaScript 作为一种现代 T-SQL 包含在内,并在数据库引擎内部支持原生 JavaScript 逻辑的事务执行。 DocumentDB 提供了一种编程模型,用于在存储过程和触发器方面直接在集合上执行基于 JavaScript 的应用程序逻辑。
让我们看一个创建简单存储过程的示例。以下是步骤-
步骤 1-创建一个新的控制台应用程序。
第 2 步-从 NuGet 添加 .NET SDK。我们在这里使用 .NET SDK,这意味着我们将编写一些 C# 代码来创建、执行和删除我们的存储过程,但存储过程本身是用 JavaScript 编写的。
步骤 3-右键单击​​解决方案资源管理器中的项目。
步骤 4-为存储过程添加一个新的 JavaScript 文件并将其命名为 HelloWorldStoreProce.js
JavaScript 存储过程
每个存储过程都只是一个 JavaScript 函数,因此我们将创建一个新函数,当然我们也会将此函数命名为 HelloWorldStoreProce。如果我们给函数一个名字,这并不重要。 DocumentDB 只会通过我们在创建它时提供的 ID 来引用这个存储过程。
function HelloWorldStoreProce() { 
   var context = getContext(); 
   var response = context.getResponse(); 
   response.setBody('Hello, and welcome to DocumentDB!'); 
}
存储过程所做的只是从上下文中获取响应对象并调用其 setBody 方法将字符串返回给调用者。在 C# 代码中,我们将创建存储过程,执行它,然后删除它。
存储过程的范围是每个集合,因此我们需要集合的 SelfLink 来创建存储过程。
步骤 5-首先查询 myfirstdb 数据库,然后查询 MyCollection 集合。
创建存储过程就像在 DocumentDB 中创建任何其他资源一样。
private async static Task SimpleStoredProcDemo() {  
   var endpoint = "https://azuredocdbdemo.documents.azure.com:443/"; 
   var masterKey = 
      "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
	  
   using (var client = new DocumentClient(new Uri(endpoint), masterKey)) { 
      // Get database 
      Database database = client 
         .CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'") 
         .AsEnumerable() 
         .First();
			
      // Get collection 
      DocumentCollection collection = client 
         .CreateDocumentCollectionQuery(database.CollectionsLink, "SELECT * FROM 
         c WHERE c.id = 'MyCollection'") 
         .AsEnumerable() 
         .First();
			
      // Create stored procedure 
      var sprocBody = File.ReadAllText(@"..\..\HelloWorldStoreProce.js"); 
		
      var sprocDefinition = new StoredProcedure { 
         Id = "HelloWorldStoreProce", 
         Body = sprocBody 
      };
	  
      StoredProcedure sproc = await client.
         CreateStoredProcedureAsync(collection.SelfLink, sprocDefinition); 
      Console.WriteLine("Created stored procedure {0} ({1})", 
         sproc.Id, sproc.ResourceId);
				  
      // Execute stored procedure 
      var result = await client.ExecuteStoredProcedureAsync
    
   
    
     (sproc.SelfLink); 
      Console.
    WriteLine(
    "Executed stored procedure; response = {0}", result.Response);
	  
      
    // Delete stored procedure 
      await client.
    DeleteStoredProcedureAsync(sproc.SelfLink); 
      Console.
    WriteLine(
    "Deleted stored procedure {0} ({1})", 
         sproc.Id, sproc.ResourceId); 
   }  
} 
    
   
步骤 6-首先使用新资源的 Id 创建一个定义对象,然后调用 DocumentClient 对象上的 Create 方法之一。对于存储过程,定义包括 Id 和您想要传送到服务器的实际 JavaScript 代码。
步骤 7-调用 File.ReadAllText 从 JS 文件中提取存储过程代码。
步骤 8-将存储过程代码分配给定义对象的 body 属性。
就 DocumentDB 而言,我们这里在定义中指定的 Id 是存储过程的名称,而不管我们实际命名 JavaScript 函数的名称是什么。
尽管如此,在创建存储过程和其他服务器端对象时,建议我们命名 JavaScript 函数,并且这些函数名称确实与我们在 DocumentDB 定义中设置的 Id 匹配。
步骤 9-调用 CreateStoredProcedureAsync,传入 MyCollection 集合的 SelfLink 和存储过程定义.这将创建存储过程和 DocumentDB 分配给它的 ResourceId
步骤 10-调用存储过程。 ExecuteStoredProcedureAsync 采用您设置为存储过程返回值的预期数据类型的类型参数,如果您想要返回动态对象,您可以简单地将其指定为对象。这是一个对象,其属性将在运行时绑定。
在这个例子中,我们知道我们的存储过程只是返回一个字符串,所以我们调用 ExecuteStoredProcedureAsync
以下是 Program.cs 文件的完整实现。
using Microsoft.Azure.Documents; 
using Microsoft.Azure.Documents.Client; 
using Microsoft.Azure.Documents.Linq; 
using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
 
namespace DocumentDBStoreProce { 
   class Program { 
      private static void Main(string[] args) { 
         Task.Run(async () => { 
            await SimpleStoredProcDemo(); 
         }).Wait(); 
      } 
	  
      private async static Task SimpleStoredProcDemo() {  
         var endpoint = "https://azuredocdbdemo.documents.azure.com:443/"; 
         var masterKey = 
            "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";  
				
         using (var client = new DocumentClient(new Uri(endpoint), masterKey)) { 
            // Get database 
            Database database = client 
               .CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'")
               .AsEnumerable() 
               .First(); 
					
            // Get collection 
            DocumentCollection collection = client 
               .CreateDocumentCollectionQuery(database.CollectionsLink, 
               "SELECT * FROM c WHERE c.id = 'MyCollection'") 
               .AsEnumerable() 
               .First();
					 
            // Create stored procedure 
            var sprocBody = File.ReadAllText(@"..\..\HelloWorldStoreProce.js"); 
				
            var sprocDefinition = new StoredProcedure { 
               Id = "HelloWorldStoreProce", 
               Body = sprocBody 
            };
			
            StoredProcedure sproc = await client
               .CreateStoredProcedureAsync(collection.SelfLink, sprocDefinition);
					
            Console.WriteLine("Created stored procedure {0} ({1})", sproc
               .Id, sproc.ResourceId);
					 
            // Execute stored procedure 
            var result = await client
               .ExecuteStoredProcedureAsync<string>(sproc.SelfLink); 
            Console.WriteLine("Executed stored procedure; response = {0}", 
               result.Response);
					
            // Delete stored procedure 
            await client.DeleteStoredProcedureAsync(sproc.SelfLink); 
            Console.WriteLine("Deleted stored procedure {0} ({1})", 
               sproc.Id, sproc.ResourceId); 
         } 
      } 
   } 
} 					
执行上述代码时,会产生以下输出。
Created stored procedure HelloWorldStoreProce (Ic8LAMEUVgACAAAAAAAAgA==)
Executed stored procedure; response = Hello, and welcome to DocumentDB!	 
如上面的输出所示,响应属性具有"您好,欢迎使用 DocumentDB!"由我们的存储过程返回。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4