Skip to content

Commit

Permalink
database:base - add Table.insert_many method to insert multiple entries
Browse files Browse the repository at this point in the history
  • Loading branch information
MatteoCampinoti94 committed Nov 6, 2023
1 parent f183978 commit f2e17a7
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions acacore/database/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
from typing import Any
from typing import Generator
from typing import Generic
from typing import Iterator
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Type
from typing import TypeVar
from typing import Union
Expand Down Expand Up @@ -318,6 +320,24 @@ def insert(self, entry: dict[str, Any], exist_ok: bool = False, replace: bool =

self.connection.execute(" ".join(elements), values)

def insert_many(
self,
entries: Union[Sequence[dict[str, Any]], Iterator[dict[str, Any]]],
exist_ok: bool = False,
replace: bool = False,
):
"""
Insert multiple rows in the table. Existing rows with matching keys can be ignored or replaced.
Args:
entries: The rows to be inserted as a list (or iterator) of dicts with keys matching the names of
the columns. The values need not be converted beforehand.
exist_ok: True if existing rows with the same keys should be ignored, False otherwise
replace: True if existing rows with the same keys should be replaced, False otherwise.
"""
for entry in entries:
self.insert(entry, exist_ok, replace)


class ModelTable(Table, Generic[M]):
def __init__(self, connection: "FileDBBase", name: str, model: Type[M]) -> None:
Expand Down Expand Up @@ -385,6 +405,24 @@ def insert(self, entry: M, exist_ok: bool = False, replace: bool = False):
"""
super().insert(entry.model_dump(), exist_ok, replace)

def insert_many(
self,
entries: Union[Sequence[M], Iterator[M]],
exist_ok: bool = False,
replace: bool = False,
):
"""
Insert multiple rows in the table. Existing rows with matching keys can be ignored or replaced.
Args:
entries: The rows to be inserted as a list (or iterator) of model objects with attributes matching
the names of the columns.
exist_ok: True if existing rows with the same keys should be ignored, False otherwise
replace: True if existing rows with the same keys should be replaced, False otherwise.
"""
for entry in entries:
self.insert(entry, exist_ok, replace)


# noinspection SqlNoDataSourceInspection
class View(Table):
Expand Down Expand Up @@ -519,6 +557,13 @@ def insert(self, *_args, **_kwargs):
""" # noqa: D205
raise OperationalError("Cannot insert into view")

def insert_many(self, *_args, **_kwargs):
"""
Raises:
OperationalError: Insert transactions are not allowed on views.
""" # noqa: D205
raise OperationalError("Cannot insert into view")


class ModelView(View, Generic[M]):
def __init__(
Expand Down

0 comments on commit f2e17a7

Please sign in to comment.