0
# Table Operations
1
2
Table-specific operations for entity management including CRUD operations, batch transactions, querying with filtering and pagination, and access policy management.
3
4
## Capabilities
5
6
### Table Client Initialization
7
8
Create and configure TableClient for table-specific operations with various authentication methods and initialization patterns.
9
10
```python { .api }
11
class TableClient:
12
def __init__(
13
self,
14
endpoint: str,
15
table_name: str,
16
*,
17
credential=None,
18
audience: str = None,
19
api_version: str = None,
20
**kwargs
21
):
22
"""
23
Initialize TableClient for table operations.
24
25
Parameters:
26
- endpoint: Full URL to the Tables account
27
- table_name: Name of the table
28
- credential: Authentication credential
29
- audience: Service audience for token authentication
30
- api_version: Storage API version to use
31
"""
32
33
@classmethod
34
def from_connection_string(
35
cls,
36
conn_str: str,
37
table_name: str,
38
**kwargs
39
) -> "TableClient":
40
"""
41
Create client from connection string.
42
43
Parameters:
44
- conn_str: Connection string with account credentials
45
- table_name: Name of the table
46
47
Returns:
48
TableClient instance
49
"""
50
51
@classmethod
52
def from_table_url(
53
cls,
54
table_url: str,
55
*,
56
credential=None,
57
**kwargs
58
) -> "TableClient":
59
"""
60
Create client from table URL.
61
62
Parameters:
63
- table_url: Complete URL to the table
64
- credential: Authentication credential
65
66
Returns:
67
TableClient instance
68
"""
69
```
70
71
#### Usage Example
72
73
```python
74
from azure.data.tables import TableClient
75
from azure.core.credentials import AzureNamedKeyCredential
76
77
# From connection string
78
table_client = TableClient.from_connection_string(
79
conn_str="DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey",
80
table_name="customers"
81
)
82
83
# From endpoint and credential
84
credential = AzureNamedKeyCredential("myaccount", "mykey")
85
table_client = TableClient(
86
endpoint="https://myaccount.table.core.windows.net/",
87
table_name="customers",
88
credential=credential
89
)
90
91
# From table URL
92
table_client = TableClient.from_table_url(
93
table_url="https://myaccount.table.core.windows.net/customers",
94
credential=credential
95
)
96
```
97
98
### Table Lifecycle Management
99
100
Create and delete tables directly through the table client.
101
102
```python { .api }
103
class TableClient:
104
def create_table(self, **kwargs) -> TableItem:
105
"""
106
Create the table.
107
108
Returns:
109
TableItem representing the created table
110
111
Raises:
112
ResourceExistsError: If table already exists
113
"""
114
115
def delete_table(self, **kwargs) -> None:
116
"""
117
Delete the table.
118
119
Raises:
120
ResourceNotFoundError: If table doesn't exist
121
"""
122
```
123
124
### Entity CRUD Operations
125
126
Complete Create, Read, Update, Delete operations for table entities with flexible entity representations.
127
128
```python { .api }
129
class TableClient:
130
def create_entity(
131
self,
132
entity: Union[TableEntity, Mapping[str, Any]],
133
**kwargs
134
) -> Dict[str, Any]:
135
"""
136
Insert a new entity into the table.
137
138
Parameters:
139
- entity: Entity data (TableEntity or dictionary)
140
141
Returns:
142
Dictionary with entity metadata including etag
143
144
Raises:
145
ResourceExistsError: If entity already exists
146
"""
147
148
def get_entity(
149
self,
150
partition_key: str,
151
row_key: str,
152
*,
153
select: List[str] = None,
154
**kwargs
155
) -> TableEntity:
156
"""
157
Retrieve a single entity by partition and row key.
158
159
Parameters:
160
- partition_key: Entity partition key
161
- row_key: Entity row key
162
- select: List of property names to return
163
164
Returns:
165
TableEntity with the requested entity data
166
167
Raises:
168
ResourceNotFoundError: If entity doesn't exist
169
"""
170
171
def update_entity(
172
self,
173
entity: Union[TableEntity, Mapping[str, Any]],
174
mode: UpdateMode = UpdateMode.MERGE,
175
**kwargs
176
) -> Dict[str, Any]:
177
"""
178
Update an existing entity.
179
180
Parameters:
181
- entity: Entity data with PartitionKey and RowKey
182
- mode: Update mode (MERGE or REPLACE)
183
184
Returns:
185
Dictionary with updated entity metadata
186
187
Raises:
188
ResourceNotFoundError: If entity doesn't exist
189
"""
190
191
def upsert_entity(
192
self,
193
entity: Union[TableEntity, Mapping[str, Any]],
194
mode: UpdateMode = UpdateMode.MERGE,
195
**kwargs
196
) -> Dict[str, Any]:
197
"""
198
Insert or update entity (upsert operation).
199
200
Parameters:
201
- entity: Entity data with PartitionKey and RowKey
202
- mode: Update mode for existing entities
203
204
Returns:
205
Dictionary with entity metadata
206
"""
207
208
def delete_entity(
209
self,
210
partition_key: str,
211
row_key: str,
212
*,
213
etag: Optional[str] = None,
214
match_condition: Optional[MatchConditions] = None,
215
**kwargs
216
) -> None:
217
"""
218
Delete an entity from the table using partition and row keys.
219
220
Parameters:
221
- partition_key: The partition key of the entity
222
- row_key: The row key of the entity
223
- etag: Optional etag for optimistic concurrency
224
- match_condition: Optional condition for conditional delete
225
226
Raises:
227
ResourceNotFoundError: If entity doesn't exist
228
"""
229
230
def delete_entity(
231
self,
232
entity: Union[TableEntity, Mapping[str, Any]],
233
*,
234
etag: Optional[str] = None,
235
match_condition: Optional[MatchConditions] = None,
236
**kwargs
237
) -> None:
238
"""
239
Delete an entity from the table using entity object.
240
241
Parameters:
242
- entity: Entity with PartitionKey and RowKey properties
243
- etag: Optional etag for optimistic concurrency (overrides entity etag)
244
- match_condition: Optional condition for conditional delete
245
246
Raises:
247
ResourceNotFoundError: If entity doesn't exist
248
"""
249
```
250
251
#### Usage Example
252
253
```python
254
from azure.data.tables import TableClient, TableEntity, UpdateMode
255
256
table_client = TableClient.from_connection_string(conn_str, "customers")
257
258
# Create entity
259
entity = TableEntity()
260
entity["PartitionKey"] = "customer"
261
entity["RowKey"] = "001"
262
entity["Name"] = "John Doe"
263
entity["Email"] = "john@example.com"
264
entity["Age"] = 30
265
266
result = table_client.create_entity(entity)
267
print(f"Created entity with etag: {result['etag']}")
268
269
# Get entity
270
retrieved = table_client.get_entity("customer", "001")
271
print(f"Name: {retrieved['Name']}")
272
273
# Update entity (merge)
274
retrieved["Age"] = 31
275
table_client.update_entity(retrieved, mode=UpdateMode.MERGE)
276
277
# Upsert entity
278
new_entity = {
279
"PartitionKey": "customer",
280
"RowKey": "002",
281
"Name": "Jane Smith",
282
"Email": "jane@example.com"
283
}
284
table_client.upsert_entity(new_entity)
285
286
# Delete entity by keys
287
table_client.delete_entity("customer", "001")
288
289
# Delete entity by object
290
table_client.delete_entity(retrieved)
291
```
292
293
### Entity Querying
294
295
Advanced querying capabilities with OData filters, pagination, and property selection.
296
297
```python { .api }
298
class TableClient:
299
def list_entities(
300
self,
301
*,
302
results_per_page: int = None,
303
select: List[str] = None,
304
**kwargs
305
) -> ItemPaged[TableEntity]:
306
"""
307
List all entities in the table.
308
309
Parameters:
310
- results_per_page: Maximum entities per page
311
- select: List of property names to return
312
313
Returns:
314
Paged iterator of TableEntity objects
315
"""
316
317
def query_entities(
318
self,
319
query_filter: str,
320
*,
321
results_per_page: int = None,
322
parameters: Dict[str, Any] = None,
323
select: List[str] = None,
324
**kwargs
325
) -> ItemPaged[TableEntity]:
326
"""
327
Query entities with OData filter expression.
328
329
Parameters:
330
- query_filter: OData filter expression
331
- results_per_page: Maximum results per page
332
- parameters: Parameter substitution values
333
- select: List of property names to return
334
335
Returns:
336
Paged iterator of matching TableEntity objects
337
"""
338
```
339
340
#### Usage Example
341
342
```python
343
from azure.data.tables import TableClient
344
345
table_client = TableClient.from_connection_string(conn_str, "customers")
346
347
# List all entities
348
for entity in table_client.list_entities():
349
print(f"Customer: {entity['Name']}")
350
351
# Query with filter
352
entities = table_client.query_entities(
353
query_filter="Age gt 25 and PartitionKey eq 'customer'",
354
select=["Name", "Email", "Age"]
355
)
356
357
for entity in entities:
358
print(f"Name: {entity['Name']}, Age: {entity['Age']}")
359
360
# Query with parameters
361
entities = table_client.query_entities(
362
query_filter="Age gt @age_limit",
363
parameters={"age_limit": 30}
364
)
365
366
# Paginated results
367
pages = table_client.query_entities(
368
query_filter="PartitionKey eq 'customer'",
369
results_per_page=10
370
)
371
372
for page in pages.by_page():
373
print(f"Page with {len(list(page))} entities")
374
```
375
376
### Batch Transactions
377
378
Execute multiple operations in a single atomic transaction for improved performance and consistency.
379
380
```python { .api }
381
class TableClient:
382
def submit_transaction(
383
self,
384
operations: Iterable[Union[
385
Tuple[str, Union[TableEntity, Mapping[str, Any]]],
386
Tuple[str, Union[TableEntity, Mapping[str, Any]], Mapping[str, Any]]
387
]],
388
**kwargs
389
) -> List[Mapping[str, Any]]:
390
"""
391
Submit a batch of operations as a single transaction.
392
393
Parameters:
394
- operations: List of (operation_type, entity) or (operation_type, entity, options) tuples
395
396
Operation types:
397
- "create": Insert new entity
398
- "update": Update existing entity
399
- "upsert": Insert or update entity
400
- "delete": Delete entity
401
402
Returns:
403
List of operation results
404
405
Raises:
406
TableTransactionError: If any operation fails
407
408
Note:
409
All entities in a batch must have the same PartitionKey
410
Maximum 100 operations per batch
411
"""
412
```
413
414
#### Usage Example
415
416
```python
417
from azure.data.tables import TableClient, UpdateMode
418
419
table_client = TableClient.from_connection_string(conn_str, "customers")
420
421
# Prepare batch operations
422
operations = [
423
("create", {
424
"PartitionKey": "batch",
425
"RowKey": "001",
426
"Name": "Customer 1"
427
}),
428
("create", {
429
"PartitionKey": "batch",
430
"RowKey": "002",
431
"Name": "Customer 2"
432
}),
433
("update", {
434
"PartitionKey": "batch",
435
"RowKey": "003",
436
"Name": "Updated Customer 3"
437
}, {"mode": UpdateMode.REPLACE}),
438
("delete", {
439
"PartitionKey": "batch",
440
"RowKey": "004"
441
})
442
]
443
444
# Submit transaction
445
try:
446
results = table_client.submit_transaction(operations)
447
print(f"Successfully processed {len(results)} operations")
448
except TableTransactionError as e:
449
print(f"Transaction failed at operation {e.index}: {e.message}")
450
```
451
452
### Access Policy Management
453
454
Manage stored access policies for table-level permissions and SAS token generation.
455
456
```python { .api }
457
class TableClient:
458
def get_table_access_policy(
459
self,
460
**kwargs
461
) -> Dict[str, Optional[TableAccessPolicy]]:
462
"""
463
Get stored access policies for the table.
464
465
Returns:
466
Dictionary mapping policy IDs to TableAccessPolicy objects
467
"""
468
469
def set_table_access_policy(
470
self,
471
signed_identifiers: Mapping[str, Optional[TableAccessPolicy]],
472
**kwargs
473
) -> None:
474
"""
475
Set stored access policies for the table.
476
477
Parameters:
478
- signed_identifiers: Dictionary mapping policy IDs to policies
479
Use None value to delete a policy
480
"""
481
```
482
483
#### Usage Example
484
485
```python
486
from azure.data.tables import TableClient, TableAccessPolicy
487
from datetime import datetime, timedelta
488
489
table_client = TableClient.from_connection_string(conn_str, "customers")
490
491
# Create access policy
492
policy = TableAccessPolicy(
493
start=datetime.utcnow(),
494
expiry=datetime.utcnow() + timedelta(hours=1),
495
permission="r" # read-only
496
)
497
498
# Set access policies
499
table_client.set_table_access_policy({
500
"read-policy": policy,
501
"old-policy": None # Delete this policy
502
})
503
504
# Get current policies
505
policies = table_client.get_table_access_policy()
506
for policy_id, policy in policies.items():
507
if policy:
508
print(f"Policy {policy_id}: {policy.permission}")
509
```
510
511
## Client Properties
512
513
```python { .api }
514
class TableClient:
515
@property
516
def account_name(self) -> str:
517
"""The name of the Tables account."""
518
519
@property
520
def table_name(self) -> str:
521
"""The name of the table."""
522
523
@property
524
def scheme(self) -> str:
525
"""The scheme component in the full URL."""
526
527
@property
528
def url(self) -> str:
529
"""The full endpoint URL to this table."""
530
531
@property
532
def api_version(self) -> str:
533
"""The version of the Storage API used for requests."""
534
535
@property
536
def credential(self):
537
"""The credentials with which to authenticate."""
538
```
539
540
## Data Models
541
542
```python { .api }
543
class UpdateMode(Enum):
544
"""Entity update modes."""
545
REPLACE = "replace" # Replace entire entity
546
MERGE = "merge" # Merge properties with existing entity
547
548
class TableAccessPolicy:
549
"""Access policy for shared access signatures."""
550
def __init__(
551
self,
552
start: Union[datetime, str] = None,
553
expiry: Union[datetime, str] = None,
554
permission: str = None
555
): ...
556
```