Skip to content
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

feat: add max-affected and handling parameters in prefer header support #520

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion infra/docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
version: '3'
services:
rest:
image: postgrest/postgrest:v11.2.2
image: postgrest/postgrest:v12.2.3
ports:
- '3000:3000'
environment:
Expand Down
26 changes: 24 additions & 2 deletions postgrest/_async/request_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
pre_upsert,
)
from ..exceptions import APIError, generate_default_error_message
from ..types import ReturnMethod
from ..types import Handling, ReturnMethod
from ..utils import AsyncClient, get_origin_and_cast

_ReturnT = TypeVar("_ReturnT")
Expand Down Expand Up @@ -283,16 +283,20 @@ def select(
*columns: str,
count: Optional[CountMethod] = None,
head: Optional[bool] = None,
handling: Handling = Handling.lenient,
) -> AsyncSelectRequestBuilder[_ReturnT]:
"""Run a SELECT query.

Args:
*columns: The names of the columns to fetch.
count: The method to use to get the count of rows returned.
handling: Either 'lenient' or 'strict'
Returns:
:class:`AsyncSelectRequestBuilder`
"""
method, params, headers, json = pre_select(*columns, count=count, head=head)
method, params, headers, json = pre_select(
*columns, count=count, head=head, handling=handling
)
return AsyncSelectRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
)
Expand All @@ -305,6 +309,7 @@ def insert(
returning: ReturnMethod = ReturnMethod.representation,
upsert: bool = False,
default_to_null: bool = True,
handling: Handling = Handling.lenient,
) -> AsyncQueryRequestBuilder[_ReturnT]:
"""Run an INSERT query.

Expand All @@ -316,6 +321,7 @@ def insert(
default_to_null: Make missing fields default to `null`.
Otherwise, use the default value for the column.
Only applies for bulk inserts.
handling: Either 'lenient' or 'strict'
Returns:
:class:`AsyncQueryRequestBuilder`
"""
Expand All @@ -325,6 +331,7 @@ def insert(
returning=returning,
upsert=upsert,
default_to_null=default_to_null,
handling=handling,
)
return AsyncQueryRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
Expand All @@ -339,6 +346,7 @@ def upsert(
ignore_duplicates: bool = False,
on_conflict: str = "",
default_to_null: bool = True,
handling: Handling = Handling.lenient,
) -> AsyncQueryRequestBuilder[_ReturnT]:
"""Run an upsert (INSERT ... ON CONFLICT DO UPDATE) query.

Expand All @@ -352,6 +360,7 @@ def upsert(
default value for the column. This only applies when inserting new rows,
not when merging with existing rows under `ignoreDuplicates: false`.
This also only applies when doing bulk upserts.
handling: Either 'lenient' or 'strict'
Returns:
:class:`AsyncQueryRequestBuilder`
"""
Expand All @@ -362,6 +371,7 @@ def upsert(
ignore_duplicates=ignore_duplicates,
on_conflict=on_conflict,
default_to_null=default_to_null,
handling=handling,
)
return AsyncQueryRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
Expand All @@ -373,20 +383,26 @@ def update(
*,
count: Optional[CountMethod] = None,
returning: ReturnMethod = ReturnMethod.representation,
handling: Handling = Handling.lenient,
max_affected: Optional[int] = None,
) -> AsyncFilterRequestBuilder[_ReturnT]:
"""Run an UPDATE query.

Args:
json: The updated fields.
count: The method to use to get the count of rows returned.
returning: Either 'minimal' or 'representation'
handling: Either 'lenient' or 'strict'
max_affected: Limit of rows that can be affected during request. Working only with handling=strict.
Returns:
:class:`AsyncFilterRequestBuilder`
"""
method, params, headers, json = pre_update(
json,
count=count,
returning=returning,
handling=handling,
max_affected=max_affected,
)
return AsyncFilterRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
Expand All @@ -397,18 +413,24 @@ def delete(
*,
count: Optional[CountMethod] = None,
returning: ReturnMethod = ReturnMethod.representation,
handling: Handling = Handling.lenient,
max_affected: Optional[int] = None,
) -> AsyncFilterRequestBuilder[_ReturnT]:
"""Run a DELETE query.

Args:
count: The method to use to get the count of rows returned.
returning: Either 'minimal' or 'representation'
handling: Either 'lenient' or 'strict'
max_affected: Limit of rows that can be affected during request. Working only with handling=strict.
Returns:
:class:`AsyncFilterRequestBuilder`
"""
method, params, headers, json = pre_delete(
count=count,
returning=returning,
handling=handling,
max_affected=max_affected,
)
return AsyncFilterRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
Expand Down
28 changes: 25 additions & 3 deletions postgrest/_sync/request_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
pre_upsert,
)
from ..exceptions import APIError, generate_default_error_message
from ..types import ReturnMethod
from ..types import Handling, ReturnMethod
from ..utils import SyncClient, get_origin_and_cast

