【问题标题】:How do I run mutlple SQL statements in an AppSync resolver?如何在 AppSync 解析器中运行多个 SQL 语句?
【发布时间】:2019-03-11 16:07:52
【问题描述】:

我有两张桌子,cutsholds。为了响应我的应用程序中的事件,我希望能够将具有给定idhold 条目中的值移动到cuts 表中。天真的方法是先写一个INSERT,然后再写一个DELETE

如何在 AppSync 解析器中运行多个 sql 语句以实现该结果?我尝试了以下方法(将sql 替换为statements 并将其转换为数组)但没有成功。

{
 "version" : "2017-02-28",
 "operation": "Invoke",

 #set($id = $util.autoId())

"payload": {
    "statements": [
        "INSERT INTO cuts (id, rollId, length, reason, notes, orderId) SELECT '$id', rollId, length, reason, notes, orderId FROM holds WHERE id=:ID",
        "DELETE FROM holds WHERE id=:ID"
    ],
    "variableMapping": {
        ":ID": "$context.arguments.id"
    },
    "responseSQL": "SELECT * FROM cuts WHERE id = '$id'"
}

}

【问题讨论】:

    标签: amazon-web-services aws-appsync amazon-aurora


    【解决方案1】:

    如果您使用此处https://github.com/aws-samples/aws-appsync-rds-aurora-sample 的“AWS AppSync 使用 Amazon Aurora 作为数据源通过 AWS Lambda”,您将无法在 sql 字段中发送多个语句

    如果您使用 AWS AppSync 与 Aurora Serverless Data API 的集成,您最多可以在语句数组中传递 2 个语句,如下例所示:

    {
        "version": "2018-05-29",
        "statements": [
            "select * from Pets WHERE id='$ctx.args.input.id'",
            "delete from Pets WHERE id='$ctx.args.input.id'"
        ]
    }
    

    【讨论】:

    【解决方案2】:

    您将能够按照以下方式执行此操作。如果您使用的是“通过 AWS Lambda 使用 Amazon Aurora 作为数据源的 AWS AppSync”,请在此处找到 https://github.com/aws-samples/aws-appsync-rds-aurora-sample

    在解析器中,添加“sql0”和“sql1”字段(您可以随意命名):

    {
        "version" : "2017-02-28",
        "operation": "Invoke",
        #set($id = $util.autoId())
    
        "payload": {
          "sql":"INSERT INTO cuts (id, rollId, length, reason, notes, orderId)",
          "sql0":"SELECT '$id', rollId, length, reason, notes, orderId FROM holds WHERE id=:ID",
          "sql1":"DELETE FROM holds WHERE id=:ID",
          "variableMapping": {
                ":ID": "$context.arguments.id"
          },
          "responseSQL": "SELECT * FROM cuts WHERE id = '$id'"
        }
    }
    

    在您的 lambda 中,添加以下代码:

      if (event.sql0) {
      const inputSQL0 = populateAndSanitizeSQL(event.sql0, event.variableMapping, connection);
      await executeSQL(connection, inputSQL0);
      }
      if (event.sql1) {
      const inputSQL1 = populateAndSanitizeSQL(event.sql1, event.variableMapping, connection);
      await executeSQL(connection, inputSQL1);
      }
    

    通过这种方法,您可以向您的 lambda 发送任意数量的 sql 语句,然后您的 lambda 将执行它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多