Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check if DBs already exist instead of crashing #40

Merged
merged 2 commits into from
Jun 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 25 additions & 21 deletions store/app/api/crud/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import Any, AsyncContextManager, Literal, Self

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

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -40,7 +41,7 @@ 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 +53,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:
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()
Loading