_ReturnT = TypeVar("_ReturnT")
Expand All @@ -34,7 +34,7 @@ def __init__(
http_method: str,
headers: Headers,
params: QueryParams,
json: Union[dict, list],
json: dict,
) -> None:
self.session = session
self.path = path
Expand Down Expand Up @@ -283,16 +283,20 @@ def select(
*columns: str,
count: Optional[CountMethod] = None,
head: Optional[bool] = None,
handling: Handling = Handling.lenient,
) -> SyncSelectRequestBuilder[_ReturnT]:
"""Run a SELECT query.

Args:
*columns: The names of the columns to fetch.
count: The method to use to get the count of rows returned.
handling: Either 'lenient' or 'strict'
Returns:
:class:`SyncSelectRequestBuilder`
"""
method, params, headers, json = pre_select(*columns, count=count, head=head)
method, params, headers, json = pre_select(
*columns, count=count, head=head, handling=handling
)
return SyncSelectRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
)
Expand All @@ -305,6 +309,7 @@ def insert(
returning: ReturnMethod = ReturnMethod.representation,
upsert: bool = False,
default_to_null: bool = True,
handling: Handling = Handling.lenient,
) -> SyncQueryRequestBuilder[_ReturnT]:
"""Run an INSERT query.

Expand All @@ -316,6 +321,7 @@ def insert(
default_to_null: Make missing fields default to `null`.
Otherwise, use the default value for the column.
Only applies for bulk inserts.
handling: Either 'lenient' or 'strict'
Returns:
:class:`SyncQueryRequestBuilder`
"""
Expand All @@ -325,6 +331,7 @@ def insert(
returning=returning,
upsert=upsert,
default_to_null=default_to_null,
handling=handling,
)
return SyncQueryRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
Expand All @@ -339,6 +346,7 @@ def upsert(
ignore_duplicates: bool = False,
on_conflict: str = "",
default_to_null: bool = True,
handling: Handling = Handling.lenient,
) -> SyncQueryRequestBuilder[_ReturnT]:
"""Run an upsert (INSERT ... ON CONFLICT DO UPDATE) query.

Expand All @@ -352,6 +360,7 @@ def upsert(
default value for the column. This only applies when inserting new rows,
not when merging with existing rows under `ignoreDuplicates: false`.
This also only applies when doing bulk upserts.
handling: Either 'lenient' or 'strict'
Returns:
:class:`SyncQueryRequestBuilder`
"""
Expand All @@ -362,6 +371,7 @@ def upsert(
ignore_duplicates=ignore_duplicates,
on_conflict=on_conflict,
default_to_null=default_to_null,
handling=handling,
)
return SyncQueryRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
Expand All @@ -373,20 +383,26 @@ def update(
*,
count: Optional[CountMethod] = None,
returning: ReturnMethod = ReturnMethod.representation,
handling: Handling = Handling.lenient,
max_affected: Optional[int] = None,
) -> SyncFilterRequestBuilder[_ReturnT]:
"""Run an UPDATE query.

Args:
json: The updated fields.
count: The method to use to get the count of rows returned.
returning: Either 'minimal' or 'representation'
handling: Either 'lenient' or 'strict'
max_affected: Limit of rows that can be affected during request. Working only with handling=strict.
Returns:
:class:`SyncFilterRequestBuilder`
"""
method, params, headers, json = pre_update(
json,
count=count,
returning=returning,
handling=handling,
max_affected=max_affected,
)
return SyncFilterRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
Expand All @@ -397,18 +413,24 @@ def delete(
*,
count: Optional[CountMethod] = None,
returning: ReturnMethod = ReturnMethod.representation,
handling: Handling = Handling.lenient,
max_affected: Optional[int] = None,
) -> SyncFilterRequestBuilder[_ReturnT]:
"""Run a DELETE query.

Args:
count: The method to use to get the count of rows returned.
returning: Either 'minimal' or 'representation'
handling: Either 'lenient' or 'strict'
max_affected: Limit of rows that can be affected during request. Working only with handling=strict.
Returns:
:class:`SyncFilterRequestBuilder`
"""
method, params, headers, json = pre_delete(
count=count,
returning=returning,
handling=handling,
max_affected=max_affected,
)
return SyncFilterRequestBuilder[_ReturnT](
self.session, self.path, method, headers, params, json
Expand Down
35 changes: 29 additions & 6 deletions postgrest/base_request_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
# < 2.0.0
from pydantic import validator as field_validator

from .types import CountMethod, Filters, RequestMethod, ReturnMethod
from .types import CountMethod, Filters, Handling, RequestMethod, ReturnMethod
from .utils import AsyncClient, SyncClient, get_origin_and_cast, sanitize_param


Expand Down Expand Up @@ -70,12 +70,16 @@ def pre_select(
*columns: str,
count: Optional[CountMethod] = None,
head: Optional[bool] = None,
handling: Handling = Handling.lenient,
) -> QueryArgs:
method = RequestMethod.HEAD if head else RequestMethod.GET
cleaned_columns = _cleaned_columns(columns or "*")
params = QueryParams({"select": cleaned_columns})

headers = Headers({"Prefer": f"count={count}"}) if count else Headers()
prefer_headers = [f"handling={handling}"]
if count:
prefer_headers.append(f"count={count}")
headers = Headers({"Prefer": ",".join(prefer_headers)})
return QueryArgs(method, params, headers, {})


Expand All @@ -86,8 +90,9 @@ def pre_insert(
returning: ReturnMethod,
upsert: bool,
default_to_null: bool = True,
handling: Handling = Handling.lenient,
) -> QueryArgs:
prefer_headers = [f"return={returning}"]
prefer_headers = [f"return={returning}", f"handling={handling}"]
if count:
prefer_headers.append(f"count={count}")
if upsert:
Expand All @@ -110,9 +115,13 @@ def pre_upsert(
ignore_duplicates: bool,
on_conflict: str = "",
default_to_null: bool = True,
handling: Handling = Handling.lenient,
) -> QueryArgs:
query_params = {}
prefer_headers = [f"return={returning}"]
prefer_headers = [
f"return={returning}",
f"handling={handling}",
]
if count:
prefer_headers.append(f"count={count}")
resolution = "ignore" if ignore_duplicates else "merge"
Expand All @@ -133,10 +142,17 @@ def pre_update(
*,
count: Optional[CountMethod],
returning: ReturnMethod,
handling: Handling = Handling.lenient,
max_affected: Optional[int] = None,
) -> QueryArgs:
prefer_headers = [f"return={returning}"]
prefer_headers = [
f"return={returning}",
f"handling={handling}",
]
if count:
prefer_headers.append(f"count={count}")
if max_affected and handling == handling.strict:
prefer_headers.append(f"max-affected={max_affected}")
headers = Headers({"Prefer": ",".join(prefer_headers)})
return QueryArgs(RequestMethod.PATCH, QueryParams(), headers, json)

Expand All @@ -145,10 +161,17 @@ def pre_delete(
*,
count: Optional[CountMethod],
returning: ReturnMethod,
handling: Handling = Handling.lenient,
max_affected: Optional[int] = None,
) -> QueryArgs:
prefer_headers = [f"return={returning}"]
prefer_headers = [
f"return={returning}",
f"handling={handling}",
]
if count:
prefer_headers.append(f"count={count}")
if max_affected and handling == handling.strict:
prefer_headers.append(f"max-affected={max_affected}")
headers = Headers({"Prefer": ",".join(prefer_headers)})
return QueryArgs(RequestMethod.DELETE, QueryParams(), headers, {})

Expand Down
5 changes: 5 additions & 0 deletions postgrest/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,8 @@ class RequestMethod(StrEnum):
class ReturnMethod(StrEnum):
minimal = "minimal"
representation = "representation"


class Handling(StrEnum):
lenient = "lenient"
strict = "strict"
Loading