Skip to content

DynamoDBConfig

Bases: BaseModel, NameValidationMixin

Configuration model for DynamoDB table creation and management.

Comprehensive configuration model that defines all aspects of a DynamoDB table including key schema, indexes, streaming, and metadata. This model validates the complete table structure and ensures consistency between primary keys and secondary indexes.

Attributes:

Name Type Description
enable_stream bool

Enable DynamoDB Streams for change data capture

pk PartitionKey

Primary partition key configuration for item distribution

sk Optional[SortKey]

Optional sort key for composite primary keys and range queries

indexes Optional[Dict[str, GlobalSecondaryIndex]]

Global Secondary Index configurations for alternative access patterns

tag_key str

Primary tag key for backup and operational policies

tag_value str

Primary tag value for backup and operational policies

table_base_name str

Base identifier for the table following naming conventions

Source code in mare_aws_common_lib/models/dynamodb_config.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
class DynamoDBConfig(BaseModel, NameValidationMixin):
    """Configuration model for DynamoDB table creation and management.

    Comprehensive configuration model that defines all aspects of a DynamoDB
    table including key schema, indexes, streaming, and metadata. This model
    validates the complete table structure and ensures consistency between
    primary keys and secondary indexes.

    Attributes:
        enable_stream: Enable DynamoDB Streams for change data capture
        pk: Primary partition key configuration for item distribution
        sk: Optional sort key for composite primary keys and range queries
        indexes: Global Secondary Index configurations for alternative access patterns
        tag_key: Primary tag key for backup and operational policies
        tag_value: Primary tag value for backup and operational policies
        table_base_name: Base identifier for the table following naming conventions
    """

    model_config = ConfigDict(extra="forbid")

    enable_stream: bool = Field(False, description="Wether to enable DynamoDB Streams with NEW_AND_OLD_IMAGES view type")
    pk: PartitionKey = Field(..., description="Partition key configuration")
    sk: Optional[SortKey] = Field(None, description="Sort key configuration (optional)")
    indexes: Optional[Dict[str, GlobalSecondaryIndex]] = Field(
        None,
        description="Global secondary indexes configuration"
    )
    tag_key: str = Field(..., description="Tag key for backup strategy")
    tag_value: str = Field(..., description="Tag value for backup strategy")
    table_base_name: str = Field(..., min_length=1, description="Base name for the DynamoDB table")

    @field_validator('table_base_name')
    @classmethod
    def validate_table_name(cls, value: str) -> str:
        """Validate the DynamoDB table base name.

        Applies validation rules to table naming to ensure the 
        name meets AWS requirements and organizational standards.

        Args:
            value: Raw table base name from configuration

        Returns:
            Validated table base name

        Raises:
            ValueError: If the table name fails validation rules
        """
        return cls.validate_name(value)

    @model_validator(mode="after")
    def validate_table_structure(self) -> 'DynamoDBConfig':
        if self.sk:
            if self.sk.name == self.pk.name:
                raise ValueError("Sort key name cannot be the same as partition key name")

        if self.indexes:
            for index_name, index_config in self.indexes.items():
                if index_config.sk and index_config.sk.name == index_config.pk.name:
                    raise ValueError(f"Index '{index_name}': sort key name cannot be the same as partition key name")

        return self

validate_table_name(value) classmethod

Validate the DynamoDB table base name.

Applies validation rules to table naming to ensure the name meets AWS requirements and organizational standards.

Parameters:

Name Type Description Default
value str

Raw table base name from configuration

required

Returns:

Type Description
str

Validated table base name

Raises:

Type Description
ValueError

If the table name fails validation rules

Source code in mare_aws_common_lib/models/dynamodb_config.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
@field_validator('table_base_name')
@classmethod
def validate_table_name(cls, value: str) -> str:
    """Validate the DynamoDB table base name.

    Applies validation rules to table naming to ensure the 
    name meets AWS requirements and organizational standards.

    Args:
        value: Raw table base name from configuration

    Returns:
        Validated table base name

    Raises:
        ValueError: If the table name fails validation rules
    """
    return cls.validate_name(value)
Example
from mare_aws_common_lib.models import DynamoDBConfig

config = DynamoDBConfig(
    table_base_name="users-sessions",
    pk=PartitionKey(name="user_id", type=AttributeType.STRING),
    sk=SortKey(name="session_id", type=AttributeType.STRING),
    enable_stream=True,
    indexes={
        "status-index": GlobalSecondaryIndex(
            pk=PartitionKey(name="status", type=AttributeType.STRING),
            sk=SortKey(name="expires_at", type=AttributeType.NUMBER)
        )
    },
    tag_key="Environment",
    tag_value="Production"
)

AttributeType

Bases: str, Enum

DynamoDB attribute data types with CDK conversion support.

Represents the three fundamental attribute types supported by DynamoDB and provides conversion to CDK AttributeType constants for seamless integration with AWS CDK DynamoDB constructs.

Attributes:

Name Type Description
STRING

Text-based data type for strings and Unicode characters

NUMBER

Numeric data type for integers and floating-point numbers

BINARY

Binary data type for binary data, images, and compressed objects

