Skip to content

Commit 8058047

Browse files
author
Harinath
committed
Revert "Added batch_save method to backend."
This reverts commit 0936be5.
1 parent 55ee0d8 commit 8058047

File tree

7 files changed

+8
-189
lines changed

7 files changed

+8
-189
lines changed

README.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,6 @@ NOTE: Rule complexity is limited by the querying capabilities of the backend.
5151

5252
`save()` - store the Model instance to the backend
5353

54-
`batch_save()` - store the List of Model instance to the backend
55-
5654
### DynamoDB
5755

5856
`get(key: Union[Dict, Any])`

pydanticrud/backends/dynamodb.py

Lines changed: 3 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
from ..main import IterableResult
1313
from ..exceptions import DoesNotExist, ConditionCheckFailed
14-
from ..dynamo_type_serializer import DynamoTypeSerializer
1514

1615
log = logging.getLogger(__name__)
1716

@@ -87,6 +86,7 @@ def _to_epoch_float(dt):
8786
"array": json.dumps,
8887
}
8988

89+
9090
DESERIALIZE_MAP = {
9191
"number": float,
9292
"boolean": bool,
@@ -95,10 +95,6 @@ def _to_epoch_float(dt):
9595
}
9696

9797

98-
def chunk_list(lst, size):
99-
return [lst[i: i + size] for i in range(0, len(lst), size)]
100-
101-
10298
def index_definition(index_name, keys, gsi=False):
10399
schema = {
104100
"IndexName": index_name,
@@ -114,10 +110,9 @@ def index_definition(index_name, keys, gsi=False):
114110
return schema
115111

116112

117-
class DynamoSerializer(DynamoTypeSerializer):
113+
class DynamoSerializer:
118114
def __init__(self, schema):
119-
super().__init__()
120-
self.properties = schema.get("properties")
115+
self.properties = schema["properties"]
121116
self.definitions = schema.get("definitions")
122117

123118
def _get_type_possibilities(self, field_name) -> Set[tuple]:
@@ -414,32 +409,3 @@ def save(self, item, condition: Optional[Rule] = None) -> bool:
414409

415410
def delete(self, key):
416411
self.get_table().delete_item(Key=self._key_param_to_dict(key))
417-
418-
def batch_save(self, items: list) -> dict:
419-
"""
420-
This function is to write multiple records in to dynamodb and returns unprocessed records in dict
421-
if something gone wrong with the record.This will by default try 3 time if any unprocessed
422-
records exists in result. Currently, batch_write is not supporting ConditionExpression
423-
Refer docs:
424-
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/batch_write_item.html
425-
"""
426-
# Prepare the batch write requests
427-
request_items = {self.table_name: []}
428-
429-
# chunk list for size limit of 25 items to write using this batch_write operation refer below.
430-
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/batch_write_item.html#:~:text=The%20BatchWriteItem%20operation,Data%20Types.
431-
for chunk in chunk_list(items, 20):
432-
serialized_items = [self.serializer.serialize_record(item.dict(by_alias=True)) for item in chunk]
433-
for serialized_item in serialized_items:
434-
request_items[self.table_name].append({"PutRequest":
435-
{"Item": serialized_item }#self.serializer.serialize_item(serialized_item)}
436-
})
437-
try:
438-
response = self.dynamodb.batch_write_item(RequestItems=request_items)
439-
except ClientError as e:
440-
raise e
441-
except (ValueError, TypeError, KeyError) as ex:
442-
raise ex
443-
unprocessed_items = response.get("UnprocessedItems", {})
444-
# Return any unprocessed items
445-
return unprocessed_items

pydanticrud/backends/sqlite.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,3 @@ def save(self, item, condition: Optional[Rule] = None) -> bool:
191191

192192
def delete(self, item_key: str):
193193
self._conn.execute(f"DELETE FROM {self.table_name} WHERE {self.hash_key} = ?;", [item_key])
194-
195-
def batch_save(self, items: dict):
196-
pass

pydanticrud/dynamo_type_serializer.py

Lines changed: 0 additions & 54 deletions
This file was deleted.

pydanticrud/main.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,3 @@ def save(self) -> bool:
7373
@classmethod
7474
def delete(cls, *args, **kwargs):
7575
cls.__backend__.delete(*args, **kwargs)
76-
77-
@classmethod
78-
def batch_save(cls, *args, **kwargs):
79-
return cls.__backend__.batch_save(*args, **kwargs)

tests/test_dynamo_type_serializer.py

Lines changed: 0 additions & 56 deletions
This file was deleted.

tests/test_dynamodb.py

Lines changed: 5 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import random
66

77
import docker
8-
from botocore.exceptions import ClientError
98
from pydantic import BaseModel as PydanticBaseModel, Field, root_validator, ValidationError
109
from pydanticrud import BaseModel, DynamoDbBackend, ConditionCheckFailed
1110
import pytest
@@ -67,7 +66,6 @@ class ComplexKeyModel(BaseModel):
6766
category_id: int
6867
notification_id: str
6968
thread_id: str
70-
body: str = 'some random string'
7169

7270
class Config:
7371
title = "ComplexModelTitle123"
@@ -398,7 +396,7 @@ def test_query_with_hash_key_complex(dynamo, complex_query_data):
398396

399397
@pytest.mark.parametrize('order', ('asc', 'desc'))
400398
def test_ordered_query_with_hash_key_complex(dynamo, complex_query_data, order):
401-
middle_record = complex_query_data[(len(complex_query_data) // 2)]
399+
middle_record = complex_query_data[(len(complex_query_data)//2)]
402400
res = ComplexKeyModel.query(
403401
Rule(f"account == '{middle_record['account']}' and sort_date_key >= '{middle_record['sort_date_key']}'"),
404402
order=order
@@ -416,9 +414,8 @@ def test_ordered_query_with_hash_key_complex(dynamo, complex_query_data, order):
416414
@pytest.mark.parametrize('order', ('asc', 'desc'))
417415
def test_pagination_query_with_hash_key_complex(dynamo, complex_query_data, order):
418416
page_size = 2
419-
middle_record = complex_query_data[(len(complex_query_data) // 2)]
420-
query_rule = Rule(
421-
f"account == '{middle_record['account']}' and sort_date_key >= '{middle_record['sort_date_key']}'")
417+
middle_record = complex_query_data[(len(complex_query_data)//2)]
418+
query_rule = Rule(f"account == '{middle_record['account']}' and sort_date_key >= '{middle_record['sort_date_key']}'")
422419
res = ComplexKeyModel.query(query_rule, order=order, limit=page_size)
423420
res_data = [(m.account, m.sort_date_key) for m in res]
424421
check_data = sorted([
@@ -435,13 +432,13 @@ def test_pagination_query_with_hash_key_complex(dynamo, complex_query_data, orde
435432
(m["account"], m["sort_date_key"])
436433
for m in complex_query_data
437434
if m["account"] == middle_record['account'] and m["sort_date_key"] >= middle_record['sort_date_key']
438-
], reverse=order == 'desc')[page_size:page_size * 2]
435+
], reverse=order == 'desc')[page_size:page_size*2]
439436
assert res_data == check_data
440437

441438

442439
def test_pagination_query_with_index_complex(dynamo, complex_query_data):
443440
page_size = 2
444-
middle_record = complex_query_data[(len(complex_query_data) // 2)]
441+
middle_record = complex_query_data[(len(complex_query_data)//2)]
445442
query_rule = Rule(f"account == '{middle_record['account']}' and category_id >= {middle_record['category_id']}")
446443
check_data = ComplexKeyModel.query(query_rule)
447444
res = ComplexKeyModel.query(query_rule, limit=page_size)
@@ -531,28 +528,3 @@ def test_alias_model_validator_ingest(dynamo):
531528
data.pop("typ")
532529
with pytest.raises(ValidationError):
533530
AliasKeyModel(**data)
534-
535-
536-
def test_batch_write(dynamo, complex_table):
537-
response = {"UnprocessedItems": {}}
538-
data = [
539-
ComplexKeyModel.parse_obj(complex_model_data_generator())
540-
for x in range(0, 10)
541-
]
542-
un_proc = ComplexKeyModel.batch_save(data)
543-
assert un_proc == response["UnprocessedItems"]
544-
res_get = ComplexKeyModel.get((data[0].account, data[0].sort_date_key))
545-
res_query = ComplexKeyModel.query(Rule(f"account == '{data[0].account}' and sort_date_key == '{data[0].sort_date_key}'"))
546-
assert res_get == data[0]
547-
assert res_query.count == 1
548-
assert res_query.records == [data[0]]
549-
550-
551-
def test_message_batch_write_client_exception(dynamo, complex_table):
552-
data = [
553-
ComplexKeyModel.parse_obj(complex_model_data_generator(body="some big string"*10000))
554-
for x in range(0, 2)
555-
]
556-
with pytest.raises(ClientError) as exc:
557-
ComplexKeyModel.batch_save(data)
558-
assert exc.value.response['Error']['Message'] == 'Item size has exceeded the maximum allowed size'

0 commit comments

Comments
 (0)