Skip to content

Commit

Permalink
Check if DBs already exist instead of crashing
Browse files Browse the repository at this point in the history
Svaes time clearing all tables
  • Loading branch information
chennisden committed Jun 3, 2024
1 parent 943cd4d commit 8ead3e5
Showing 1 changed file with 26 additions and 21 deletions.
47 changes: 26 additions & 21 deletions store/app/api/crud/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import aioboto3
from types_aiobotocore_dynamodb.service_resource import DynamoDBServiceResource
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -40,7 +41,8 @@ async def _create_dynamodb_table(
gsis: list[tuple[str, str, Literal["S", "N", "B"], Literal["HASH", "RANGE"]]] = [],
deletion_protection: bool = False,
) -> None:
"""Creates a table in the Dynamo database.
"""Creates a table in the Dynamo database if a table of that name does
not already exist.
Args:
name: Name of the table.
Expand All @@ -52,23 +54,26 @@ async def _create_dynamodb_table(
deletion_protection: Whether the table is protected from being
deleted.
"""
logger.info("Creating %s table", name)
table = await self.db.create_table(
AttributeDefinitions=[
{"AttributeName": n, "AttributeType": t}
for n, t in itertools.chain(((n, t) for (n, t, _) in keys), ((n, t) for _, n, t, _ in gsis))
],
TableName=name,
KeySchema=[{"AttributeName": n, "KeyType": t} for n, _, t in keys],
GlobalSecondaryIndexes=[
{
"IndexName": i,
"KeySchema": [{"AttributeName": n, "KeyType": t}],
"Projection": {"ProjectionType": "ALL"},
}
for i, n, _, t in gsis
],
DeletionProtectionEnabled=deletion_protection,
BillingMode="PAY_PER_REQUEST",
)
await table.wait_until_exists()
try:
await self.db.meta.client.describe_table(TableName=name)
except ClientError as e:
logger.info("Creating %s table", name)
table = await self.db.create_table(
AttributeDefinitions=[
{"AttributeName": n, "AttributeType": t}
for n, t in itertools.chain(((n, t) for (n, t, _) in keys), ((n, t) for _, n, t, _ in gsis))
],
TableName=name,
KeySchema=[{"AttributeName": n, "KeyType": t} for n, _, t in keys],
GlobalSecondaryIndexes=[
{
"IndexName": i,
"KeySchema": [{"AttributeName": n, "KeyType": t}],
"Projection": {"ProjectionType": "ALL"},
}
for i, n, _, t in gsis
],
DeletionProtectionEnabled=deletion_protection,
BillingMode="PAY_PER_REQUEST",
)
await table.wait_until_exists()

0 comments on commit 8ead3e5

Please sign in to comment.