Skip to content

Commit

Permalink
DDL and some DML methods to m1 (#223)
Browse files Browse the repository at this point in the history
* list_collection_names method for [async]Database

* typing of async fixtures ok

* count_documents, insert_one, delete_one, delete_many
  • Loading branch information
hemidactylus authored Feb 28, 2024
1 parent d4c2308 commit ed88549
Show file tree
Hide file tree
Showing 16 changed files with 741 additions and 70 deletions.
40 changes: 40 additions & 0 deletions astrapy/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,26 @@ def delete_one(self, id: str) -> API_RESPONSE:

return response

def delete_one_filter(self, filter: Dict[str, Any]) -> API_RESPONSE:
"""
Delete a single document from the collection based on a filter clause
Args:
filter: any filter dictionary
Returns:
dict: The response from the database after the delete operation.
"""
json_query = {
"deleteOne": {
"filter": filter,
}
}

response = self._request(
method=http_methods.POST, path=f"{self.base_path}", json_data=json_query
)

return response

def delete_many(self, filter: Dict[str, Any]) -> API_RESPONSE:
"""
Delete many documents from the collection based on a filter condition
Expand Down Expand Up @@ -1909,6 +1929,26 @@ async def delete_one(self, id: str) -> API_RESPONSE:

return response

async def delete_one_filter(self, filter: Dict[str, Any]) -> API_RESPONSE:
"""
Delete a single document from the collection based on a filter clause
Args:
filter: any filter dictionary
Returns:
dict: The response from the database after the delete operation.
"""
json_query = {
"deleteOne": {
"filter": filter,
}
}

response = await self._request(
method=http_methods.POST, path=f"{self.base_path}", json_data=json_query
)

return response

async def delete_many(self, filter: Dict[str, Any]) -> API_RESPONSE:
"""
Delete many documents from the collection based on a filter condition
Expand Down
2 changes: 1 addition & 1 deletion astrapy/idiomatic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

__all__ = [
"AsyncCollection",
"Collection",
"AsyncDatabase",
"Collection",
"Database",
]
252 changes: 250 additions & 2 deletions astrapy/idiomatic/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

from typing import Any, Optional, TypedDict
import json
from typing import Any, Dict, Optional, TypedDict

from astrapy.db import AstraDBCollection, AsyncAstraDBCollection
from astrapy.idiomatic.utils import unsupported
from astrapy.idiomatic.utils import raise_unsupported_parameter, unsupported
from astrapy.idiomatic.database import AsyncDatabase, Database
from astrapy.idiomatic.results import DeleteResult, InsertOneResult


class CollectionConstructorParams(TypedDict):
Expand Down Expand Up @@ -90,6 +94,128 @@ def set_caller(
caller_version=caller_version,
)

def insert_one(
self,
document: Dict[str, Any],
*,
bypass_document_validation: Optional[bool] = None,
) -> InsertOneResult:
if bypass_document_validation:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="insert_one",
parameter_name="bypass_document_validation",
)
io_response = self._astra_db_collection.insert_one(document)
if "insertedIds" in io_response.get("status", {}):
if io_response["status"]["insertedIds"]:
inserted_id = io_response["status"]["insertedIds"][0]
return InsertOneResult(
inserted_id=inserted_id,
)
else:
raise ValueError(
"Could not complete a insert_one operation. "
f"(gotten '${json.dumps(io_response)}')"
)
else:
raise ValueError(
"Could not complete a insert_one operation. "
f"(gotten '${json.dumps(io_response)}')"
)

def count_documents(
self,
filter: Dict[str, Any],
*,
skip: Optional[int] = None,
limit: Optional[int] = None,
) -> int:
if skip:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="count_documents",
parameter_name="skip",
)
if limit:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="count_documents",
parameter_name="limit",
)
cd_response = self._astra_db_collection.count_documents(filter=filter)
if "count" in cd_response.get("status", {}):
return cd_response["status"]["count"] # type: ignore[no-any-return]
else:
raise ValueError(
"Could not complete a count_documents operation. "
f"(gotten '${json.dumps(cd_response)}')"
)

