Wiz*_*Cat 9 php amazon-web-services nosql amazon-dynamodb
检查DynamoDb中是否存在表的最佳方法是什么?
如果代码是PHP,我将不胜感激.
无论是否有效.
*稍后作为示例添加到错误代码400的各种情况
检查表是否存在非常容易,它可以具有以下表之一:TableStatus => CREATING,ACTIVE,DELETING或UPDATING
但如果我得到错误400,它可能意味着不止一件事.
1)错误地将空字符串作为表名发送.
[x-aws-body] => {"TableName":""})
[body] => CFSimpleXML Object
    (
        [__type] => com.amazon.coral.validate#ValidationException
        [message] => The paramater 'tableName' must be at least 3 characters long and at most 255 characters long
    )
[status] => 400
2)发送到DynamoDB的命令中的语法错误,例如写入tabel_name而不是table_name.
[x-aws-body] => {"TabelName":"test7"})
[body] => CFSimpleXML Object
    (
        [__type] => com.amazon.coral.validate#ValidationException
        [message] => The paramater 'tableName' is required but was not present in the request
    )
[status] => 400
3)如果我同时超过表中的预配容量,我会猜测,但没有检查.
您可以查看官方PHP SDK的" describe_table ".400意味着" 不存在 "官方文档中有一个非常广泛的例子.看看它如何在"删除"示例中使用,就在底部.
这是doc中的(剥离)示例
<?php
require_once dirname(__FILE__) . '/sdk/sdk.class.php';
$dynamodb = new AmazonDynamoDB();
$table_name = 'ExampleTable';
$response = $dynamodb->describe_table(array('TableName' => $table_name));
if((integer) $response->status !== 400)
{
    $error_type = $response->body->__type;
    $error_code = explode('#', $error_type)[1];
    if($error_code == 'ResourceNotFoundException')
    {
        echo "Table ".$table_name." exists.";
    }
}
?>
其中一些答案是使用较旧的SDK,所以我想我会用我编码的内容更新这个有用的问题并且运行良好.较新的例外确实使这项任务更容易.这个函数为你提供了一个在脚本中使用的好的布尔值.
use Aws\DynamoDb\Exception\ResourceNotFoundException; // <-- make sure this line is at the top
    public function TableExists($tableName) {
    $ddb = DynamoDbClient::factory(array('region' => 'us-east-1')); // EC2 role security
    try {
        $result = $ddb->describeTable(array(
            "TableName" => $tableName
        ));
    } catch (ResourceNotFoundException $e) {
        // if this exception is thrown, the table doesn't exist
        return false;
    }
    // no exception thrown? table exists!
    return true;
}
希望这个完整的工作代码可以帮助你们.
我认为,随着解决了这个答案describeTable是一个很好的,但打打闹闹与状态码响应使代码的可读性和更混乱.
我选择使用检查表存在listTables.这是文档
$tableName = 'my_table';
$client = DynamoDbClient::factory(array('region' => 'us-west-2'));
$response = $client->listTables();
if (!in_array($tableName, $response['TableNames'])) {
    // handle non-existence.
    // throw an error if you want or whatever
}
// handle existence
echo "Table " . $tableName . " exists";
| 归档时间: | 
 | 
| 查看次数: | 11373 次 | 
| 最近记录: |