Source code in mare_aws_common_lib/models/dynamodb_config.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class AttributeType(str, Enum):
    """DynamoDB attribute data types with CDK conversion support.

    Represents the three fundamental attribute types supported by DynamoDB
    and provides conversion to CDK AttributeType constants for seamless
    integration with AWS CDK DynamoDB constructs.

    Attributes:
        STRING: Text-based data type for strings and Unicode characters
        NUMBER: Numeric data type for integers and floating-point numbers  
        BINARY: Binary data type for binary data, images, and compressed objects
    """
    STRING = "STRING"
    NUMBER = "NUMBER"
    BINARY = "BINARY"

    @property
    def as_cdk(self) -> dynamodb.AttributeType:
        """CDK-compatible representation of the DynamoDB attribute type.

        Returns:
            CDK DynamoDB AttributeType constant matching this enum value
        """
        return {
            "STRING": dynamodb.AttributeType.STRING,
            "NUMBER": dynamodb.AttributeType.NUMBER,
            "BINARY": dynamodb.AttributeType.BINARY
        }[self.value]

as_cdk property

CDK-compatible representation of the DynamoDB attribute type.

Returns:

Type Description
AttributeType

CDK DynamoDB AttributeType constant matching this enum value

GlobalSecondaryIndex

Bases: BaseModel

Configuration model for DynamoDB Global Secondary Indexes (GSI).

Defines the structure of a Global Secondary Index, which provides alternative query patterns on a DynamoDB table. GSIs have their own partition key and optional sort key, independent of the base table.

Attributes:

Name Type Description
pk PartitionKey

Partition key configuration for the index

sk Optional[SortKey]

Optional sort key configuration for the index

Note

GSIs enable querying on different attributes than the main table's primary key, providing flexible access patterns for applications.

Source code in mare_aws_common_lib/models/dynamodb_config.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class GlobalSecondaryIndex(BaseModel):
    """Configuration model for DynamoDB Global Secondary Indexes (GSI).

    Defines the structure of a Global Secondary Index, which provides
    alternative query patterns on a DynamoDB table. GSIs have their own
    partition key and optional sort key, independent of the base table.

    Attributes:
        pk: Partition key configuration for the index
        sk: Optional sort key configuration for the index

    Note:
        GSIs enable querying on different attributes than the main table's
        primary key, providing flexible access patterns for applications.
    """
    model_config = ConfigDict(extra="forbid")
    pk: PartitionKey = Field(..., description="Partition key for the index")
    sk: Optional[SortKey] = Field(default=None, description="Sort key for the index (optional)")
Example
from mare_aws_common_lib.models import GlobalSecondaryIndex, AttributeType, PartitionKey, SortKey

gsi = GlobalSecondaryIndex(
    pk=PartitionKey(name="status", type=AttributeType.STRING),
    sk=SortKey(name="created_at", type=AttributeType.NUMBER)
)

PartitionKey

Bases: BaseModel

Configuration model for DynamoDB table partition keys.

Defines the partition key (primary key) structure for a DynamoDB table. The partition key determines how data is distributed across multiple partitions and is required for all DynamoDB tables.

Attributes:

Name Type Description
name str

Attribute name for the partition key (defaults to 'pk')

type AttributeType

Data type of the partition key attribute

Source code in mare_aws_common_lib/models/dynamodb_config.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class PartitionKey(BaseModel):
    """Configuration model for DynamoDB table partition keys.

    Defines the partition key (primary key) structure for a DynamoDB table.
    The partition key determines how data is distributed across multiple
    partitions and is required for all DynamoDB tables.

    Attributes:
        name: Attribute name for the partition key (defaults to 'pk')
        type: Data type of the partition key attribute
    """
    model_config = ConfigDict(extra="forbid")
    name: str = Field("pk", min_length=1, description="Name of the partition key")
    type: AttributeType = Field(..., description="Data type of the partition key")
Example
from mare_aws_common_lib.models import PartitionKey, AttributeType

pk = PartitionKey(name="user_id", type=AttributeType.STRING)

SortKey

Bases: BaseModel

Configuration model for DynamoDB table sort keys.

Defines the sort key (range key) structure for a DynamoDB table. Sort keys are optional and enable querying items with the same partition key in sorted order, creating composite primary keys.

Attributes:

Name Type Description
name str

Attribute name for the sort key (defaults to 'sk')

type AttributeType

Data type of the sort key attribute

Source code in mare_aws_common_lib/models/dynamodb_config.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class SortKey(BaseModel):
    """Configuration model for DynamoDB table sort keys.

    Defines the sort key (range key) structure for a DynamoDB table.
    Sort keys are optional and enable querying items with the same
    partition key in sorted order, creating composite primary keys.

    Attributes:
        name: Attribute name for the sort key (defaults to 'sk')
        type: Data type of the sort key attribute
    """
    model_config = ConfigDict(extra="forbid")
    name: str = Field("sk", min_length=1, description="Name of the sort key")
    type: AttributeType = Field(..., description="Data type of the sort key")
Example
from mare_aws_common_lib.models import SortKey, AttributeType

sk = SortKey(name="timestamp", type=AttributeType.NUMBER)