def delete_one(
self,
filter: Dict[str, Any],
*,
let: Optional[int] = None,
) -> DeleteResult:
if let:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="delete_one",
parameter_name="let",
)
do_response = self._astra_db_collection.delete_one_filter(filter=filter)
if "deletedCount" in do_response.get("status", {}):
deleted_count = do_response["status"]["deletedCount"]
if deleted_count == -1:
return DeleteResult(
deleted_count=None,
raw_result=do_response,
)
else:
# expected a non-negative integer:
return DeleteResult(
deleted_count=deleted_count,
raw_result=do_response,
)
else:
raise ValueError(
"Could not complete a delete_one operation. "
f"(gotten '${json.dumps(do_response)}')"
)

def delete_many(
self,
filter: Dict[str, Any],
*,
let: Optional[int] = None,
) -> DeleteResult:
if let:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="delete_many",
parameter_name="let",
)
dm_response = self._astra_db_collection.delete_many(filter=filter)
if "deletedCount" in dm_response.get("status", {}):
deleted_count = dm_response["status"]["deletedCount"]
if deleted_count == -1:
return DeleteResult(
deleted_count=None,
raw_result=dm_response,
)
else:
# expected a non-negative integer:
return DeleteResult(
deleted_count=deleted_count,
raw_result=dm_response,
)
else:
raise ValueError(
"Could not complete a delete_many operation. "
f"(gotten '${json.dumps(dm_response)}')"
)

@unsupported
def find_raw_batches(*pargs: Any, **kwargs: Any) -> Any: ...

Expand Down Expand Up @@ -197,6 +323,128 @@ def set_caller(
caller_version=caller_version,
)

async def insert_one(
self,
document: Dict[str, Any],
*,
bypass_document_validation: Optional[bool] = None,
) -> InsertOneResult:
if bypass_document_validation:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="insert_one",
parameter_name="bypass_document_validation",
)
io_response = await self._astra_db_collection.insert_one(document)
if "insertedIds" in io_response.get("status", {}):
if io_response["status"]["insertedIds"]:
inserted_id = io_response["status"]["insertedIds"][0]
return InsertOneResult(
inserted_id=inserted_id,
)
else:
raise ValueError(
"Could not complete a insert_one operation. "
f"(gotten '${json.dumps(io_response)}')"
)
else:
raise ValueError(
"Could not complete a insert_one operation. "
f"(gotten '${json.dumps(io_response)}')"
)

async def count_documents(
self,
filter: Dict[str, Any],
*,
skip: Optional[int] = None,
limit: Optional[int] = None,
) -> int:
if skip:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="count_documents",
parameter_name="skip",
)
if limit:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="count_documents",
parameter_name="limit",
)
cd_response = await self._astra_db_collection.count_documents(filter=filter)
if "count" in cd_response.get("status", {}):
return cd_response["status"]["count"] # type: ignore[no-any-return]
else:
raise ValueError(
"Could not complete a count_documents operation. "
f"(gotten '${json.dumps(cd_response)}')"
)

async def delete_one(
self,
filter: Dict[str, Any],
*,
let: Optional[int] = None,
) -> DeleteResult:
if let:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="delete_one",
parameter_name="let",
)
do_response = await self._astra_db_collection.delete_one_filter(filter=filter)
if "deletedCount" in do_response.get("status", {}):
deleted_count = do_response["status"]["deletedCount"]
if deleted_count == -1:
return DeleteResult(
deleted_count=None,
raw_result=do_response,
)
else:
# expected a non-negative integer:
return DeleteResult(
deleted_count=deleted_count,
raw_result=do_response,
)
else:
raise ValueError(
"Could not complete a delete_one operation. "
f"(gotten '${json.dumps(do_response)}')"
)

async def delete_many(
self,
filter: Dict[str, Any],
*,
let: Optional[int] = None,
) -> DeleteResult:
if let:
raise_unsupported_parameter(
class_name=self.__class__.__name__,
method_name="delete_many",
parameter_name="let",
)
dm_response = await self._astra_db_collection.delete_many(filter=filter)
if "deletedCount" in dm_response.get("status", {}):
deleted_count = dm_response["status"]["deletedCount"]
if deleted_count == -1:
return DeleteResult(
deleted_count=None,
raw_result=dm_response,
)
else:
# expected a non-negative integer:
return DeleteResult(
deleted_count=deleted_count,
raw_result=dm_response,
)
else:
raise ValueError(
"Could not complete a delete_many operation. "
f"(gotten '${json.dumps(dm_response)}')"
)

@unsupported
async def find_raw_batches(*pargs: Any, **kwargs: Any) -> Any: ...

Expand Down
Loading

0 comments on commit ed88549

Please sign in to comment.