DocumentDB 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函数,并且这些函数名称与Id匹配我们在DocumentDB的定义中设置了.

步骤9 : 调用 CreateStoredProcedureAsync ,传入 MyCollection 集合的 SelfLink 和存储过程定义.这将创建存储过程和DocumentDB分配给它的 ResourceId .

步骤10 : 调用存储过程. ExecuteStoredProcedureAsync 采用您设置为存储过程返回的值的预期数据类型的类型参数,如果要返回动态对象,则可以将其简单地指定为对象.这是一个对象,其属性将在运行时绑定.

在这个例子中,我们知道我们的存储过程只返回一个字符串,所以我们调用 ExecuteStoredProcedureAsync< string> .

以下是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!	

如上面的输出所示,响应属性的存储过程返回了"Hello,欢迎使用DocumentDB!".