dynamo icon indicating copy to clipboard operation
dynamo copied to clipboard

add IfNotExists to CreateTable to easily skip table creation

Open guregu opened this issue 2 years ago • 1 comments

or maybe a flag like SkipIfExists, UpdateIfExists to try to match the input

guregu avatar Mar 23 '22 05:03 guregu

I have this small piece of code that does that, with the aws sdk, if it helps:

package database

import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
	"github.com/pkg/errors"
)

func TableExists(tableName string) (bool, error) {
	log.Printf("Validating table existence: %s", tableName)

	exists := true
	_, err := DbClient.DescribeTable(
		context.TODO(), &dynamodb.DescribeTableInput{TableName: aws.String(tableName)},
	)
	if err != nil {
		var notFoundEx *types.ResourceNotFoundException
		if errors.As(err, &notFoundEx) {
			log.Printf("Table %v does not exist.\n", tableName)
			err = nil
		} else {
			log.Printf("Couldn't determine existence of table %v. Here's why: %v\n", tableName, err)
		}
		exists = false
	}

	if exists {
		log.Printf("Table already exists. skipping...")
	}
	return exists, err
}


pedrohba1 avatar Mar 08 '23 14:03 pedrohba1