-
Notifications
You must be signed in to change notification settings - Fork 97
Api for upserting #798
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Api for upserting #798
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,7 +4,12 @@ | |
|
|
||
| from piccolo.custom_types import TableInstance | ||
| from piccolo.query.base import Query | ||
| from piccolo.query.mixins import AddDelegate, ReturningDelegate | ||
| from piccolo.query.mixins import ( | ||
| AddDelegate, | ||
| OnConflict, | ||
| OnConflictDelegate, | ||
| ReturningDelegate, | ||
| ) | ||
| from piccolo.querystring import QueryString | ||
|
|
||
| if t.TYPE_CHECKING: # pragma: no cover | ||
|
|
@@ -15,14 +20,24 @@ | |
| class Insert( | ||
| t.Generic[TableInstance], Query[TableInstance, t.List[t.Dict[str, t.Any]]] | ||
| ): | ||
| __slots__ = ("add_delegate", "returning_delegate") | ||
| __slots__ = ( | ||
| "add_delegate", | ||
| "returning_delegate", | ||
| "on_conflict_delegate", | ||
| ) | ||
|
|
||
| def __init__( | ||
| self, table: t.Type[TableInstance], *instances: TableInstance, **kwargs | ||
| self, | ||
| table: t.Type[TableInstance], | ||
| on_conflict: t.Optional[OnConflict] = None, | ||
| *instances: TableInstance, | ||
| **kwargs, | ||
| ): | ||
| super().__init__(table, **kwargs) | ||
| self.add_delegate = AddDelegate() | ||
| self.returning_delegate = ReturningDelegate() | ||
| self.on_conflict_delegate = OnConflictDelegate() | ||
| self.on_conflict(on_conflict) # type: ignore | ||
| self.add(*instances) | ||
|
|
||
| ########################################################################### | ||
|
|
@@ -36,6 +51,10 @@ def returning(self: Self, *columns: Column) -> Self: | |
| self.returning_delegate.returning(columns) | ||
| return self | ||
|
|
||
| def on_conflict(self: Self, conflict: OnConflict) -> Self: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do you think we should allow the user to pass in specific columns? await Band.insert(Band(name="Pythonistas")).on_conflict(Band.name, do_nothing=True)If not specified, then we default to all columns.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If you look at the tests, even now the user can update one or more columns on |
||
| self.on_conflict_delegate.on_conflict(conflict) | ||
| return self | ||
|
|
||
| ########################################################################### | ||
|
|
||
| def _raw_response_callback(self, results): | ||
|
|
@@ -55,21 +74,55 @@ def _raw_response_callback(self, results): | |
|
|
||
| @property | ||
| def default_querystrings(self) -> t.Sequence[QueryString]: | ||
| base = f'INSERT INTO "{self.table._meta.tablename}"' | ||
| engine_type = self.engine_type | ||
| if ( | ||
| engine_type == "sqlite" | ||
| and self.table._meta.db.get_version_sync() < 3.24 | ||
| ): # pragma: no cover | ||
| if self.on_conflict_delegate._on_conflict == OnConflict.do_nothing: | ||
| base = f'INSERT OR IGNORE INTO "{self.table._meta.tablename}"' | ||
| elif ( | ||
| self.on_conflict_delegate._on_conflict == OnConflict.do_update | ||
| ): | ||
| base = f'INSERT OR REPLACE INTO "{self.table._meta.tablename}"' | ||
| else: | ||
| raise ValueError("Invalid on conflict value") | ||
| else: | ||
| base = f'INSERT INTO "{self.table._meta.tablename}"' | ||
| columns = ",".join( | ||
| f'"{i._meta.db_column_name}"' for i in self.table._meta.columns | ||
| ) | ||
| values = ",".join("{}" for _ in self.add_delegate._add) | ||
| query = f"{base} ({columns}) VALUES {values}" | ||
| if self.on_conflict_delegate._on_conflict is not None: | ||
| if self.on_conflict_delegate._on_conflict == OnConflict.do_nothing: | ||
| query = f""" | ||
| {base} ({columns}) VALUES {values} ON CONFLICT | ||
| {self.on_conflict_delegate._on_conflict.value} | ||
| """ | ||
| elif ( | ||
| self.on_conflict_delegate._on_conflict == OnConflict.do_update | ||
| ): | ||
| excluded_updated_columns = ", ".join( | ||
| f"{i._meta.db_column_name}=EXCLUDED.{i._meta.db_column_name}" # noqa: E501 | ||
| for i in self.table._meta.columns | ||
| ) | ||
| query = f""" | ||
| {base} ({columns}) VALUES {values} ON CONFLICT | ||
| ({self.table._meta.primary_key._meta.name}) | ||
| {self.on_conflict_delegate._on_conflict.value} | ||
| SET {excluded_updated_columns} | ||
| """ | ||
| else: | ||
| raise ValueError("Invalid on conflict value") | ||
| else: | ||
| query = f"{base} ({columns}) VALUES {values}" | ||
| querystring = QueryString( | ||
| query, | ||
| *[i.querystring for i in self.add_delegate._add], | ||
| query_type="insert", | ||
| table=self.table, | ||
| ) | ||
|
|
||
| engine_type = self.engine_type | ||
|
|
||
| if engine_type in ("postgres", "cockroach") or ( | ||
| engine_type == "sqlite" | ||
| and self.table._meta.db.get_version_sync() >= 3.35 | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would drop consider dropping this, and just using the
on_conflictmethod instead.The reason being, we can add extra arguments to the
on_conflictmethod in the future, but we don't want to add too many to__init__.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think we should change it, but feel free to do as you think is best. With this method, we can also easily solve the problem with duplicate entries in M2M. I'm sorry if I didn't understand well what you wanted to say and feel free to change this if you think
on_conflictas method would be better way.