0
# Entity Data Types
1
2
Data modeling capabilities for Azure Tables including entity representation, type-safe properties, metadata handling, and Entity Data Model (EDM) type specifications for precise data representation.
3
4
## Capabilities
5
6
### Table Entity
7
8
Dictionary-based entity representation with metadata support for Azure Tables operations.
9
10
```python { .api }
11
class TableEntity(dict):
12
"""
13
Table entity that extends dict with metadata support.
14
15
Inherits all dictionary methods and adds metadata handling.
16
PartitionKey and RowKey are required for all operations.
17
"""
18
19
metadata: EntityMetadata
20
21
def __init__(self, *args, **kwargs):
22
"""
23
Initialize TableEntity.
24
25
Can be initialized like a standard dictionary:
26
- TableEntity() - empty entity
27
- TableEntity({"key": "value"}) - from dict
28
- TableEntity(key="value") - from kwargs
29
"""
30
```
31
32
#### Usage Example
33
34
```python
35
from azure.data.tables import TableEntity
36
37
# Create empty entity
38
entity = TableEntity()
39
entity["PartitionKey"] = "customer"
40
entity["RowKey"] = "001"
41
entity["Name"] = "John Doe"
42
entity["Age"] = 30
43
44
# Create from dictionary
45
entity_data = {
46
"PartitionKey": "product",
47
"RowKey": "item001",
48
"Name": "Widget",
49
"Price": 29.99,
50
"InStock": True
51
}
52
entity = TableEntity(entity_data)
53
54
# Create with kwargs
55
entity = TableEntity(
56
PartitionKey="order",
57
RowKey="12345",
58
CustomerName="Jane Smith",
59
Total=149.99
60
)
61
62
# Access like dictionary
63
print(entity["Name"])
64
entity["Status"] = "Active"
65
66
# Access metadata after operations
67
print(f"ETag: {entity.metadata.get('etag')}")
68
print(f"Timestamp: {entity.metadata.get('timestamp')}")
69
```
70
71
### Entity Property
72
73
Explicitly typed entity property for precise data type control and EDM type specification.
74
75
```python { .api }
76
class EntityProperty(NamedTuple):
77
"""
78
Explicitly typed entity property.
79
80
Used when you need to specify exact EDM types for properties
81
instead of relying on automatic type inference.
82
"""
83
84
value: Any
85
edm_type: Union[str, EdmType]
86
```
87
88
#### Usage Example
89
90
```python
91
from azure.data.tables import TableEntity, EntityProperty, EdmType
92
from datetime import datetime
93
import uuid
94
95
# Create entity with explicit types
96
entity = TableEntity()
97
entity["PartitionKey"] = "typed"
98
entity["RowKey"] = "001"
99
100
# Explicit string type
101
entity["Description"] = EntityProperty("Product description", EdmType.STRING)
102
103
# Explicit datetime type
104
entity["Created"] = EntityProperty(datetime.utcnow(), EdmType.DATETIME)
105
106
# Explicit GUID type
107
entity["ProductId"] = EntityProperty(str(uuid.uuid4()), EdmType.GUID)
108
109
# Explicit binary data
110
entity["Thumbnail"] = EntityProperty(b"image_data", EdmType.BINARY)
111
112
# Large integer (beyond JavaScript int53 range)
113
entity["BigNumber"] = EntityProperty(9007199254740992, EdmType.INT64)
114
115
# Insert entity with explicit types
116
table_client.create_entity(entity)
117
```
118
119
### EDM Type System
120
121
Entity Data Model types for precise data representation in Azure Tables.
122
123
```python { .api }
124
class EdmType(Enum):
125
"""
126
Entity Data Model types for Table service.
127
128
These types ensure proper serialization and deserialization
129
of data between client and service.
130
"""
131
132
STRING = "Edm.String" # String data (default for str)
133
INT32 = "Edm.Int32" # 32-bit integer (default for int)
134
INT64 = "Edm.Int64" # 64-bit large integer
135
BOOLEAN = "Edm.Boolean" # Boolean value (default for bool)
136
DATETIME = "Edm.DateTime" # Date and time (default for datetime)
137
GUID = "Edm.Guid" # GUID/UUID identifier
138
BINARY = "Edm.Binary" # Binary data (default for bytes)
139
DOUBLE = "Edm.Double" # Double precision float (default for float)
140
```
141
142
#### Usage Example
143
144
```python
145
from azure.data.tables import TableEntity, EntityProperty, EdmType
146
from datetime import datetime
147
import uuid
148
149
entity = TableEntity()
150
entity["PartitionKey"] = "types"
151
entity["RowKey"] = "demo"
152
153
# String type (explicit)
154
entity["Name"] = EntityProperty("Product Name", EdmType.STRING)
155
156
# Integer types
157
entity["Quantity"] = EntityProperty(100, EdmType.INT32)
158
entity["SerialNumber"] = EntityProperty(1234567890123456789, EdmType.INT64)
159
160
# Boolean type
161
entity["IsActive"] = EntityProperty(True, EdmType.BOOLEAN)
162
163
# DateTime type
164
entity["CreatedAt"] = EntityProperty(datetime.utcnow(), EdmType.DATETIME)
165
166
# GUID type
167
entity["UniqueId"] = EntityProperty(str(uuid.uuid4()), EdmType.GUID)
168
169
# Binary type
170
entity["Data"] = EntityProperty(b"binary_content", EdmType.BINARY)
171
172
# Double precision float
173
entity["Price"] = EntityProperty(123.456789, EdmType.DOUBLE)
174
175
# When you retrieve the entity, types are preserved
176
retrieved = table_client.get_entity("types", "demo")
177
print(f"Price type: {type(retrieved['Price'])}") # float
178
```
179
180
### Entity Metadata
181
182
Metadata structure containing system-generated and service-managed entity information.
183
184
```python { .api }
185
class EntityMetadata(TypedDict):
186
"""
187
Metadata associated with table entities.
188
189
Automatically populated by Azure Tables service during operations.
190
Used for optimistic concurrency control and entity tracking.
191
"""
192
193
etag: Required[Optional[str]] # Entity tag for concurrency
194
timestamp: Required[Optional[datetime]] # Last modified timestamp
195
id: str # Entity ID (optional)
196
type: str # Type name (optional)
197
editLink: str # Edit link (optional)
198
```
199
200
#### Usage Example
201
202
```python
203
from azure.data.tables import TableClient, TableEntity
204
205
table_client = TableClient.from_connection_string(conn_str, "products")
206
207
# Create entity
208
entity = TableEntity(
209
PartitionKey="electronics",
210
RowKey="laptop001",
211
Name="Gaming Laptop",
212
Price=1299.99
213
)
214
215
# Insert entity
216
result = table_client.create_entity(entity)
217
print(f"Created with ETag: {result['etag']}")
218
219
# Retrieve entity with metadata
220
retrieved = table_client.get_entity("electronics", "laptop001")
221
222
# Access metadata
223
print(f"ETag: {retrieved.metadata['etag']}")
224
print(f"Last Modified: {retrieved.metadata['timestamp']}")
225
226
# Use ETag for optimistic concurrency
227
retrieved['Price'] = 1199.99
228
try:
229
table_client.update_entity(
230
retrieved,
231
etag=retrieved.metadata['etag'],
232
match_condition=MatchConditions.IfNotModified
233
)
234
print("Update successful")
235
except ResourceModifiedError:
236
print("Entity was modified by another process")
237
```
238
239
### Type Inference and Conversion
240
241
Automatic type inference rules and conversion behaviors for entity properties.
242
243
```python { .api }
244
# Automatic type mapping for common Python types:
245
#
246
# Python type -> EDM type
247
# str -> Edm.String
248
# int -> Edm.Int32 (if within range) or Edm.Int64
249
# float -> Edm.Double
250
# bool -> Edm.Boolean
251
# datetime -> Edm.DateTime
252
# bytes -> Edm.Binary
253
# uuid.UUID -> Edm.Guid (as string)
254
255
# Special values:
256
# None -> null property (omitted in some operations)
257
# Large integers -> Automatically promoted to Edm.Int64
258
```
259
260
#### Usage Example
261
262
```python
263
from azure.data.tables import TableEntity
264
from datetime import datetime
265
import uuid
266
267
# Automatic type inference
268
entity = TableEntity()
269
entity["PartitionKey"] = "auto"
270
entity["RowKey"] = "001"
271
272
# These will be automatically typed:
273
entity["Name"] = "Product" # -> Edm.String
274
entity["Count"] = 42 # -> Edm.Int32
275
entity["BigCount"] = 9007199254740992 # -> Edm.Int64
276
entity["Price"] = 99.99 # -> Edm.Double
277
entity["Active"] = True # -> Edm.Boolean
278
entity["Created"] = datetime.utcnow() # -> Edm.DateTime
279
entity["Data"] = b"bytes" # -> Edm.Binary
280
entity["Id"] = str(uuid.uuid4()) # -> Edm.String (not GUID)
281
282
# For GUID type, use explicit EntityProperty
283
entity["GuidId"] = EntityProperty(str(uuid.uuid4()), EdmType.GUID)
284
285
table_client.create_entity(entity)
286
```
287
288
### Advanced Entity Patterns
289
290
Common patterns for working with complex entity structures and data modeling.
291
292
#### Usage Example
293
294
```python
295
from azure.data.tables import TableEntity, EntityProperty, EdmType
296
from datetime import datetime
297
import json
298
299
# Complex entity with mixed types
300
order = TableEntity()
301
order["PartitionKey"] = f"order_{datetime.now().year}"
302
order["RowKey"] = "12345"
303
304
# Standard properties
305
order["CustomerName"] = "John Doe"
306
order["OrderDate"] = datetime.utcnow()
307
order["Total"] = 299.99
308
order["Status"] = "pending"
309
310
# JSON data as string
311
order_items = [
312
{"product": "Widget", "quantity": 2, "price": 99.99},
313
{"product": "Gadget", "quantity": 1, "price": 99.99}
314
]
315
order["Items"] = json.dumps(order_items)
316
317
# Large tracking number
318
order["TrackingNumber"] = EntityProperty(1234567890123456789, EdmType.INT64)
319
320
# Binary attachment
321
order["Invoice"] = EntityProperty(b"PDF_content", EdmType.BINARY)
322
323
table_client.create_entity(order)
324
325
# Retrieve and process
326
retrieved = table_client.get_entity(order["PartitionKey"], order["RowKey"])
327
items = json.loads(retrieved["Items"])
328
print(f"Order has {len(items)} items")
329
```
330
331
## Common Type Aliases
332
333
```python { .api }
334
# Type aliases used throughout the library
335
EntityType = Union[TableEntity, Mapping[str, Any]]
336
"""Entity can be TableEntity or any mapping (dict-like) object"""
337
338
OperationType = Union[TransactionOperation, str]
339
"""Operation type for batch transactions"""
340
341
TransactionOperationType = Union[
342
Tuple[OperationType, EntityType],
343
Tuple[OperationType, EntityType, Mapping[str, Any]]
344
]
345
"""Complete transaction operation specification with optional parameters"""
346
```