Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|> with pytest.raises(LocalProtocolError):
validate(my_re, b"0.")
groups = validate(my_re, b"0.1")
assert groups == {"group1": b"0", "group2": b"1"}
# successful partial matches are an error - must match whole string
with pytest.raises(LocalProtocolError):
validate(my_re, b"0.1xx")
with pytest.raises(LocalProtocolError):
validate(my_re, b"0.1\n")
def test_validate_formatting() -> None:
my_re = re.compile(br"foo")
with pytest.raises(LocalProtocolError) as excinfo:
validate(my_re, b"", "oops")
assert "oops" in str(excinfo.value)
with pytest.raises(LocalProtocolError) as excinfo:
validate(my_re, b"", "oops {}")
assert "oops {}" in str(excinfo.value)
with pytest.raises(LocalProtocolError) as excinfo:
validate(my_re, b"", "oops {} xx", 10)
assert "oops 10 xx" in str(excinfo.value)
def test_make_sentinel() -> None:
<|code_end|>
with the help of current file imports:
import re
import sys
import traceback
import pytest
from typing import NoReturn
from .._util import (
bytesify,
LocalProtocolError,
ProtocolError,
RemoteProtocolError,
Sentinel,
validate,
)
and context from other files:
# Path: h11/_util.py
# def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
# # Fast-path:
# if type(s) is bytes:
# return s
# if isinstance(s, str):
# s = s.encode("ascii")
# if isinstance(s, int):
# raise TypeError("expected bytes-like object, not int")
# return bytes(s)
#
# class LocalProtocolError(ProtocolError):
# def _reraise_as_remote_protocol_error(self) -> NoReturn:
# # After catching a LocalProtocolError, use this method to re-raise it
# # as a RemoteProtocolError. This method must be called from inside an
# # except: block.
# #
# # An easy way to get an equivalent RemoteProtocolError is just to
# # modify 'self' in place.
# self.__class__ = RemoteProtocolError # type: ignore
# # But the re-raising is somewhat non-trivial -- you might think that
# # now that we've modified the in-flight exception object, that just
# # doing 'raise' to re-raise it would be enough. But it turns out that
# # this doesn't work, because Python tracks the exception type
# # (exc_info[0]) separately from the exception object (exc_info[1]),
# # and we only modified the latter. So we really do need to re-raise
# # the new type explicitly.
# # On py3, the traceback is part of the exception object, so our
# # in-place modification preserved it and we can just re-raise:
# raise self
#
# class ProtocolError(Exception):
# """Exception indicating a violation of the HTTP/1.1 protocol.
#
# This as an abstract base class, with two concrete base classes:
# :exc:`LocalProtocolError`, which indicates that you tried to do something
# that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which
# indicates that the remote peer tried to do something that HTTP/1.1 says is
# illegal. See :ref:`error-handling` for details.
#
# In addition to the normal :exc:`Exception` features, it has one attribute:
#
# .. attribute:: error_status_hint
#
# This gives a suggestion as to what status code a server might use if
# this error occurred as part of a request.
#
# For a :exc:`RemoteProtocolError`, this is useful as a suggestion for
# how you might want to respond to a misbehaving peer, if you're
# implementing a server.
#
# For a :exc:`LocalProtocolError`, this can be taken as a suggestion for
# how your peer might have responded to *you* if h11 had allowed you to
# continue.
#
# The default is 400 Bad Request, a generic catch-all for protocol
# violations.
#
# """
#
# def __init__(self, msg: str, error_status_hint: int = 400) -> None:
# if type(self) is ProtocolError:
# raise TypeError("tried to directly instantiate ProtocolError")
# Exception.__init__(self, msg)
# self.error_status_hint = error_status_hint
#
# class RemoteProtocolError(ProtocolError):
# pass
#
# class Sentinel(type):
# def __new__(
# cls: Type[_T_Sentinel],
# name: str,
# bases: Tuple[type, ...],
# namespace: Dict[str, Any],
# **kwds: Any
# ) -> _T_Sentinel:
# assert bases == (Sentinel,)
# v = super().__new__(cls, name, bases, namespace, **kwds)
# v.__class__ = v # type: ignore
# return v
#
# def __repr__(self) -> str:
# return self.__name__
#
# def validate(
# regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
# ) -> Dict[str, bytes]:
# match = regex.fullmatch(data)
# if not match:
# if format_args:
# msg = msg.format(*format_args)
# raise LocalProtocolError(msg)
# return match.groupdict()
, which may contain function names, class names, or code. Output only the next line. | class S(Sentinel, metaclass=Sentinel): |
Given the code snippet: <|code_start|> except LocalProtocolError as e:
assert str(e) == "foo"
assert e.error_status_hint == 400
try:
raise LocalProtocolError("foo", error_status_hint=418)
except LocalProtocolError as e:
assert str(e) == "foo"
assert e.error_status_hint == 418
def thunk() -> NoReturn:
raise LocalProtocolError("a", error_status_hint=420)
try:
try:
thunk()
except LocalProtocolError as exc1:
orig_traceback = "".join(traceback.format_tb(sys.exc_info()[2]))
exc1._reraise_as_remote_protocol_error()
except RemoteProtocolError as exc2:
assert type(exc2) is RemoteProtocolError
assert exc2.args == ("a",)
assert exc2.error_status_hint == 420
new_traceback = "".join(traceback.format_tb(sys.exc_info()[2]))
assert new_traceback.endswith(orig_traceback)
def test_validate() -> None:
my_re = re.compile(br"(?P<group1>[0-9]+)\.(?P<group2>[0-9]+)")
with pytest.raises(LocalProtocolError):
<|code_end|>
, generate the next line using the imports in this file:
import re
import sys
import traceback
import pytest
from typing import NoReturn
from .._util import (
bytesify,
LocalProtocolError,
ProtocolError,
RemoteProtocolError,
Sentinel,
validate,
)
and context (functions, classes, or occasionally code) from other files:
# Path: h11/_util.py
# def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
# # Fast-path:
# if type(s) is bytes:
# return s
# if isinstance(s, str):
# s = s.encode("ascii")
# if isinstance(s, int):
# raise TypeError("expected bytes-like object, not int")
# return bytes(s)
#
# class LocalProtocolError(ProtocolError):
# def _reraise_as_remote_protocol_error(self) -> NoReturn:
# # After catching a LocalProtocolError, use this method to re-raise it
# # as a RemoteProtocolError. This method must be called from inside an
# # except: block.
# #
# # An easy way to get an equivalent RemoteProtocolError is just to
# # modify 'self' in place.
# self.__class__ = RemoteProtocolError # type: ignore
# # But the re-raising is somewhat non-trivial -- you might think that
# # now that we've modified the in-flight exception object, that just
# # doing 'raise' to re-raise it would be enough. But it turns out that
# # this doesn't work, because Python tracks the exception type
# # (exc_info[0]) separately from the exception object (exc_info[1]),
# # and we only modified the latter. So we really do need to re-raise
# # the new type explicitly.
# # On py3, the traceback is part of the exception object, so our
# # in-place modification preserved it and we can just re-raise:
# raise self
#
# class ProtocolError(Exception):
# """Exception indicating a violation of the HTTP/1.1 protocol.
#
# This as an abstract base class, with two concrete base classes:
# :exc:`LocalProtocolError`, which indicates that you tried to do something
# that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which
# indicates that the remote peer tried to do something that HTTP/1.1 says is
# illegal. See :ref:`error-handling` for details.
#
# In addition to the normal :exc:`Exception` features, it has one attribute:
#
# .. attribute:: error_status_hint
#
# This gives a suggestion as to what status code a server might use if
# this error occurred as part of a request.
#
# For a :exc:`RemoteProtocolError`, this is useful as a suggestion for
# how you might want to respond to a misbehaving peer, if you're
# implementing a server.
#
# For a :exc:`LocalProtocolError`, this can be taken as a suggestion for
# how your peer might have responded to *you* if h11 had allowed you to
# continue.
#
# The default is 400 Bad Request, a generic catch-all for protocol
# violations.
#
# """
#
# def __init__(self, msg: str, error_status_hint: int = 400) -> None:
# if type(self) is ProtocolError:
# raise TypeError("tried to directly instantiate ProtocolError")
# Exception.__init__(self, msg)
# self.error_status_hint = error_status_hint
#
# class RemoteProtocolError(ProtocolError):
# pass
#
# class Sentinel(type):
# def __new__(
# cls: Type[_T_Sentinel],
# name: str,
# bases: Tuple[type, ...],
# namespace: Dict[str, Any],
# **kwds: Any
# ) -> _T_Sentinel:
# assert bases == (Sentinel,)
# v = super().__new__(cls, name, bases, namespace, **kwds)
# v.__class__ = v # type: ignore
# return v
#
# def __repr__(self) -> str:
# return self.__name__
#
# def validate(
# regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
# ) -> Dict[str, bytes]:
# match = regex.fullmatch(data)
# if not match:
# if format_args:
# msg = msg.format(*format_args)
# raise LocalProtocolError(msg)
# return match.groupdict()
. Output only the next line. | validate(my_re, b"0.") |
Predict the next line for this snippet: <|code_start|># "a proxy MUST NOT change the order of these field values when forwarding a
# message"
# (and there are several headers where the order indicates a preference)
#
# Multiple occurences of the same header:
# "A sender MUST NOT generate multiple header fields with the same field name
# in a message unless either the entire field value for that header field is
# defined as a comma-separated list [or the header is Set-Cookie which gets a
# special exception]" - RFC 7230. (cookies are in RFC 6265)
#
# So every header aside from Set-Cookie can be merged by b", ".join if it
# occurs repeatedly. But, of course, they can't necessarily be split by
# .split(b","), because quoting.
#
# Given all this mess (case insensitive, duplicates allowed, order is
# important, ...), there doesn't appear to be any standard way to handle
# headers in Python -- they're almost like dicts, but... actually just
# aren't. For now we punt and just use a super simple representation: headers
# are a list of pairs
#
# [(name1, value1), (name2, value2), ...]
#
# where all entries are bytestrings, names are lowercase and have no
# leading/trailing whitespace, and values are bytestrings with no
# leading/trailing whitespace. Searching and updating are done via naive O(n)
# methods.
#
# Maybe a dict-of-lists would be better?
_content_length_re = re.compile(br"[0-9]+")
<|code_end|>
with the help of current file imports:
import re
from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
from ._abnf import field_name, field_value
from ._util import bytesify, LocalProtocolError, validate
from ._events import Request
from typing import Literal
from typing_extensions import Literal # type: ignore
and context from other files:
# Path: h11/_abnf.py
# OWS = r"[ \t]*"
# HEXDIG = r"[0-9A-Fa-f]"
#
# Path: h11/_util.py
# def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
# # Fast-path:
# if type(s) is bytes:
# return s
# if isinstance(s, str):
# s = s.encode("ascii")
# if isinstance(s, int):
# raise TypeError("expected bytes-like object, not int")
# return bytes(s)
#
# class LocalProtocolError(ProtocolError):
# def _reraise_as_remote_protocol_error(self) -> NoReturn:
# # After catching a LocalProtocolError, use this method to re-raise it
# # as a RemoteProtocolError. This method must be called from inside an
# # except: block.
# #
# # An easy way to get an equivalent RemoteProtocolError is just to
# # modify 'self' in place.
# self.__class__ = RemoteProtocolError # type: ignore
# # But the re-raising is somewhat non-trivial -- you might think that
# # now that we've modified the in-flight exception object, that just
# # doing 'raise' to re-raise it would be enough. But it turns out that
# # this doesn't work, because Python tracks the exception type
# # (exc_info[0]) separately from the exception object (exc_info[1]),
# # and we only modified the latter. So we really do need to re-raise
# # the new type explicitly.
# # On py3, the traceback is part of the exception object, so our
# # in-place modification preserved it and we can just re-raise:
# raise self
#
# def validate(
# regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
# ) -> Dict[str, bytes]:
# match = regex.fullmatch(data)
# if not match:
# if format_args:
# msg = msg.format(*format_args)
# raise LocalProtocolError(msg)
# return match.groupdict()
, which may contain function names, class names, or code. Output only the next line. | _field_name_re = re.compile(field_name.encode("ascii")) |
Given snippet: <|code_start|># message"
# (and there are several headers where the order indicates a preference)
#
# Multiple occurences of the same header:
# "A sender MUST NOT generate multiple header fields with the same field name
# in a message unless either the entire field value for that header field is
# defined as a comma-separated list [or the header is Set-Cookie which gets a
# special exception]" - RFC 7230. (cookies are in RFC 6265)
#
# So every header aside from Set-Cookie can be merged by b", ".join if it
# occurs repeatedly. But, of course, they can't necessarily be split by
# .split(b","), because quoting.
#
# Given all this mess (case insensitive, duplicates allowed, order is
# important, ...), there doesn't appear to be any standard way to handle
# headers in Python -- they're almost like dicts, but... actually just
# aren't. For now we punt and just use a super simple representation: headers
# are a list of pairs
#
# [(name1, value1), (name2, value2), ...]
#
# where all entries are bytestrings, names are lowercase and have no
# leading/trailing whitespace, and values are bytestrings with no
# leading/trailing whitespace. Searching and updating are done via naive O(n)
# methods.
#
# Maybe a dict-of-lists would be better?
_content_length_re = re.compile(br"[0-9]+")
_field_name_re = re.compile(field_name.encode("ascii"))
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
from ._abnf import field_name, field_value
from ._util import bytesify, LocalProtocolError, validate
from ._events import Request
from typing import Literal
from typing_extensions import Literal # type: ignore
and context:
# Path: h11/_abnf.py
# OWS = r"[ \t]*"
# HEXDIG = r"[0-9A-Fa-f]"
#
# Path: h11/_util.py
# def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
# # Fast-path:
# if type(s) is bytes:
# return s
# if isinstance(s, str):
# s = s.encode("ascii")
# if isinstance(s, int):
# raise TypeError("expected bytes-like object, not int")
# return bytes(s)
#
# class LocalProtocolError(ProtocolError):
# def _reraise_as_remote_protocol_error(self) -> NoReturn:
# # After catching a LocalProtocolError, use this method to re-raise it
# # as a RemoteProtocolError. This method must be called from inside an
# # except: block.
# #
# # An easy way to get an equivalent RemoteProtocolError is just to
# # modify 'self' in place.
# self.__class__ = RemoteProtocolError # type: ignore
# # But the re-raising is somewhat non-trivial -- you might think that
# # now that we've modified the in-flight exception object, that just
# # doing 'raise' to re-raise it would be enough. But it turns out that
# # this doesn't work, because Python tracks the exception type
# # (exc_info[0]) separately from the exception object (exc_info[1]),
# # and we only modified the latter. So we really do need to re-raise
# # the new type explicitly.
# # On py3, the traceback is part of the exception object, so our
# # in-place modification preserved it and we can just re-raise:
# raise self
#
# def validate(
# regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
# ) -> Dict[str, bytes]:
# match = regex.fullmatch(data)
# if not match:
# if format_args:
# msg = msg.format(*format_args)
# raise LocalProtocolError(msg)
# return match.groupdict()
which might include code, classes, or functions. Output only the next line. | _field_value_re = re.compile(field_value.encode("ascii")) |
Predict the next line for this snippet: <|code_start|>
@overload
def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers:
...
@overload
def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers:
...
@overload
def normalize_and_validate(
headers: Union[Headers, HeaderTypes], _parsed: bool = False
) -> Headers:
...
def normalize_and_validate(
headers: Union[Headers, HeaderTypes], _parsed: bool = False
) -> Headers:
new_headers = []
seen_content_length = None
saw_transfer_encoding = False
for name, value in headers:
# For headers coming out of the parser, we can safely skip some steps,
# because it always returns bytes and has already run these regexes
# over the data:
if not _parsed:
<|code_end|>
with the help of current file imports:
import re
from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
from ._abnf import field_name, field_value
from ._util import bytesify, LocalProtocolError, validate
from ._events import Request
from typing import Literal
from typing_extensions import Literal # type: ignore
and context from other files:
# Path: h11/_abnf.py
# OWS = r"[ \t]*"
# HEXDIG = r"[0-9A-Fa-f]"
#
# Path: h11/_util.py
# def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
# # Fast-path:
# if type(s) is bytes:
# return s
# if isinstance(s, str):
# s = s.encode("ascii")
# if isinstance(s, int):
# raise TypeError("expected bytes-like object, not int")
# return bytes(s)
#
# class LocalProtocolError(ProtocolError):
# def _reraise_as_remote_protocol_error(self) -> NoReturn:
# # After catching a LocalProtocolError, use this method to re-raise it
# # as a RemoteProtocolError. This method must be called from inside an
# # except: block.
# #
# # An easy way to get an equivalent RemoteProtocolError is just to
# # modify 'self' in place.
# self.__class__ = RemoteProtocolError # type: ignore
# # But the re-raising is somewhat non-trivial -- you might think that
# # now that we've modified the in-flight exception object, that just
# # doing 'raise' to re-raise it would be enough. But it turns out that
# # this doesn't work, because Python tracks the exception type
# # (exc_info[0]) separately from the exception object (exc_info[1]),
# # and we only modified the latter. So we really do need to re-raise
# # the new type explicitly.
# # On py3, the traceback is part of the exception object, so our
# # in-place modification preserved it and we can just re-raise:
# raise self
#
# def validate(
# regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
# ) -> Dict[str, bytes]:
# match = regex.fullmatch(data)
# if not match:
# if format_args:
# msg = msg.format(*format_args)
# raise LocalProtocolError(msg)
# return match.groupdict()
, which may contain function names, class names, or code. Output only the next line. | name = bytesify(name) |
Based on the snippet: <|code_start|>@overload
def normalize_and_validate(
headers: Union[Headers, HeaderTypes], _parsed: bool = False
) -> Headers:
...
def normalize_and_validate(
headers: Union[Headers, HeaderTypes], _parsed: bool = False
) -> Headers:
new_headers = []
seen_content_length = None
saw_transfer_encoding = False
for name, value in headers:
# For headers coming out of the parser, we can safely skip some steps,
# because it always returns bytes and has already run these regexes
# over the data:
if not _parsed:
name = bytesify(name)
value = bytesify(value)
validate(_field_name_re, name, "Illegal header name {!r}", name)
validate(_field_value_re, value, "Illegal header value {!r}", value)
assert isinstance(name, bytes)
assert isinstance(value, bytes)
raw_name = name
name = name.lower()
if name == b"content-length":
lengths = {length.strip() for length in value.split(b",")}
if len(lengths) != 1:
<|code_end|>
, predict the immediate next line with the help of imports:
import re
from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
from ._abnf import field_name, field_value
from ._util import bytesify, LocalProtocolError, validate
from ._events import Request
from typing import Literal
from typing_extensions import Literal # type: ignore
and context (classes, functions, sometimes code) from other files:
# Path: h11/_abnf.py
# OWS = r"[ \t]*"
# HEXDIG = r"[0-9A-Fa-f]"
#
# Path: h11/_util.py
# def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
# # Fast-path:
# if type(s) is bytes:
# return s
# if isinstance(s, str):
# s = s.encode("ascii")
# if isinstance(s, int):
# raise TypeError("expected bytes-like object, not int")
# return bytes(s)
#
# class LocalProtocolError(ProtocolError):
# def _reraise_as_remote_protocol_error(self) -> NoReturn:
# # After catching a LocalProtocolError, use this method to re-raise it
# # as a RemoteProtocolError. This method must be called from inside an
# # except: block.
# #
# # An easy way to get an equivalent RemoteProtocolError is just to
# # modify 'self' in place.
# self.__class__ = RemoteProtocolError # type: ignore
# # But the re-raising is somewhat non-trivial -- you might think that
# # now that we've modified the in-flight exception object, that just
# # doing 'raise' to re-raise it would be enough. But it turns out that
# # this doesn't work, because Python tracks the exception type
# # (exc_info[0]) separately from the exception object (exc_info[1]),
# # and we only modified the latter. So we really do need to re-raise
# # the new type explicitly.
# # On py3, the traceback is part of the exception object, so our
# # in-place modification preserved it and we can just re-raise:
# raise self
#
# def validate(
# regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
# ) -> Dict[str, bytes]:
# match = regex.fullmatch(data)
# if not match:
# if format_args:
# msg = msg.format(*format_args)
# raise LocalProtocolError(msg)
# return match.groupdict()
. Output only the next line. | raise LocalProtocolError("conflicting Content-Length headers") |
Given the following code snippet before the placeholder: <|code_start|>@overload
def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers:
...
@overload
def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers:
...
@overload
def normalize_and_validate(
headers: Union[Headers, HeaderTypes], _parsed: bool = False
) -> Headers:
...
def normalize_and_validate(
headers: Union[Headers, HeaderTypes], _parsed: bool = False
) -> Headers:
new_headers = []
seen_content_length = None
saw_transfer_encoding = False
for name, value in headers:
# For headers coming out of the parser, we can safely skip some steps,
# because it always returns bytes and has already run these regexes
# over the data:
if not _parsed:
name = bytesify(name)
value = bytesify(value)
<|code_end|>
, predict the next line using imports from the current file:
import re
from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
from ._abnf import field_name, field_value
from ._util import bytesify, LocalProtocolError, validate
from ._events import Request
from typing import Literal
from typing_extensions import Literal # type: ignore
and context including class names, function names, and sometimes code from other files:
# Path: h11/_abnf.py
# OWS = r"[ \t]*"
# HEXDIG = r"[0-9A-Fa-f]"
#
# Path: h11/_util.py
# def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
# # Fast-path:
# if type(s) is bytes:
# return s
# if isinstance(s, str):
# s = s.encode("ascii")
# if isinstance(s, int):
# raise TypeError("expected bytes-like object, not int")
# return bytes(s)
#
# class LocalProtocolError(ProtocolError):
# def _reraise_as_remote_protocol_error(self) -> NoReturn:
# # After catching a LocalProtocolError, use this method to re-raise it
# # as a RemoteProtocolError. This method must be called from inside an
# # except: block.
# #
# # An easy way to get an equivalent RemoteProtocolError is just to
# # modify 'self' in place.
# self.__class__ = RemoteProtocolError # type: ignore
# # But the re-raising is somewhat non-trivial -- you might think that
# # now that we've modified the in-flight exception object, that just
# # doing 'raise' to re-raise it would be enough. But it turns out that
# # this doesn't work, because Python tracks the exception type
# # (exc_info[0]) separately from the exception object (exc_info[1]),
# # and we only modified the latter. So we really do need to re-raise
# # the new type explicitly.
# # On py3, the traceback is part of the exception object, so our
# # in-place modification preserved it and we can just re-raise:
# raise self
#
# def validate(
# regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
# ) -> Dict[str, bytes]:
# match = regex.fullmatch(data)
# if not match:
# if format_args:
# msg = msg.format(*format_args)
# raise LocalProtocolError(msg)
# return match.groupdict()
. Output only the next line. | validate(_field_name_re, name, "Illegal header name {!r}", name) |
Given the following code snippet before the placeholder: <|code_start|>
# The agents - the brain and the ball
net = NEAT.NeuralNetwork()
genome.BuildPhenotype(net)
agent = NN_agent(space, net)
ball = Ball(space)
tstep = 0
bd = 1000000
while tstep < max_timesteps:
tstep += 1
for event in pygame.event.get():
if event.type == QUIT:
exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
exit()
elif event.type == KEYDOWN and event.key == K_f:
fast_mode = not fast_mode
### Update physics
dt = 1.0/50.0
space.step(dt)
# The NN interacts with the world on each 5 timesteps
if (tstep % 5) == 0:
agent.interact(ball)
if not fast_mode:
# draw the phenotype
<|code_end|>
, predict the next line using imports from the current file:
import sys
import random as rnd
import cv2
import numpy as np
import MultiNEAT as NEAT
import pygame
import pymunk as pm
import progressbar as pbar
import pickle
from MultiNEAT.viz import Draw
from pygame.locals import *
from pygame.color import *
from pymunk import Vec2d
from pymunk.pygame_util import draw, from_pygame
and context including class names, function names, and sometimes code from other files:
# Path: MultiNEAT/viz.py
# def Draw(x, size=(300,300)):
# img = np.zeros((size[0], size[1], 3), dtype=np.uint8)
# img += 10
#
# if isinstance(x, NeuralNetwork):
# DrawPhenotype(img, (0, 0, 250, 250), x )
# else:
# nn = NeuralNetwork()
# x.BuildPhenotype(nn)
# DrawPhenotype(img, (0, 0, 250, 250), nn )
#
# return img
. Output only the next line. | cv2.imshow("current best", Draw(net)) |
Given the following code snippet before the placeholder: <|code_start|> if event.type == QUIT:
exit()
elif event.type == KEYDOWN and event.key == K_ESCAPE:
exit()
elif event.type == KEYDOWN and event.key == K_f:
fast_mode = not fast_mode
elif event.type == KEYDOWN and event.key == K_LEFT and not fast_mode:
ball.body.velocity = (ball.body.velocity[0] - 200, ball.body.velocity[1])
elif event.type == KEYDOWN and event.key == K_RIGHT and not fast_mode:
ball.body.velocity = (ball.body.velocity[0] + 200, ball.body.velocity[1])
elif event.type == KEYDOWN and event.key == K_UP and not fast_mode:
ball.body.velocity = (ball.body.velocity[0], ball.body.velocity[1] + 200)
### Update physics
dt = 1.0/50.0
space.step(dt)
# The NN interacts with the world on each 20 timesteps
if (tstep % 20) == 0:
agent.interact(ball)
avg_ball_height += ball.body.position[1]
# stopping conditions
if not ball.in_air:
break
#if abs(agent.body.velocity[0]) < 50: # never stop on one place!
# break
if not fast_mode:
# draw the phenotype
<|code_end|>
, predict the next line using imports from the current file:
import sys
import time
import random as rnd
import cv2
import numpy as np
import math
import MultiNEAT as NEAT
import pygame
import pymunk as pm
from MultiNEAT.viz import Draw
from pygame.locals import *
from pygame.color import *
from pymunk import Vec2d
from pymunk.pygame_util import draw, from_pygame
and context including class names, function names, and sometimes code from other files:
# Path: MultiNEAT/viz.py
# def Draw(x, size=(300,300)):
# img = np.zeros((size[0], size[1], 3), dtype=np.uint8)
# img += 10
#
# if isinstance(x, NeuralNetwork):
# DrawPhenotype(img, (0, 0, 250, 250), x )
# else:
# nn = NeuralNetwork()
# x.BuildPhenotype(nn)
# DrawPhenotype(img, (0, 0, 250, 250), nn )
#
# return img
. Output only the next line. | cv2.imshow("current best", Draw(net)) |
Next line prediction: <|code_start|>from __future__ import absolute_import
DEFAULT_CONF_NAME = "ricloud.ini"
def get_config(config_name=DEFAULT_CONF_NAME):
<|code_end|>
. Use current file imports:
(import os
from ricloud.compat import RawConfigParser)
and context including class names, function names, or small code snippets from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
. Output only the next line. | config = RawConfigParser() |
Given the code snippet: <|code_start|>
def log_info(message, *args, **kwargs):
logger.info(message, *args, **kwargs)
def generate_timestamp():
return int(time.time())
def _encode(data):
"""Adapted from Django source:
https://github.com/django/django/blob/master/django/core/serializers/json.py
"""
if isinstance(data, datetime.datetime):
r = data.isoformat()
if data.microsecond:
r = r[:23] + r[26:]
if r.endswith("+00:00"):
r = r[:-6] + "Z"
return r
elif isinstance(data, datetime.date):
return data.isoformat()
elif isinstance(data, datetime.time):
r = data.isoformat()
if data.microsecond:
r = r[:12]
return r
elif isinstance(data, datetime.timedelta):
return data.total_seconds()
elif isinstance(data, (decimal.Decimal, uuid.UUID)):
<|code_end|>
, generate the next line using the imports in this file:
import os
import csv
import json
import time
import uuid
import base64
import decimal
import hashlib
import logging
import datetime
import ricloud
from collections import OrderedDict
from ricloud import compat
from ricloud import conf
and context (functions, classes, or occasionally code) from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/conf.py
# DEFAULT_CONF_NAME = "ricloud.ini"
# def get_config(config_name=DEFAULT_CONF_NAME):
# def get_user_root_config_path(config_name=DEFAULT_CONF_NAME):
# def get(setting_section, setting_name):
# def getint(setting_section, setting_name):
# def getboolean(setting_section, setting_name):
. Output only the next line. | return compat.to_str(data) |
Using the snippet: <|code_start|>
@pytest.fixture
def nested_obj():
return ResourceFixture(
"abcd1234", **{"nested": {"id": "abcd123", "resource": "test_resource"}}
)
class TestResource(object):
def test_ok(self, resource_obj):
assert resource_obj.id == "abcd1234"
assert resource_obj.attr1 == "value1"
assert resource_obj["id"] == "abcd1234"
assert resource_obj["attr1"] == "value1"
def test_nested(self, nested_obj):
assert nested_obj.id == "abcd1234"
assert isinstance(nested_obj.nested, ResourceFixture)
assert nested_obj.nested.id == "abcd123"
def test_resource_url(self):
assert ResourceFixture.resource_url() == ricloud.url + "/test/resource"
def test_instance_url(self, resource_obj):
assert resource_obj.instance_url == ricloud.url + "/test/resource/abcd1234"
@pytest.fixture
def list_obj():
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import ricloud
from ricloud.resources.abase import Resource, List
and context (class names, function names, or code) available:
# Path: ricloud/resources/abase.py
# class Resource(ABResource):
# RESOURCE = ""
# RESOURCE_PATH = ""
#
# def __init__(self, *args, **attrs):
# if args:
# attrs["id"] = args[0]
# super(Resource, self).__init__(**attrs)
#
# @classmethod
# def resource_url(cls, resource_path=None):
# resource_path = resource_path or cls.RESOURCE_PATH
# return join_url(ricloud.url, resource_path)
#
# @property
# def instance_url(self):
# return "{}/{}".format(self.resource_url(), self.id)
#
# @classmethod
# def retrieve(cls, id):
# resource = cls(id=id)
# resource.refresh()
# return resource
#
# def refresh(self):
# response, _ = self.request_handler.get(self.instance_url)
# self.attrs = response
#
# class List(ABList):
# RESOURCE = "list"
#
# @property
# def instance_url(self):
# return self.url
. Output only the next line. | return List( |
Next line prediction: <|code_start|>from __future__ import absolute_import, unicode_literals
DEFAULT_ALGORITHM = hashlib.sha256
def hmac_sign(message, key, algorithm=None):
"""Get a hmac signature of a message using the give key."""
algorithm = algorithm or DEFAULT_ALGORITHM
return hmac.new(
<|code_end|>
. Use current file imports:
(import hmac
import hashlib
from ricloud import compat
from ricloud.utils import encode_b64, decode_b64, generate_timestamp)
and context including class names, function names, or small code snippets from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/utils.py
# def encode_b64(data):
# return base64.b64encode(data)
#
# def decode_b64(data):
# return base64.b64decode(data)
#
# def generate_timestamp():
# return int(time.time())
. Output only the next line. | compat.want_bytes(key), compat.want_bytes(message), digestmod=algorithm |
Continue the code snippet: <|code_start|>def hmac_verify(digest, message, key, algorithm=None):
"""Check a hmac signature is valid for a given message and key."""
algorithm = algorithm or DEFAULT_ALGORITHM
return hmac.compare_digest(hmac_sign(message, key), digest)
class Signature:
"""Helper for handling hmac signatures."""
class SignatureError(Exception):
"""Generic signature error."""
class InvalidSignatureHeader(SignatureError):
"""Signature header did not conform to the expected format."""
class InvalidSignature(SignatureError):
"""Signature did not match the expected signature given the payload and secret."""
class InvalidSignatureTimestamp(SignatureError):
"""Timestamp too old, not accepting signature as relevant."""
def __init__(self, signature, timestamp):
self.signature = signature
self.timestamp = timestamp
_header_format = "t={timestamp},s={signature}"
def to_header(self):
"""Dump the signature to a header format."""
<|code_end|>
. Use current file imports:
import hmac
import hashlib
from ricloud import compat
from ricloud.utils import encode_b64, decode_b64, generate_timestamp
and context (classes, functions, or code) from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/utils.py
# def encode_b64(data):
# return base64.b64encode(data)
#
# def decode_b64(data):
# return base64.b64decode(data)
#
# def generate_timestamp():
# return int(time.time())
. Output only the next line. | signature = compat.want_text(encode_b64(self.signature)) |
Next line prediction: <|code_start|>
class InvalidSignature(SignatureError):
"""Signature did not match the expected signature given the payload and secret."""
class InvalidSignatureTimestamp(SignatureError):
"""Timestamp too old, not accepting signature as relevant."""
def __init__(self, signature, timestamp):
self.signature = signature
self.timestamp = timestamp
_header_format = "t={timestamp},s={signature}"
def to_header(self):
"""Dump the signature to a header format."""
signature = compat.want_text(encode_b64(self.signature))
return Signature._header_format.format(
timestamp=self.timestamp, signature=signature
)
@classmethod
def from_header(cls, header):
"""Load a signature from a header string."""
try:
timestamp, signature = header.split(",", 1)
timestamp = int(timestamp[2:])
signature = signature[2:]
<|code_end|>
. Use current file imports:
(import hmac
import hashlib
from ricloud import compat
from ricloud.utils import encode_b64, decode_b64, generate_timestamp)
and context including class names, function names, or small code snippets from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/utils.py
# def encode_b64(data):
# return base64.b64encode(data)
#
# def decode_b64(data):
# return base64.b64decode(data)
#
# def generate_timestamp():
# return int(time.time())
. Output only the next line. | signature = decode_b64(compat.want_bytes(signature)) |
Given snippet: <|code_start|> self.timestamp = timestamp
_header_format = "t={timestamp},s={signature}"
def to_header(self):
"""Dump the signature to a header format."""
signature = compat.want_text(encode_b64(self.signature))
return Signature._header_format.format(
timestamp=self.timestamp, signature=signature
)
@classmethod
def from_header(cls, header):
"""Load a signature from a header string."""
try:
timestamp, signature = header.split(",", 1)
timestamp = int(timestamp[2:])
signature = signature[2:]
signature = decode_b64(compat.want_bytes(signature))
except Exception:
raise Signature.InvalidSignatureHeader
return Signature(signature, timestamp)
@classmethod
def sign(cls, data, secret):
"""Sign a bit of data with the given secret."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import hmac
import hashlib
from ricloud import compat
from ricloud.utils import encode_b64, decode_b64, generate_timestamp
and context:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/utils.py
# def encode_b64(data):
# return base64.b64encode(data)
#
# def decode_b64(data):
# return base64.b64decode(data)
#
# def generate_timestamp():
# return int(time.time())
which might include code, classes, or functions. Output only the next line. | timestamp = compat.want_text(generate_timestamp()) |
Next line prediction: <|code_start|> help="Automatically sets up a webhook config for this URL.",
)
@click.option(
"--only",
default=None,
help="Comma separated list. Only echo events with these slugs.",
)
@click.option(
"--exclude",
default=None,
help="Comma separated list. Exclude events with these slugs.",
)
def listen(host, port, debug, webhook_url, only, exclude):
"""ricloud API event notification listener.
Sets up a small Flask-based server listening on HOST (default: 0.0.0.0) and PORT (default: 8080).
It is likely that you are using something like ngrok to expose the endpoint to the API. If that's the case, pass in the forwarding URL using the --webhook-url option. This will automatically setup a webhook config on the API and set it as active for your key (assuming it is valid).
In most cases, you will likely set up a utility like ngrok to expose this endpoint to the internet.
The default handler simply echos received event data to stdout.
"""
webhook_secret = conf.get("webhooks", "secret")
webhook_delta = conf.getint("webhooks", "delta")
if webhook_url:
key = ricloud.Key.current()
<|code_end|>
. Use current file imports:
(import os
import click
import ricloud
import ricloud.samples
from ricloud import utils
from ricloud import conf
from ricloud import conf
from ricloud import conf
from ricloud.webhooks import app)
and context including class names, function names, or small code snippets from other files:
# Path: ricloud/utils.py
# def log_debug(message, *args, **kwargs):
# def log_info(message, *args, **kwargs):
# def generate_timestamp():
# def _encode(data):
# def encode(data):
# def expanded_encode(data):
# def default(self, data):
# def pretty_print(data):
# def encode_json(data, indent=None):
# def decode_json(data):
# def encode_b64(data):
# def decode_b64(data):
# def transform_csv_file_to_json(file_object):
# def join_url(base, url, allow_fragments=True):
# def get_url_path(url):
# def escape(string):
# def get_md5_hash(data, hex_encode=True):
# def get_path_extension(path):
# def get_directory_from_path(path):
# def ensure_directory_exists(directory):
# def ensure_path_exists(path):
# def get_filename(*args):
# class DataEncoder(json.JSONEncoder):
# class ExpandedDataEncoder(DataEncoder):
. Output only the next line. | url = utils.join_url(webhook_url, "webhooks") |
Given snippet: <|code_start|>from __future__ import absolute_import
def get_or_create_user(user_identifier):
info("Getting user...")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import ricloud
from ricloud import conf
from ricloud import storage
from ricloud import utils
from .utils import info, warn, success, await_response
and context:
# Path: ricloud/conf.py
# DEFAULT_CONF_NAME = "ricloud.ini"
# def get_config(config_name=DEFAULT_CONF_NAME):
# def get_user_root_config_path(config_name=DEFAULT_CONF_NAME):
# def get(setting_section, setting_name):
# def getint(setting_section, setting_name):
# def getboolean(setting_section, setting_name):
#
# Path: ricloud/storage.py
# def download_result(url, to_filename=None):
# def download_result_from_gs(bucket_name, blob_name, to_filename=None):
# def download_result_from_s3(bucket_name, blob_name, to_filename=None):
# def download_result_from_local(blob_name, to_filename=None):
#
# Path: ricloud/utils.py
# def log_debug(message, *args, **kwargs):
# def log_info(message, *args, **kwargs):
# def generate_timestamp():
# def _encode(data):
# def encode(data):
# def expanded_encode(data):
# def default(self, data):
# def pretty_print(data):
# def encode_json(data, indent=None):
# def decode_json(data):
# def encode_b64(data):
# def decode_b64(data):
# def transform_csv_file_to_json(file_object):
# def join_url(base, url, allow_fragments=True):
# def get_url_path(url):
# def escape(string):
# def get_md5_hash(data, hex_encode=True):
# def get_path_extension(path):
# def get_directory_from_path(path):
# def ensure_directory_exists(directory):
# def ensure_path_exists(path):
# def get_filename(*args):
# class DataEncoder(json.JSONEncoder):
# class ExpandedDataEncoder(DataEncoder):
#
# Path: ricloud/samples/utils.py
# def info(message):
# click.secho(message, fg="yellow")
#
# def warn(message):
# click.secho(message, fg="red")
#
# def success(message):
# click.secho(message, fg="green")
#
# def await_response(resource, timeout=60):
# """Poll the API until processing resolves or the timeout is reached."""
# timeout_time = time.time() + timeout
# while resource.state in ("pending", "processing") and time.time() < timeout_time:
#
# time.sleep(1)
#
# resource.refresh()
which might include code, classes, or functions. Output only the next line. | user_identifier = user_identifier or conf.get("samples", "user_identifier") |
Here is a snippet: <|code_start|>
if is_json and cascade:
file_ids = parse_file_ids_from_result_data(download)
if limit:
file_ids = file_ids[:limit]
payload = {"files": file_ids}
cascade_poll = create_poll(
payload, session=poll["session"], source=poll["source"]
)
_, cascade_files = download_results(cascade_poll.results, poll=poll)
files.update(cascade_files)
return result_data, files
def download_result(result, to_filename=None, poll=None):
success("Downloading result {}:".format(result["id"]))
success(" - identifier {}".format(result["identifier"]))
success(" - stored at {}".format(result["url"]))
if not to_filename:
to_filename = utils.escape(result["identifier"])
poll_id = poll["id"] if poll else result["poll"]
to_filename = utils.get_filename(poll_id, to_filename)
<|code_end|>
. Write the next line using the current file imports:
import click
import ricloud
from ricloud import conf
from ricloud import storage
from ricloud import utils
from .utils import info, warn, success, await_response
and context from other files:
# Path: ricloud/conf.py
# DEFAULT_CONF_NAME = "ricloud.ini"
# def get_config(config_name=DEFAULT_CONF_NAME):
# def get_user_root_config_path(config_name=DEFAULT_CONF_NAME):
# def get(setting_section, setting_name):
# def getint(setting_section, setting_name):
# def getboolean(setting_section, setting_name):
#
# Path: ricloud/storage.py
# def download_result(url, to_filename=None):
# def download_result_from_gs(bucket_name, blob_name, to_filename=None):
# def download_result_from_s3(bucket_name, blob_name, to_filename=None):
# def download_result_from_local(blob_name, to_filename=None):
#
# Path: ricloud/utils.py
# def log_debug(message, *args, **kwargs):
# def log_info(message, *args, **kwargs):
# def generate_timestamp():
# def _encode(data):
# def encode(data):
# def expanded_encode(data):
# def default(self, data):
# def pretty_print(data):
# def encode_json(data, indent=None):
# def decode_json(data):
# def encode_b64(data):
# def decode_b64(data):
# def transform_csv_file_to_json(file_object):
# def join_url(base, url, allow_fragments=True):
# def get_url_path(url):
# def escape(string):
# def get_md5_hash(data, hex_encode=True):
# def get_path_extension(path):
# def get_directory_from_path(path):
# def ensure_directory_exists(directory):
# def ensure_path_exists(path):
# def get_filename(*args):
# class DataEncoder(json.JSONEncoder):
# class ExpandedDataEncoder(DataEncoder):
#
# Path: ricloud/samples/utils.py
# def info(message):
# click.secho(message, fg="yellow")
#
# def warn(message):
# click.secho(message, fg="red")
#
# def success(message):
# click.secho(message, fg="green")
#
# def await_response(resource, timeout=60):
# """Poll the API until processing resolves or the timeout is reached."""
# timeout_time = time.time() + timeout
# while resource.state in ("pending", "processing") and time.time() < timeout_time:
#
# time.sleep(1)
#
# resource.refresh()
, which may include functions, classes, or code. Output only the next line. | storage.download_result(result["url"], to_filename=to_filename) |
Using the snippet: <|code_start|> if is_json:
result_data[result["identifier"]] = download
else:
files[result["identifier"]] = download
if is_json and cascade:
file_ids = parse_file_ids_from_result_data(download)
if limit:
file_ids = file_ids[:limit]
payload = {"files": file_ids}
cascade_poll = create_poll(
payload, session=poll["session"], source=poll["source"]
)
_, cascade_files = download_results(cascade_poll.results, poll=poll)
files.update(cascade_files)
return result_data, files
def download_result(result, to_filename=None, poll=None):
success("Downloading result {}:".format(result["id"]))
success(" - identifier {}".format(result["identifier"]))
success(" - stored at {}".format(result["url"]))
if not to_filename:
<|code_end|>
, determine the next line of code. You have imports:
import click
import ricloud
from ricloud import conf
from ricloud import storage
from ricloud import utils
from .utils import info, warn, success, await_response
and context (class names, function names, or code) available:
# Path: ricloud/conf.py
# DEFAULT_CONF_NAME = "ricloud.ini"
# def get_config(config_name=DEFAULT_CONF_NAME):
# def get_user_root_config_path(config_name=DEFAULT_CONF_NAME):
# def get(setting_section, setting_name):
# def getint(setting_section, setting_name):
# def getboolean(setting_section, setting_name):
#
# Path: ricloud/storage.py
# def download_result(url, to_filename=None):
# def download_result_from_gs(bucket_name, blob_name, to_filename=None):
# def download_result_from_s3(bucket_name, blob_name, to_filename=None):
# def download_result_from_local(blob_name, to_filename=None):
#
# Path: ricloud/utils.py
# def log_debug(message, *args, **kwargs):
# def log_info(message, *args, **kwargs):
# def generate_timestamp():
# def _encode(data):
# def encode(data):
# def expanded_encode(data):
# def default(self, data):
# def pretty_print(data):
# def encode_json(data, indent=None):
# def decode_json(data):
# def encode_b64(data):
# def decode_b64(data):
# def transform_csv_file_to_json(file_object):
# def join_url(base, url, allow_fragments=True):
# def get_url_path(url):
# def escape(string):
# def get_md5_hash(data, hex_encode=True):
# def get_path_extension(path):
# def get_directory_from_path(path):
# def ensure_directory_exists(directory):
# def ensure_path_exists(path):
# def get_filename(*args):
# class DataEncoder(json.JSONEncoder):
# class ExpandedDataEncoder(DataEncoder):
#
# Path: ricloud/samples/utils.py
# def info(message):
# click.secho(message, fg="yellow")
#
# def warn(message):
# click.secho(message, fg="red")
#
# def success(message):
# click.secho(message, fg="green")
#
# def await_response(resource, timeout=60):
# """Poll the API until processing resolves or the timeout is reached."""
# timeout_time = time.time() + timeout
# while resource.state in ("pending", "processing") and time.time() < timeout_time:
#
# time.sleep(1)
#
# resource.refresh()
. Output only the next line. | to_filename = utils.escape(result["identifier"]) |
Given the following code snippet before the placeholder: <|code_start|> user_identifier = user_identifier or conf.get("samples", "user_identifier")
user = ricloud.User.create(identifier=user_identifier)
success("User {} retrieved.".format(user.id))
return user
def retrieve_session(session_id):
info("Retrieving session {} ...".format(session_id))
session = ricloud.Session.retrieve(session_id)
success("Session {} retrieved.".format(session_id))
return session
def create_subscription(session, poll_payload, source=None):
info("Creating subscription...")
request_payload = {"session": session, "poll_payload": poll_payload}
if source:
request_payload["source"] = source
sub = ricloud.Subscription.create(**request_payload)
await_response(sub)
if session.state == "pending":
<|code_end|>
, predict the next line using imports from the current file:
import click
import ricloud
from ricloud import conf
from ricloud import storage
from ricloud import utils
from .utils import info, warn, success, await_response
and context including class names, function names, and sometimes code from other files:
# Path: ricloud/conf.py
# DEFAULT_CONF_NAME = "ricloud.ini"
# def get_config(config_name=DEFAULT_CONF_NAME):
# def get_user_root_config_path(config_name=DEFAULT_CONF_NAME):
# def get(setting_section, setting_name):
# def getint(setting_section, setting_name):
# def getboolean(setting_section, setting_name):
#
# Path: ricloud/storage.py
# def download_result(url, to_filename=None):
# def download_result_from_gs(bucket_name, blob_name, to_filename=None):
# def download_result_from_s3(bucket_name, blob_name, to_filename=None):
# def download_result_from_local(blob_name, to_filename=None):
#
# Path: ricloud/utils.py
# def log_debug(message, *args, **kwargs):
# def log_info(message, *args, **kwargs):
# def generate_timestamp():
# def _encode(data):
# def encode(data):
# def expanded_encode(data):
# def default(self, data):
# def pretty_print(data):
# def encode_json(data, indent=None):
# def decode_json(data):
# def encode_b64(data):
# def decode_b64(data):
# def transform_csv_file_to_json(file_object):
# def join_url(base, url, allow_fragments=True):
# def get_url_path(url):
# def escape(string):
# def get_md5_hash(data, hex_encode=True):
# def get_path_extension(path):
# def get_directory_from_path(path):
# def ensure_directory_exists(directory):
# def ensure_path_exists(path):
# def get_filename(*args):
# class DataEncoder(json.JSONEncoder):
# class ExpandedDataEncoder(DataEncoder):
#
# Path: ricloud/samples/utils.py
# def info(message):
# click.secho(message, fg="yellow")
#
# def warn(message):
# click.secho(message, fg="red")
#
# def success(message):
# click.secho(message, fg="green")
#
# def await_response(resource, timeout=60):
# """Poll the API until processing resolves or the timeout is reached."""
# timeout_time = time.time() + timeout
# while resource.state in ("pending", "processing") and time.time() < timeout_time:
#
# time.sleep(1)
#
# resource.refresh()
. Output only the next line. | warn( |
Given snippet: <|code_start|>from __future__ import absolute_import
def get_or_create_user(user_identifier):
info("Getting user...")
user_identifier = user_identifier or conf.get("samples", "user_identifier")
user = ricloud.User.create(identifier=user_identifier)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
import ricloud
from ricloud import conf
from ricloud import storage
from ricloud import utils
from .utils import info, warn, success, await_response
and context:
# Path: ricloud/conf.py
# DEFAULT_CONF_NAME = "ricloud.ini"
# def get_config(config_name=DEFAULT_CONF_NAME):
# def get_user_root_config_path(config_name=DEFAULT_CONF_NAME):
# def get(setting_section, setting_name):
# def getint(setting_section, setting_name):
# def getboolean(setting_section, setting_name):
#
# Path: ricloud/storage.py
# def download_result(url, to_filename=None):
# def download_result_from_gs(bucket_name, blob_name, to_filename=None):
# def download_result_from_s3(bucket_name, blob_name, to_filename=None):
# def download_result_from_local(blob_name, to_filename=None):
#
# Path: ricloud/utils.py
# def log_debug(message, *args, **kwargs):
# def log_info(message, *args, **kwargs):
# def generate_timestamp():
# def _encode(data):
# def encode(data):
# def expanded_encode(data):
# def default(self, data):
# def pretty_print(data):
# def encode_json(data, indent=None):
# def decode_json(data):
# def encode_b64(data):
# def decode_b64(data):
# def transform_csv_file_to_json(file_object):
# def join_url(base, url, allow_fragments=True):
# def get_url_path(url):
# def escape(string):
# def get_md5_hash(data, hex_encode=True):
# def get_path_extension(path):
# def get_directory_from_path(path):
# def ensure_directory_exists(directory):
# def ensure_path_exists(path):
# def get_filename(*args):
# class DataEncoder(json.JSONEncoder):
# class ExpandedDataEncoder(DataEncoder):
#
# Path: ricloud/samples/utils.py
# def info(message):
# click.secho(message, fg="yellow")
#
# def warn(message):
# click.secho(message, fg="red")
#
# def success(message):
# click.secho(message, fg="green")
#
# def await_response(resource, timeout=60):
# """Poll the API until processing resolves or the timeout is reached."""
# timeout_time = time.time() + timeout
# while resource.state in ("pending", "processing") and time.time() < timeout_time:
#
# time.sleep(1)
#
# resource.refresh()
which might include code, classes, or functions. Output only the next line. | success("User {} retrieved.".format(user.id)) |
Here is a snippet: <|code_start|>def get_or_create_user(user_identifier):
info("Getting user...")
user_identifier = user_identifier or conf.get("samples", "user_identifier")
user = ricloud.User.create(identifier=user_identifier)
success("User {} retrieved.".format(user.id))
return user
def retrieve_session(session_id):
info("Retrieving session {} ...".format(session_id))
session = ricloud.Session.retrieve(session_id)
success("Session {} retrieved.".format(session_id))
return session
def create_subscription(session, poll_payload, source=None):
info("Creating subscription...")
request_payload = {"session": session, "poll_payload": poll_payload}
if source:
request_payload["source"] = source
sub = ricloud.Subscription.create(**request_payload)
<|code_end|>
. Write the next line using the current file imports:
import click
import ricloud
from ricloud import conf
from ricloud import storage
from ricloud import utils
from .utils import info, warn, success, await_response
and context from other files:
# Path: ricloud/conf.py
# DEFAULT_CONF_NAME = "ricloud.ini"
# def get_config(config_name=DEFAULT_CONF_NAME):
# def get_user_root_config_path(config_name=DEFAULT_CONF_NAME):
# def get(setting_section, setting_name):
# def getint(setting_section, setting_name):
# def getboolean(setting_section, setting_name):
#
# Path: ricloud/storage.py
# def download_result(url, to_filename=None):
# def download_result_from_gs(bucket_name, blob_name, to_filename=None):
# def download_result_from_s3(bucket_name, blob_name, to_filename=None):
# def download_result_from_local(blob_name, to_filename=None):
#
# Path: ricloud/utils.py
# def log_debug(message, *args, **kwargs):
# def log_info(message, *args, **kwargs):
# def generate_timestamp():
# def _encode(data):
# def encode(data):
# def expanded_encode(data):
# def default(self, data):
# def pretty_print(data):
# def encode_json(data, indent=None):
# def decode_json(data):
# def encode_b64(data):
# def decode_b64(data):
# def transform_csv_file_to_json(file_object):
# def join_url(base, url, allow_fragments=True):
# def get_url_path(url):
# def escape(string):
# def get_md5_hash(data, hex_encode=True):
# def get_path_extension(path):
# def get_directory_from_path(path):
# def ensure_directory_exists(directory):
# def ensure_path_exists(path):
# def get_filename(*args):
# class DataEncoder(json.JSONEncoder):
# class ExpandedDataEncoder(DataEncoder):
#
# Path: ricloud/samples/utils.py
# def info(message):
# click.secho(message, fg="yellow")
#
# def warn(message):
# click.secho(message, fg="red")
#
# def success(message):
# click.secho(message, fg="green")
#
# def await_response(resource, timeout=60):
# """Poll the API until processing resolves or the timeout is reached."""
# timeout_time = time.time() + timeout
# while resource.state in ("pending", "processing") and time.time() < timeout_time:
#
# time.sleep(1)
#
# resource.refresh()
, which may include functions, classes, or code. Output only the next line. | await_response(sub) |
Predict the next line after this snippet: <|code_start|>
def __repr__(self):
return "RequestError(status={s.status}, content='{s.content}')".format(s=self)
def __str__(self):
return "status:{s.status}, content:{s.content}".format(s=self)
class RequestError(RicloudError):
"""Error response returned from the API."""
def __init__(self, status, content):
super(RequestError, self).__init__(status, content)
self.error, self.message, self.params = self.parse_content(content)
@staticmethod
def parse_content(content):
data = decode_json(content)
error = data.get("error")
message = data.get("message")
params = data.get("params")
return error, message, params
def __str__(self):
format_str = "status:{s.status}, error:{s.error}, message:'{s.message}'".format(
s=self
)
if self.params:
<|code_end|>
using the current file's imports:
from ricloud.utils import encode_json, decode_json
and any relevant context from other files:
# Path: ricloud/utils.py
# def encode_json(data, indent=None):
# return json.dumps(data, indent=indent, cls=DataEncoder, ensure_ascii=False)
#
# def decode_json(data):
# return json.loads(data, object_pairs_hook=OrderedDict)
. Output only the next line. | format_str += ", params:{params}".format(params=encode_json(self.params)) |
Based on the snippet: <|code_start|>from __future__ import absolute_import
class RicloudError(Exception):
def __init__(self, status, content):
self.status = status
self.content = content
def __repr__(self):
return "RequestError(status={s.status}, content='{s.content}')".format(s=self)
def __str__(self):
return "status:{s.status}, content:{s.content}".format(s=self)
class RequestError(RicloudError):
"""Error response returned from the API."""
def __init__(self, status, content):
super(RequestError, self).__init__(status, content)
self.error, self.message, self.params = self.parse_content(content)
@staticmethod
def parse_content(content):
<|code_end|>
, predict the immediate next line with the help of imports:
from ricloud.utils import encode_json, decode_json
and context (classes, functions, sometimes code) from other files:
# Path: ricloud/utils.py
# def encode_json(data, indent=None):
# return json.dumps(data, indent=indent, cls=DataEncoder, ensure_ascii=False)
#
# def decode_json(data):
# return json.loads(data, object_pairs_hook=OrderedDict)
. Output only the next line. | data = decode_json(content) |
Next line prediction: <|code_start|>
app = Flask(__name__)
@app.route("/webhooks/<uuid:event_id>", methods=["post"])
def webhooks(event_id):
if not request.is_json:
abort(400)
webhook_secret = app.config.get("WEBHOOK_SECRET")
webhook_delta = app.config.get("WEBHOOK_DELTA")
if webhook_secret and not verify_request(
request, webhook_secret, delta=webhook_delta
):
abort(400)
only = app.config.get("EVENTS_ONLY")
exclude = app.config.get("EVENTS_EXCLUDE")
try:
handle_event(request.json, only=only, exclude=exclude)
except Exception as exc:
print("Exception occurred during event handling:", str(exc))
abort(400)
return "OK"
def verify_request(request, secret, delta=600):
<|code_end|>
. Use current file imports:
(from flask import Flask, request, abort
from ricloud.signing import Signature
from ricloud.utils import encode_json)
and context including class names, function names, or small code snippets from other files:
# Path: ricloud/signing.py
# class Signature:
# """Helper for handling hmac signatures."""
#
# class SignatureError(Exception):
# """Generic signature error."""
#
# class InvalidSignatureHeader(SignatureError):
# """Signature header did not conform to the expected format."""
#
# class InvalidSignature(SignatureError):
# """Signature did not match the expected signature given the payload and secret."""
#
# class InvalidSignatureTimestamp(SignatureError):
# """Timestamp too old, not accepting signature as relevant."""
#
# def __init__(self, signature, timestamp):
# self.signature = signature
# self.timestamp = timestamp
#
# _header_format = "t={timestamp},s={signature}"
#
# def to_header(self):
# """Dump the signature to a header format."""
# signature = compat.want_text(encode_b64(self.signature))
#
# return Signature._header_format.format(
# timestamp=self.timestamp, signature=signature
# )
#
# @classmethod
# def from_header(cls, header):
# """Load a signature from a header string."""
# try:
# timestamp, signature = header.split(",", 1)
#
# timestamp = int(timestamp[2:])
# signature = signature[2:]
#
# signature = decode_b64(compat.want_bytes(signature))
# except Exception:
# raise Signature.InvalidSignatureHeader
#
# return Signature(signature, timestamp)
#
# @classmethod
# def sign(cls, data, secret):
# """Sign a bit of data with the given secret."""
# timestamp = compat.want_text(generate_timestamp())
#
# payload = cls._get_payload(data, timestamp)
#
# signature = hmac_sign(payload, secret)
#
# return Signature(signature, timestamp)
#
# def verify(self, data, secret, delta=None):
# """Verify a signature is valid for a given payload and secret."""
# payload = self._get_payload(data, self.timestamp)
#
# if not hmac_verify(self.signature, payload, secret):
# raise Signature.InvalidSignature
#
# if delta and (generate_timestamp() - self.timestamp) > delta:
# raise Signature.InvalidSignatureTimestamp
#
# @staticmethod
# def _get_payload(data, timestamp):
# return ".".join([compat.want_text(str(timestamp)), compat.want_text(data)])
#
# Path: ricloud/utils.py
# def encode_json(data, indent=None):
# return json.dumps(data, indent=indent, cls=DataEncoder, ensure_ascii=False)
. Output only the next line. | signature = Signature.from_header(request.headers["Ricloud-Signature"]) |
Using the snippet: <|code_start|>
return "OK"
def verify_request(request, secret, delta=600):
signature = Signature.from_header(request.headers["Ricloud-Signature"])
try:
signature.verify(request.data, secret, delta=delta)
except Signature.SignatureError as exc:
print("Event signature verification failed:", str(exc))
return False
return True
def handle_event(data, only=None, exclude=None):
event_type = data["type"]
event_action = data["action"]
event_slug = event_type + "." + event_action
if event_slug == "webhook_config.test":
print("Test event received!")
if only and event_slug not in only:
return
if exclude and event_slug in exclude:
return
<|code_end|>
, determine the next line of code. You have imports:
from flask import Flask, request, abort
from ricloud.signing import Signature
from ricloud.utils import encode_json
and context (class names, function names, or code) available:
# Path: ricloud/signing.py
# class Signature:
# """Helper for handling hmac signatures."""
#
# class SignatureError(Exception):
# """Generic signature error."""
#
# class InvalidSignatureHeader(SignatureError):
# """Signature header did not conform to the expected format."""
#
# class InvalidSignature(SignatureError):
# """Signature did not match the expected signature given the payload and secret."""
#
# class InvalidSignatureTimestamp(SignatureError):
# """Timestamp too old, not accepting signature as relevant."""
#
# def __init__(self, signature, timestamp):
# self.signature = signature
# self.timestamp = timestamp
#
# _header_format = "t={timestamp},s={signature}"
#
# def to_header(self):
# """Dump the signature to a header format."""
# signature = compat.want_text(encode_b64(self.signature))
#
# return Signature._header_format.format(
# timestamp=self.timestamp, signature=signature
# )
#
# @classmethod
# def from_header(cls, header):
# """Load a signature from a header string."""
# try:
# timestamp, signature = header.split(",", 1)
#
# timestamp = int(timestamp[2:])
# signature = signature[2:]
#
# signature = decode_b64(compat.want_bytes(signature))
# except Exception:
# raise Signature.InvalidSignatureHeader
#
# return Signature(signature, timestamp)
#
# @classmethod
# def sign(cls, data, secret):
# """Sign a bit of data with the given secret."""
# timestamp = compat.want_text(generate_timestamp())
#
# payload = cls._get_payload(data, timestamp)
#
# signature = hmac_sign(payload, secret)
#
# return Signature(signature, timestamp)
#
# def verify(self, data, secret, delta=None):
# """Verify a signature is valid for a given payload and secret."""
# payload = self._get_payload(data, self.timestamp)
#
# if not hmac_verify(self.signature, payload, secret):
# raise Signature.InvalidSignature
#
# if delta and (generate_timestamp() - self.timestamp) > delta:
# raise Signature.InvalidSignatureTimestamp
#
# @staticmethod
# def _get_payload(data, timestamp):
# return ".".join([compat.want_text(str(timestamp)), compat.want_text(data)])
#
# Path: ricloud/utils.py
# def encode_json(data, indent=None):
# return json.dumps(data, indent=indent, cls=DataEncoder, ensure_ascii=False)
. Output only the next line. | print("Event received:", encode_json(data, indent=2)) |
Given the code snippet: <|code_start|>from __future__ import absolute_import
class TestHelp(object):
def test_ok(self):
runner = CliRunner()
<|code_end|>
, generate the next line using the imports in this file:
from click.testing import CliRunner
from ricloud.cli import cli
and context (functions, classes, or occasionally code) from other files:
# Path: ricloud/cli.py
# @click.group()
# def cli():
# pass
. Output only the next line. | result = runner.invoke(cli, ["--help"]) |
Given snippet: <|code_start|>from __future__ import absolute_import
USER_IDENTIFIER = "testing@reincubate.com"
SOURCE_IDENTIFIER = "john.appleseed@reincubate.com"
@pytest.mark.integration
class TestIntegration(object):
def test_ok(self):
user = ricloud.User.create(identifier=USER_IDENTIFIER)
assert isinstance(user, ricloud.User)
assert user.identifier == USER_IDENTIFIER
session = ricloud.Session.create(
source={
"user": user,
"type": "mocks.mock",
"identifier": SOURCE_IDENTIFIER,
},
payload={"password": "abcd1234"},
)
assert isinstance(session, ricloud.Session)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import ricloud
from ricloud.samples.utils import await_response
and context:
# Path: ricloud/samples/utils.py
# def await_response(resource, timeout=60):
# """Poll the API until processing resolves or the timeout is reached."""
# timeout_time = time.time() + timeout
# while resource.state in ("pending", "processing") and time.time() < timeout_time:
#
# time.sleep(1)
#
# resource.refresh()
which might include code, classes, or functions. Output only the next line. | await_response(session) |
Here is a snippet: <|code_start|> if name in self.__dict__:
return super(ABResource, self).__delattr__(name)
del self.attrs[name]
def __eq__(self, other):
ignore = ["resource"]
attrs_self = {key: value for key, value in self.items() if key not in ignore}
attrs_other = {key: value for key, value in other.items() if key not in ignore}
return attrs_self == attrs_other
@classmethod
def get_resources(cls):
for subclass in cls.__subclasses__():
if getattr(subclass, "RESOURCE", None):
yield subclass.RESOURCE, subclass
for item in subclass.get_resources():
yield item
_resources = None
@classmethod
def get_resource(cls, resource_type):
if ABResource._resources is None:
ABResource._resources = dict(ABResource.get_resources())
return ABResource._resources.get(resource_type)
@classmethod
def parse_value(cls, value):
<|code_end|>
. Write the next line using the current file imports:
from collections import OrderedDict
from ricloud.compat import Mapping, MutableMapping, MutableSequence
from ricloud.requests import RequestHandler
from ricloud.utils import pretty_print, join_url
import ricloud
and context from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/requests.py
# class RequestHandler(object):
# def __init__(self):
# self.session = requests.Session()
#
# self.max_retries = conf.getint("api", "max_retries")
# self.await_for = conf.get("api", "await_for")
#
# def set_headers(self, headers):
# headers = headers or {}
#
# headers.setdefault("User-Agent", get_user_agent_header())
# headers.setdefault("Authorization", get_auth_header())
#
# if self.await_for:
# headers.setdefault("Ricloud-Await", self.await_for)
#
# return headers
#
# def get(self, url, headers=None, params=None):
# if params:
# for param, value in params.items():
# encoded_value = encode(value)
# params[param] = encoded_value if encoded_value is not None else value
#
# return self.send("GET", url, headers=headers, params=params)
#
# def post(self, url, headers=None, data=None):
# json_data = encode_json(data)
#
# return self.send("POST", url, headers=headers, data=json_data)
#
# def delete(self, url, headers=None):
# return self.send("DELETE", url, headers=headers)
#
# def send(self, method, url, headers=None, data=None, params=None):
# headers = self.set_headers(headers)
#
# response = self._send(
# method=method,
# url=url,
# headers=headers,
# data=data,
# params=params,
# retries_remaining=self.max_retries,
# )
#
# if response.status_code >= 500:
# raise ServerError(response.status_code, response.content)
# elif response.status_code >= 400:
# raise RequestError(response.status_code, response.content)
#
# return decode_json(response.content), response.status_code
#
# def _send(self, method, url, headers, data, params, retries_remaining=None):
# try:
# response = self.session.request(
# method=method, url=url, headers=headers, data=data, params=params
# )
# except (ConnectionError, Timeout):
# if not retries_remaining:
# raise
#
# response = None
#
# # Explicit None comparison as bad responses are falsey.
# if response is None or (response.status_code >= 500):
# if retries_remaining:
# return self._send(
# method=method,
# url=url,
# headers=headers,
# data=data,
# params=params,
# retries_remaining=retries_remaining - 1,
# )
#
# return response
#
# Path: ricloud/utils.py
# def pretty_print(data):
# return json.dumps(data, indent=2, cls=ExpandedDataEncoder, ensure_ascii=False)
#
# def join_url(base, url, allow_fragments=True):
# return compat.urljoin(base, url, allow_fragments=allow_fragments)
, which may include functions, classes, or code. Output only the next line. | if isinstance(value, Mapping) and not isinstance(value, ABResource): |
Given the code snippet: <|code_start|>
class Resource(ABResource):
RESOURCE = ""
RESOURCE_PATH = ""
def __init__(self, *args, **attrs):
if args:
attrs["id"] = args[0]
super(Resource, self).__init__(**attrs)
@classmethod
def resource_url(cls, resource_path=None):
resource_path = resource_path or cls.RESOURCE_PATH
return join_url(ricloud.url, resource_path)
@property
def instance_url(self):
return "{}/{}".format(self.resource_url(), self.id)
@classmethod
def retrieve(cls, id):
resource = cls(id=id)
resource.refresh()
return resource
def refresh(self):
response, _ = self.request_handler.get(self.instance_url)
self.attrs = response
<|code_end|>
, generate the next line using the imports in this file:
from collections import OrderedDict
from ricloud.compat import Mapping, MutableMapping, MutableSequence
from ricloud.requests import RequestHandler
from ricloud.utils import pretty_print, join_url
import ricloud
and context (functions, classes, or occasionally code) from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/requests.py
# class RequestHandler(object):
# def __init__(self):
# self.session = requests.Session()
#
# self.max_retries = conf.getint("api", "max_retries")
# self.await_for = conf.get("api", "await_for")
#
# def set_headers(self, headers):
# headers = headers or {}
#
# headers.setdefault("User-Agent", get_user_agent_header())
# headers.setdefault("Authorization", get_auth_header())
#
# if self.await_for:
# headers.setdefault("Ricloud-Await", self.await_for)
#
# return headers
#
# def get(self, url, headers=None, params=None):
# if params:
# for param, value in params.items():
# encoded_value = encode(value)
# params[param] = encoded_value if encoded_value is not None else value
#
# return self.send("GET", url, headers=headers, params=params)
#
# def post(self, url, headers=None, data=None):
# json_data = encode_json(data)
#
# return self.send("POST", url, headers=headers, data=json_data)
#
# def delete(self, url, headers=None):
# return self.send("DELETE", url, headers=headers)
#
# def send(self, method, url, headers=None, data=None, params=None):
# headers = self.set_headers(headers)
#
# response = self._send(
# method=method,
# url=url,
# headers=headers,
# data=data,
# params=params,
# retries_remaining=self.max_retries,
# )
#
# if response.status_code >= 500:
# raise ServerError(response.status_code, response.content)
# elif response.status_code >= 400:
# raise RequestError(response.status_code, response.content)
#
# return decode_json(response.content), response.status_code
#
# def _send(self, method, url, headers, data, params, retries_remaining=None):
# try:
# response = self.session.request(
# method=method, url=url, headers=headers, data=data, params=params
# )
# except (ConnectionError, Timeout):
# if not retries_remaining:
# raise
#
# response = None
#
# # Explicit None comparison as bad responses are falsey.
# if response is None or (response.status_code >= 500):
# if retries_remaining:
# return self._send(
# method=method,
# url=url,
# headers=headers,
# data=data,
# params=params,
# retries_remaining=retries_remaining - 1,
# )
#
# return response
#
# Path: ricloud/utils.py
# def pretty_print(data):
# return json.dumps(data, indent=2, cls=ExpandedDataEncoder, ensure_ascii=False)
#
# def join_url(base, url, allow_fragments=True):
# return compat.urljoin(base, url, allow_fragments=allow_fragments)
. Output only the next line. | class ABList(MutableSequence, ABResource): |
Continue the code snippet: <|code_start|>from __future__ import absolute_import, unicode_literals
class ABResource(MutableMapping):
request_handler = RequestHandler()
def __init__(self, **attrs):
attrs = self.parse_attrs(attrs)
# Need to setup using object method to avoid circular deps on init.
object.__setattr__(self, "attrs", attrs or OrderedDict())
def __repr__(self):
return "{name}({attrs})".format(
<|code_end|>
. Use current file imports:
from collections import OrderedDict
from ricloud.compat import Mapping, MutableMapping, MutableSequence
from ricloud.requests import RequestHandler
from ricloud.utils import pretty_print, join_url
import ricloud
and context (classes, functions, or code) from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/requests.py
# class RequestHandler(object):
# def __init__(self):
# self.session = requests.Session()
#
# self.max_retries = conf.getint("api", "max_retries")
# self.await_for = conf.get("api", "await_for")
#
# def set_headers(self, headers):
# headers = headers or {}
#
# headers.setdefault("User-Agent", get_user_agent_header())
# headers.setdefault("Authorization", get_auth_header())
#
# if self.await_for:
# headers.setdefault("Ricloud-Await", self.await_for)
#
# return headers
#
# def get(self, url, headers=None, params=None):
# if params:
# for param, value in params.items():
# encoded_value = encode(value)
# params[param] = encoded_value if encoded_value is not None else value
#
# return self.send("GET", url, headers=headers, params=params)
#
# def post(self, url, headers=None, data=None):
# json_data = encode_json(data)
#
# return self.send("POST", url, headers=headers, data=json_data)
#
# def delete(self, url, headers=None):
# return self.send("DELETE", url, headers=headers)
#
# def send(self, method, url, headers=None, data=None, params=None):
# headers = self.set_headers(headers)
#
# response = self._send(
# method=method,
# url=url,
# headers=headers,
# data=data,
# params=params,
# retries_remaining=self.max_retries,
# )
#
# if response.status_code >= 500:
# raise ServerError(response.status_code, response.content)
# elif response.status_code >= 400:
# raise RequestError(response.status_code, response.content)
#
# return decode_json(response.content), response.status_code
#
# def _send(self, method, url, headers, data, params, retries_remaining=None):
# try:
# response = self.session.request(
# method=method, url=url, headers=headers, data=data, params=params
# )
# except (ConnectionError, Timeout):
# if not retries_remaining:
# raise
#
# response = None
#
# # Explicit None comparison as bad responses are falsey.
# if response is None or (response.status_code >= 500):
# if retries_remaining:
# return self._send(
# method=method,
# url=url,
# headers=headers,
# data=data,
# params=params,
# retries_remaining=retries_remaining - 1,
# )
#
# return response
#
# Path: ricloud/utils.py
# def pretty_print(data):
# return json.dumps(data, indent=2, cls=ExpandedDataEncoder, ensure_ascii=False)
#
# def join_url(base, url, allow_fragments=True):
# return compat.urljoin(base, url, allow_fragments=allow_fragments)
. Output only the next line. | name=self.__class__.__name__, attrs=pretty_print(self.attrs), |
Given the code snippet: <|code_start|> if ABResource._resources is None:
ABResource._resources = dict(ABResource.get_resources())
return ABResource._resources.get(resource_type)
@classmethod
def parse_value(cls, value):
if isinstance(value, Mapping) and not isinstance(value, ABResource):
resource_type = value.get("resource")
if resource_type:
resource = cls.get_resource(resource_type)
return resource(**value)
return value
@classmethod
def parse_attrs(cls, attrs):
return dict([(attr, cls.parse_value(value)) for attr, value in attrs.items()])
class Resource(ABResource):
RESOURCE = ""
RESOURCE_PATH = ""
def __init__(self, *args, **attrs):
if args:
attrs["id"] = args[0]
super(Resource, self).__init__(**attrs)
@classmethod
def resource_url(cls, resource_path=None):
resource_path = resource_path or cls.RESOURCE_PATH
<|code_end|>
, generate the next line using the imports in this file:
from collections import OrderedDict
from ricloud.compat import Mapping, MutableMapping, MutableSequence
from ricloud.requests import RequestHandler
from ricloud.utils import pretty_print, join_url
import ricloud
and context (functions, classes, or occasionally code) from other files:
# Path: ricloud/compat.py
# PY3 = sys.version_info[0] >= 3
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
# def want_bytes(data):
# def want_text(data):
# def to_str(data):
#
# Path: ricloud/requests.py
# class RequestHandler(object):
# def __init__(self):
# self.session = requests.Session()
#
# self.max_retries = conf.getint("api", "max_retries")
# self.await_for = conf.get("api", "await_for")
#
# def set_headers(self, headers):
# headers = headers or {}
#
# headers.setdefault("User-Agent", get_user_agent_header())
# headers.setdefault("Authorization", get_auth_header())
#
# if self.await_for:
# headers.setdefault("Ricloud-Await", self.await_for)
#
# return headers
#
# def get(self, url, headers=None, params=None):
# if params:
# for param, value in params.items():
# encoded_value = encode(value)
# params[param] = encoded_value if encoded_value is not None else value
#
# return self.send("GET", url, headers=headers, params=params)
#
# def post(self, url, headers=None, data=None):
# json_data = encode_json(data)
#
# return self.send("POST", url, headers=headers, data=json_data)
#
# def delete(self, url, headers=None):
# return self.send("DELETE", url, headers=headers)
#
# def send(self, method, url, headers=None, data=None, params=None):
# headers = self.set_headers(headers)
#
# response = self._send(
# method=method,
# url=url,
# headers=headers,
# data=data,
# params=params,
# retries_remaining=self.max_retries,
# )
#
# if response.status_code >= 500:
# raise ServerError(response.status_code, response.content)
# elif response.status_code >= 400:
# raise RequestError(response.status_code, response.content)
#
# return decode_json(response.content), response.status_code
#
# def _send(self, method, url, headers, data, params, retries_remaining=None):
# try:
# response = self.session.request(
# method=method, url=url, headers=headers, data=data, params=params
# )
# except (ConnectionError, Timeout):
# if not retries_remaining:
# raise
#
# response = None
#
# # Explicit None comparison as bad responses are falsey.
# if response is None or (response.status_code >= 500):
# if retries_remaining:
# return self._send(
# method=method,
# url=url,
# headers=headers,
# data=data,
# params=params,
# retries_remaining=retries_remaining - 1,
# )
#
# return response
#
# Path: ricloud/utils.py
# def pretty_print(data):
# return json.dumps(data, indent=2, cls=ExpandedDataEncoder, ensure_ascii=False)
#
# def join_url(base, url, allow_fragments=True):
# return compat.urljoin(base, url, allow_fragments=allow_fragments)
. Output only the next line. | return join_url(ricloud.url, resource_path) |
Using the snippet: <|code_start|>
class PostgresPartitioningStrategy:
"""Base class for implementing a partitioning strategy for a partitioned
table."""
@abstractmethod
def to_create(
self,
<|code_end|>
, determine the next line of code. You have imports:
from abc import abstractmethod
from typing import Generator
from .partition import PostgresPartition
and context (class names, function names, or code) available:
# Path: psqlextra/partitioning/partition.py
# class PostgresPartition:
# """Base class for a PostgreSQL table partition."""
#
# @abstractmethod
# def name(self) -> str:
# """Generates/computes the name for this partition."""
#
# @abstractmethod
# def create(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# comment: Optional[str] = None,
# ) -> None:
# """Creates this partition in the database."""
#
# @abstractmethod
# def delete(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# ) -> None:
# """Deletes this partition from the database."""
#
# def deconstruct(self) -> dict:
# """Deconstructs this partition into a dict of attributes/fields."""
#
# return {"name": self.name()}
. Output only the next line. | ) -> Generator[PostgresPartition, None, None]: |
Next line prediction: <|code_start|> )
return model
def define_fake_materialized_view_model(
fields=None,
view_options={},
meta_options={},
model_base=PostgresMaterializedViewModel,
):
"""Defines a fake materialized view model."""
model = define_fake_model(
fields=fields,
model_base=model_base,
meta_options=meta_options,
ViewMeta=type("ViewMeta", (object,), view_options),
)
return model
def define_fake_partitioned_model(
fields=None, partitioning_options={}, meta_options={}
):
"""Defines a fake partitioned model."""
model = define_fake_model(
fields=fields,
<|code_end|>
. Use current file imports:
(import os
import sys
import uuid
from contextlib import contextmanager
from django.apps import AppConfig, apps
from django.db import connection
from psqlextra.models import (
PostgresMaterializedViewModel,
PostgresModel,
PostgresPartitionedModel,
PostgresViewModel,
))
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/models/view.py
# class PostgresMaterializedViewModel(
# PostgresViewModel, metaclass=PostgresViewModelMeta
# ):
# """Base class for creating a model that is a materialized view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# @classmethod
# def refresh(
# cls, concurrently: bool = False, using: Optional[str] = None
# ) -> None:
# """Refreshes this materialized view.
#
# Arguments:
# concurrently:
# Whether to tell PostgreSQL to refresh this
# materialized view concurrently.
#
# using:
# Optionally, the name of the database connection
# to use for refreshing the materialized view.
# """
#
# conn_name = using or "default"
#
# with connections[conn_name].schema_editor() as schema_editor:
# schema_editor.refresh_materialized_view_model(cls, concurrently)
#
# class PostgresViewModel(PostgresModel, metaclass=PostgresViewModelMeta):
# """Base class for creating a model that is a view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
. Output only the next line. | model_base=PostgresPartitionedModel, |
Here is a snippet: <|code_start|> }
if fields:
attributes.update(fields)
model = type(name, (model_base,), attributes)
apps.app_configs[attributes["app_label"]].models[name] = model
return model
def define_fake_view_model(
fields=None, view_options={}, meta_options={}, model_base=PostgresViewModel
):
"""Defines a fake view model."""
model = define_fake_model(
fields=fields,
model_base=model_base,
meta_options=meta_options,
ViewMeta=type("ViewMeta", (object,), view_options),
)
return model
def define_fake_materialized_view_model(
fields=None,
view_options={},
meta_options={},
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import uuid
from contextlib import contextmanager
from django.apps import AppConfig, apps
from django.db import connection
from psqlextra.models import (
PostgresMaterializedViewModel,
PostgresModel,
PostgresPartitionedModel,
PostgresViewModel,
)
and context from other files:
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/models/view.py
# class PostgresMaterializedViewModel(
# PostgresViewModel, metaclass=PostgresViewModelMeta
# ):
# """Base class for creating a model that is a materialized view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# @classmethod
# def refresh(
# cls, concurrently: bool = False, using: Optional[str] = None
# ) -> None:
# """Refreshes this materialized view.
#
# Arguments:
# concurrently:
# Whether to tell PostgreSQL to refresh this
# materialized view concurrently.
#
# using:
# Optionally, the name of the database connection
# to use for refreshing the materialized view.
# """
#
# conn_name = using or "default"
#
# with connections[conn_name].schema_editor() as schema_editor:
# schema_editor.refresh_materialized_view_model(cls, concurrently)
#
# class PostgresViewModel(PostgresModel, metaclass=PostgresViewModelMeta):
# """Base class for creating a model that is a view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
, which may include functions, classes, or code. Output only the next line. | model_base=PostgresMaterializedViewModel, |
Here is a snippet: <|code_start|>
def define_fake_model(
fields=None, model_base=PostgresModel, meta_options={}, **attributes
):
"""Defines a fake model (but does not create it in the database)."""
name = str(uuid.uuid4()).replace("-", "")[:8].title()
attributes = {
"app_label": meta_options.get("app_label") or "tests",
"__module__": __name__,
"__name__": name,
"Meta": type("Meta", (object,), meta_options),
**attributes,
}
if fields:
attributes.update(fields)
model = type(name, (model_base,), attributes)
apps.app_configs[attributes["app_label"]].models[name] = model
return model
def define_fake_view_model(
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import uuid
from contextlib import contextmanager
from django.apps import AppConfig, apps
from django.db import connection
from psqlextra.models import (
PostgresMaterializedViewModel,
PostgresModel,
PostgresPartitionedModel,
PostgresViewModel,
)
and context from other files:
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/models/view.py
# class PostgresMaterializedViewModel(
# PostgresViewModel, metaclass=PostgresViewModelMeta
# ):
# """Base class for creating a model that is a materialized view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# @classmethod
# def refresh(
# cls, concurrently: bool = False, using: Optional[str] = None
# ) -> None:
# """Refreshes this materialized view.
#
# Arguments:
# concurrently:
# Whether to tell PostgreSQL to refresh this
# materialized view concurrently.
#
# using:
# Optionally, the name of the database connection
# to use for refreshing the materialized view.
# """
#
# conn_name = using or "default"
#
# with connections[conn_name].schema_editor() as schema_editor:
# schema_editor.refresh_materialized_view_model(cls, concurrently)
#
# class PostgresViewModel(PostgresModel, metaclass=PostgresViewModelMeta):
# """Base class for creating a model that is a view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
, which may include functions, classes, or code. Output only the next line. | fields=None, view_options={}, meta_options={}, model_base=PostgresViewModel |
Predict the next line for this snippet: <|code_start|>
class PostgresModel(models.Model):
"""Base class for for taking advantage of PostgreSQL specific features."""
class Meta:
abstract = True
base_manager_name = "objects"
<|code_end|>
with the help of current file imports:
from django.db import models
from psqlextra.manager import PostgresManager
and context from other files:
# Path: psqlextra/manager/manager.py
# class PostgresManager(Manager.from_queryset(PostgresQuerySet)):
# """Adds support for PostgreSQL specifics."""
#
# use_in_migrations = True
#
# def __init__(self, *args, **kwargs):
# """Initializes a new instance of :see:PostgresManager."""
#
# super().__init__(*args, **kwargs)
#
# # make sure our back-end is set in at least one db and refuse to proceed
# has_psqlextra_backend = any(
# [
# db_settings
# for db_settings in settings.DATABASES.values()
# if "psqlextra" in db_settings["ENGINE"]
# ]
# )
#
# if not has_psqlextra_backend:
# raise ImproperlyConfigured(
# (
# "Could not locate the 'psqlextra.backend'. "
# "django-postgres-extra cannot function without "
# "the 'psqlextra.backend'. Set DATABASES.ENGINE."
# )
# )
#
# def truncate(
# self, cascade: bool = False, using: Optional[str] = None
# ) -> None:
# """Truncates this model/table using the TRUNCATE statement.
#
# This DELETES ALL ROWS. No signals will be fired.
#
# See: https://www.postgresql.org/docs/9.1/sql-truncate.html
#
# Arguments:
# cascade:
# Whether to delete dependent rows. If set to
# False, an error will be raised if there
# are rows in other tables referencing
# the rows you're trying to delete.
# """
#
# connection = connections[using or "default"]
# table_name = connection.ops.quote_name(self.model._meta.db_table)
#
# with connection.cursor() as cursor:
# sql = "TRUNCATE TABLE %s" % table_name
# if cascade:
# sql += " CASCADE"
#
# cursor.execute(sql)
, which may contain function names, class names, or code. Output only the next line. | objects = PostgresManager() |
Predict the next line for this snippet: <|code_start|>
class HStoreRequiredSchemaEditorSideEffect:
sql_hstore_required_create = (
"ALTER TABLE {table} "
"ADD CONSTRAINT {name} "
"CHECK (({field}->'{key}') "
"IS NOT NULL)"
)
sql_hstore_required_rename = (
"ALTER TABLE {table} "
"RENAME CONSTRAINT "
"{old_name} "
"TO "
"{new_name}"
)
sql_hstore_required_drop = (
"ALTER TABLE {table} " "DROP CONSTRAINT IF EXISTS {name}"
)
def create_model(self, model):
"""Ran when a new model is created."""
for field in model._meta.local_fields:
<|code_end|>
with the help of current file imports:
from psqlextra.fields import HStoreField
and context from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
, which may contain function names, class names, or code. Output only the next line. | if not isinstance(field, HStoreField): |
Predict the next line after this snippet: <|code_start|>
def test_hstore_unique_migration_create_drop_model():
"""Tests whether indexes are properly created and dropped when creating and
dropping a model."""
uniqueness = ["beer", "cookies"]
test = migrations.create_drop_model(
<|code_end|>
using the current file's imports:
import pytest
from django.db import transaction
from django.db.utils import IntegrityError
from psqlextra.fields import HStoreField
from . import migrations
from .fake_model import get_fake_model
and any relevant context from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | HStoreField(uniqueness=uniqueness), ["CREATE UNIQUE", "DROP INDEX"] |
Based on the snippet: <|code_start|> together"."""
test = migrations.alter_field(
HStoreField(uniqueness=[("beer1", "beer2")]),
HStoreField(uniqueness=[]),
["CREATE UNIQUE", "DROP INDEX"],
)
with test as calls:
assert len(calls.get("CREATE UNIQUE", [])) == 0
assert len(calls.get("DROP INDEX", [])) == 1
def test_hstore_unique_rename_field():
"""Tests whether renaming a field doesn't cause the index to be re-
created."""
test = migrations.rename_field(
HStoreField(uniqueness=["beer", "cookies"]),
["RENAME TO", "CREATE INDEX", "DROP INDEX"],
)
with test as calls:
assert len(calls.get("RENAME TO", [])) == 2
assert len(calls.get("CREATE UNIQUE", [])) == 0
assert len(calls.get("DROP INDEX", [])) == 0
def test_hstore_unique_enforcement():
"""Tests whether the constraints are actually properly enforced."""
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from django.db import transaction
from django.db.utils import IntegrityError
from psqlextra.fields import HStoreField
from . import migrations
from .fake_model import get_fake_model
and context (classes, functions, sometimes code) from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | model = get_fake_model({"title": HStoreField(uniqueness=["en"])}) |
Using the snippet: <|code_start|>
@pytest.fixture
def model():
"""Test models, where the first model has a foreign key relationship to the
second."""
<|code_end|>
, determine the next line of code. You have imports:
import django
import pytest
from django.db import models
from psqlextra.fields import HStoreField
from .fake_model import get_fake_model
and context (class names, function names, or code) available:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | return get_fake_model({"title": HStoreField()}) |
Here is a snippet: <|code_start|>
@pytest.fixture
def model():
"""Test models, where the first model has a foreign key relationship to the
second."""
<|code_end|>
. Write the next line using the current file imports:
import django
import pytest
from django.db import models
from psqlextra.fields import HStoreField
from .fake_model import get_fake_model
and context from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
, which may include functions, classes, or code. Output only the next line. | return get_fake_model({"title": HStoreField()}) |
Next line prediction: <|code_start|>
@pytest.fixture(scope="function", autouse=True)
def database_access(db):
"""Automatically enable database access for all tests."""
# enable the hstore extension on our database because
# our tests rely on it...
with connection.schema_editor() as schema_editor:
schema_editor.execute("CREATE EXTENSION IF NOT EXISTS hstore")
register_type_handlers(schema_editor.connection)
@pytest.fixture
def fake_app():
"""Creates a fake Django app and deletes it at the end of the test."""
<|code_end|>
. Use current file imports:
(import pytest
from django.contrib.postgres.signals import register_type_handlers
from django.db import connection
from .fake_model import define_fake_app)
and context including class names, function names, or small code snippets from other files:
# Path: tests/fake_model.py
# @contextmanager
# def define_fake_app():
# """Creates and registers a fake Django app."""
#
# name = "app_" + str(uuid.uuid4()).replace("-", "")[:8]
#
# app_config_cls = type(
# name + "Config",
# (AppConfig,),
# {"name": name, "path": os.path.dirname(__file__)},
# )
#
# app_config = app_config_cls(name, "")
# app_config.apps = apps
# app_config.models = {}
#
# apps.app_configs[name] = app_config
# sys.modules[name] = {}
#
# try:
# yield app_config
# finally:
# del apps.app_configs[name]
# del sys.modules[name]
. Output only the next line. | with define_fake_app() as fake_app: |
Given the following code snippet before the placeholder: <|code_start|>
class PostgresCreateMaterializedViewModel(CreateModel):
"""Creates the model as a native PostgreSQL 11.x materialzed view."""
serialization_expand_args = [
"fields",
"options",
"managers",
"view_options",
]
def __init__(
self,
name,
fields,
options=None,
view_options={},
bases=None,
managers=None,
):
super().__init__(name, fields, options, bases, managers)
self.view_options = view_options or {}
def state_forwards(self, app_label, state):
state.add_model(
<|code_end|>
, predict the next line using imports from the current file:
from django.db.migrations.operations.models import CreateModel
from psqlextra.backend.migrations.state import (
PostgresMaterializedViewModelState,
)
and context including class names, function names, and sometimes code from other files:
# Path: psqlextra/backend/migrations/state/materialized_view.py
# class PostgresMaterializedViewModelState(PostgresViewModelState):
# """Represents the state of a :see:PostgresMaterializedViewModel in the
# migrations."""
#
# @classmethod
# def _get_base_model_class(self) -> Type[PostgresMaterializedViewModel]:
# """Gets the class to use as a base class for rendered models."""
#
# return PostgresMaterializedViewModel
. Output only the next line. | PostgresMaterializedViewModelState( |
Given the code snippet: <|code_start|> ):
"""Initializes a new instance of :see:PostgresPartitionedModelState.
Arguments:
partitioning_options:
Dictionary of options for partitioning.
See: PostgresPartitionedModelMeta for a list.
"""
super().__init__(*args, **kwargs)
self.partitions: Dict[str, PostgresPartitionState] = {
partition.name: partition for partition in partitions
}
self.partitioning_options = dict(partitioning_options)
def add_partition(self, partition: PostgresPartitionState):
"""Adds a partition to this partitioned model state."""
self.partitions[partition.name] = partition
def delete_partition(self, name: str):
"""Deletes a partition from this partitioned model state."""
del self.partitions[name]
@classmethod
def _pre_new(
cls,
<|code_end|>
, generate the next line using the imports in this file:
from typing import Dict, List, Type
from psqlextra.models import PostgresPartitionedModel
from .model import PostgresModelState
and context (functions, classes, or occasionally code) from other files:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/backend/migrations/state/model.py
# class PostgresModelState(ModelState):
# """Base for custom model states.
#
# We need this base class to create some hooks into rendering models,
# creating new states and cloning state. Most of the logic resides
# here in the base class. Our derived classes implement the `_pre_*`
# methods.
# """
#
# @classmethod
# def from_model(
# cls, model: PostgresModel, *args, **kwargs
# ) -> "PostgresModelState":
# """Creates a new :see:PostgresModelState object from the specified
# model.
#
# We override this so derived classes get the chance to attach
# additional information to the newly created model state.
#
# We also need to patch up the base class for the model.
# """
#
# model_state = super().from_model(model, *args, **kwargs)
# model_state = cls._pre_new(model, model_state)
#
# # django does not add abstract bases as a base in migrations
# # because it assumes the base does not add anything important
# # in a migration.. but it does, so we replace the Model
# # base with the actual base
# bases = tuple()
# for base in model_state.bases:
# if issubclass(base, Model):
# bases += (cls._get_base_model_class(),)
# else:
# bases += (base,)
#
# model_state.bases = bases
# return model_state
#
# def clone(self) -> "PostgresModelState":
# """Gets an exact copy of this :see:PostgresModelState."""
#
# model_state = super().clone()
# return self._pre_clone(model_state)
#
# def render(self, apps):
# """Renders this state into an actual model."""
#
# # TODO: figure out a way to do this witout pretty much
# # copying the base class's implementation
#
# try:
# bases = tuple(
# (apps.get_model(base) if isinstance(base, str) else base)
# for base in self.bases
# )
# except LookupError:
# # TODO: this should be a InvalidBaseError
# raise ValueError(
# "Cannot resolve one or more bases from %r" % (self.bases,)
# )
#
# if isinstance(self.fields, Mapping):
# # In Django 3.1 `self.fields` became a `dict`
# fields = {
# name: field.clone() for name, field in self.fields.items()
# }
# else:
# # In Django < 3.1 `self.fields` is a list of (name, field) tuples
# fields = {name: field.clone() for name, field in self.fields}
#
# meta = type(
# "Meta",
# (),
# {"app_label": self.app_label, "apps": apps, **self.options},
# )
#
# attributes = {
# **fields,
# "Meta": meta,
# "__module__": "__fake__",
# **dict(self.construct_managers()),
# }
#
# return type(*self._pre_render(self.name, bases, attributes))
#
# @classmethod
# def _pre_new(
# cls, model: PostgresModel, model_state: "PostgresModelState"
# ) -> "PostgresModelState":
# """Called when a new model state is created from the specified
# model."""
#
# return model_state
#
# def _pre_clone(
# self, model_state: "PostgresModelState"
# ) -> "PostgresModelState":
# """Called when this model state is cloned."""
#
# return model_state
#
# def _pre_render(self, name: str, bases, attributes):
# """Called when this model state is rendered into a model."""
#
# return name, bases, attributes
#
# @classmethod
# def _get_base_model_class(self) -> Type[PostgresModel]:
# """Gets the class to use as a base class for rendered models."""
#
# return PostgresModel
. Output only the next line. | model: PostgresPartitionedModel, |
Predict the next line after this snippet: <|code_start|>
class PostgresListPartitionState(PostgresPartitionState):
"""Represents the state of a list partition for a
:see:PostgresPartitionedModel during a migration."""
def __init__(self, app_label: str, model_name: str, name: str, values):
super().__init__(app_label, model_name, name)
self.values = values
class PostgresHashPartitionState(PostgresPartitionState):
"""Represents the state of a hash partition for a
:see:PostgresPartitionedModel during a migration."""
def __init__(
self,
app_label: str,
model_name: str,
name: str,
modulus: int,
remainder: int,
):
super().__init__(app_label, model_name, name)
self.modulus = modulus
self.remainder = remainder
<|code_end|>
using the current file's imports:
from typing import Dict, List, Type
from psqlextra.models import PostgresPartitionedModel
from .model import PostgresModelState
and any relevant context from other files:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/backend/migrations/state/model.py
# class PostgresModelState(ModelState):
# """Base for custom model states.
#
# We need this base class to create some hooks into rendering models,
# creating new states and cloning state. Most of the logic resides
# here in the base class. Our derived classes implement the `_pre_*`
# methods.
# """
#
# @classmethod
# def from_model(
# cls, model: PostgresModel, *args, **kwargs
# ) -> "PostgresModelState":
# """Creates a new :see:PostgresModelState object from the specified
# model.
#
# We override this so derived classes get the chance to attach
# additional information to the newly created model state.
#
# We also need to patch up the base class for the model.
# """
#
# model_state = super().from_model(model, *args, **kwargs)
# model_state = cls._pre_new(model, model_state)
#
# # django does not add abstract bases as a base in migrations
# # because it assumes the base does not add anything important
# # in a migration.. but it does, so we replace the Model
# # base with the actual base
# bases = tuple()
# for base in model_state.bases:
# if issubclass(base, Model):
# bases += (cls._get_base_model_class(),)
# else:
# bases += (base,)
#
# model_state.bases = bases
# return model_state
#
# def clone(self) -> "PostgresModelState":
# """Gets an exact copy of this :see:PostgresModelState."""
#
# model_state = super().clone()
# return self._pre_clone(model_state)
#
# def render(self, apps):
# """Renders this state into an actual model."""
#
# # TODO: figure out a way to do this witout pretty much
# # copying the base class's implementation
#
# try:
# bases = tuple(
# (apps.get_model(base) if isinstance(base, str) else base)
# for base in self.bases
# )
# except LookupError:
# # TODO: this should be a InvalidBaseError
# raise ValueError(
# "Cannot resolve one or more bases from %r" % (self.bases,)
# )
#
# if isinstance(self.fields, Mapping):
# # In Django 3.1 `self.fields` became a `dict`
# fields = {
# name: field.clone() for name, field in self.fields.items()
# }
# else:
# # In Django < 3.1 `self.fields` is a list of (name, field) tuples
# fields = {name: field.clone() for name, field in self.fields}
#
# meta = type(
# "Meta",
# (),
# {"app_label": self.app_label, "apps": apps, **self.options},
# )
#
# attributes = {
# **fields,
# "Meta": meta,
# "__module__": "__fake__",
# **dict(self.construct_managers()),
# }
#
# return type(*self._pre_render(self.name, bases, attributes))
#
# @classmethod
# def _pre_new(
# cls, model: PostgresModel, model_state: "PostgresModelState"
# ) -> "PostgresModelState":
# """Called when a new model state is created from the specified
# model."""
#
# return model_state
#
# def _pre_clone(
# self, model_state: "PostgresModelState"
# ) -> "PostgresModelState":
# """Called when this model state is cloned."""
#
# return model_state
#
# def _pre_render(self, name: str, bases, attributes):
# """Called when this model state is rendered into a model."""
#
# return name, bases, attributes
#
# @classmethod
# def _get_base_model_class(self) -> Type[PostgresModel]:
# """Gets the class to use as a base class for rendered models."""
#
# return PostgresModel
. Output only the next line. | class PostgresPartitionedModelState(PostgresModelState): |
Using the snippet: <|code_start|>
class PostgresCreatePartitionedModel(CreateModel):
"""Creates the model as a native PostgreSQL 11.x partitioned table."""
serialization_expand_args = [
"fields",
"options",
"managers",
"partitioning_options",
]
def __init__(
self,
name,
fields,
options=None,
partitioning_options={},
bases=None,
managers=None,
):
super().__init__(name, fields, options, bases, managers)
self.partitioning_options = partitioning_options or {}
def state_forwards(self, app_label, state):
state.add_model(
<|code_end|>
, determine the next line of code. You have imports:
from django.db.migrations.operations.models import CreateModel
from psqlextra.backend.migrations.state import PostgresPartitionedModelState
and context (class names, function names, or code) available:
# Path: psqlextra/backend/migrations/state/partitioning.py
# class PostgresPartitionedModelState(PostgresModelState):
# """Represents the state of a :see:PostgresPartitionedModel in the
# migrations."""
#
# def __init__(
# self,
# *args,
# partitions: List[PostgresPartitionState] = [],
# partitioning_options={},
# **kwargs
# ):
# """Initializes a new instance of :see:PostgresPartitionedModelState.
#
# Arguments:
# partitioning_options:
# Dictionary of options for partitioning.
#
# See: PostgresPartitionedModelMeta for a list.
# """
#
# super().__init__(*args, **kwargs)
#
# self.partitions: Dict[str, PostgresPartitionState] = {
# partition.name: partition for partition in partitions
# }
# self.partitioning_options = dict(partitioning_options)
#
# def add_partition(self, partition: PostgresPartitionState):
# """Adds a partition to this partitioned model state."""
#
# self.partitions[partition.name] = partition
#
# def delete_partition(self, name: str):
# """Deletes a partition from this partitioned model state."""
#
# del self.partitions[name]
#
# @classmethod
# def _pre_new(
# cls,
# model: PostgresPartitionedModel,
# model_state: "PostgresPartitionedModelState",
# ) -> "PostgresPartitionedModelState":
# """Called when a new model state is created from the specified
# model."""
#
# model_state.partitions = dict()
# model_state.partitioning_options = dict(
# model._partitioning_meta.original_attrs
# )
# return model_state
#
# def _pre_clone(
# self, model_state: "PostgresPartitionedModelState"
# ) -> "PostgresPartitionedModelState":
# """Called when this model state is cloned."""
#
# model_state.partitions = dict(self.partitions)
# model_state.partitioning_options = dict(self.partitioning_options)
# return model_state
#
# def _pre_render(self, name: str, bases, attributes):
# """Called when this model state is rendered into a model."""
#
# partitioning_meta = type(
# "PartitioningMeta", (), dict(self.partitioning_options)
# )
# return (
# name,
# bases,
# {**attributes, "PartitioningMeta": partitioning_meta},
# )
#
# @classmethod
# def _get_base_model_class(self) -> Type[PostgresPartitionedModel]:
# """Gets the class to use as a base class for rendered models."""
#
# return PostgresPartitionedModel
. Output only the next line. | PostgresPartitionedModelState( |
Continue the code snippet: <|code_start|>
@pytest.mark.parametrize("conflict_action", ConflictAction.all())
def test_on_conflict(conflict_action):
"""Tests whether simple inserts work correctly."""
model = get_fake_model(
{
<|code_end|>
. Use current file imports:
import django
import pytest
from django.core.exceptions import SuspiciousOperation
from django.db import connection, models
from django.utils import timezone
from psqlextra.fields import HStoreField
from psqlextra.models import PostgresModel
from psqlextra.query import ConflictAction
from .fake_model import get_fake_model
and context (classes, functions, or code) from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | "title": HStoreField(uniqueness=["key1"]), |
Next line prediction: <|code_start|> sql_with_params = cls._view_query_as_sql_with_params(
new_class, view_query
)
view_meta = PostgresViewOptions(query=sql_with_params)
new_class.add_to_class("_view_meta", view_meta)
return new_class
@staticmethod
def _view_query_as_sql_with_params(
model: Model, view_query: ViewQuery
) -> Optional[SQLWithParams]:
"""Gets the query associated with the view as a raw SQL query with bind
parameters.
The query can be specified as a query set, raw SQL with params
or without params. The query can also be specified as a callable
which returns any of the above.
When copying the meta options from the model, we convert any
from the above to a raw SQL query with bind parameters. We do
this is because it is what the SQL driver understands and
we can easily serialize it into a migration.
"""
# might be a callable to support delayed imports
view_query = view_query() if callable(view_query) else view_query
# make sure we don't do a boolean check on query sets,
# because that might evaluate the query set
<|code_end|>
. Use current file imports:
(from typing import Callable, Optional, Union
from django.core.exceptions import ImproperlyConfigured
from django.db import connections
from django.db.models import Model
from django.db.models.base import ModelBase
from django.db.models.query import QuerySet
from psqlextra.type_assertions import is_query_set, is_sql, is_sql_with_params
from psqlextra.types import SQL, SQLWithParams
from .base import PostgresModel
from .options import PostgresViewOptions)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/type_assertions.py
# def is_query_set(value: Any) -> bool:
# """Gets whether the specified value is a :see:QuerySet."""
#
# return isinstance(value, QuerySet)
#
# def is_sql(value: Any) -> bool:
# """Gets whether the specified value could be a raw SQL query."""
#
# return isinstance(value, str)
#
# def is_sql_with_params(value: Any) -> bool:
# """Gets whether the specified value is a tuple of a SQL query (as a string)
# and a tuple of bind parameters."""
#
# return (
# isinstance(value, tuple)
# and len(value) == 2
# and is_sql(value[0])
# and isinstance(value[1], Iterable)
# and not isinstance(value[1], (str, bytes, bytearray))
# )
#
# Path: psqlextra/types.py
# SQL = str
# NOTHING = "NOTHING"
# UPDATE = "UPDATE"
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
# class StrEnum(str, Enum):
# class ConflictAction(Enum):
# class PostgresPartitioningMethod(StrEnum):
# def all(cls) -> List["StrEnum"]:
# def values(cls) -> List[str]:
# def __str__(self) -> str:
# def all(cls) -> List["ConflictAction"]:
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/options.py
# class PostgresViewOptions:
# """Container for :see:PostgresView and :see:PostgresMaterializedView
# options.
#
# This is where attributes copied from the model's `ViewMeta` are
# held.
# """
#
# def __init__(self, query: Optional[SQLWithParams]):
# self.query = query
# self.original_attrs: Dict[str, Optional[SQLWithParams]] = dict(
# query=self.query
# )
. Output only the next line. | if not is_query_set(view_query) and not view_query: |
Given snippet: <|code_start|> return new_class
@staticmethod
def _view_query_as_sql_with_params(
model: Model, view_query: ViewQuery
) -> Optional[SQLWithParams]:
"""Gets the query associated with the view as a raw SQL query with bind
parameters.
The query can be specified as a query set, raw SQL with params
or without params. The query can also be specified as a callable
which returns any of the above.
When copying the meta options from the model, we convert any
from the above to a raw SQL query with bind parameters. We do
this is because it is what the SQL driver understands and
we can easily serialize it into a migration.
"""
# might be a callable to support delayed imports
view_query = view_query() if callable(view_query) else view_query
# make sure we don't do a boolean check on query sets,
# because that might evaluate the query set
if not is_query_set(view_query) and not view_query:
return None
is_valid_view_query = (
is_query_set(view_query)
or is_sql_with_params(view_query)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from typing import Callable, Optional, Union
from django.core.exceptions import ImproperlyConfigured
from django.db import connections
from django.db.models import Model
from django.db.models.base import ModelBase
from django.db.models.query import QuerySet
from psqlextra.type_assertions import is_query_set, is_sql, is_sql_with_params
from psqlextra.types import SQL, SQLWithParams
from .base import PostgresModel
from .options import PostgresViewOptions
and context:
# Path: psqlextra/type_assertions.py
# def is_query_set(value: Any) -> bool:
# """Gets whether the specified value is a :see:QuerySet."""
#
# return isinstance(value, QuerySet)
#
# def is_sql(value: Any) -> bool:
# """Gets whether the specified value could be a raw SQL query."""
#
# return isinstance(value, str)
#
# def is_sql_with_params(value: Any) -> bool:
# """Gets whether the specified value is a tuple of a SQL query (as a string)
# and a tuple of bind parameters."""
#
# return (
# isinstance(value, tuple)
# and len(value) == 2
# and is_sql(value[0])
# and isinstance(value[1], Iterable)
# and not isinstance(value[1], (str, bytes, bytearray))
# )
#
# Path: psqlextra/types.py
# SQL = str
# NOTHING = "NOTHING"
# UPDATE = "UPDATE"
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
# class StrEnum(str, Enum):
# class ConflictAction(Enum):
# class PostgresPartitioningMethod(StrEnum):
# def all(cls) -> List["StrEnum"]:
# def values(cls) -> List[str]:
# def __str__(self) -> str:
# def all(cls) -> List["ConflictAction"]:
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/options.py
# class PostgresViewOptions:
# """Container for :see:PostgresView and :see:PostgresMaterializedView
# options.
#
# This is where attributes copied from the model's `ViewMeta` are
# held.
# """
#
# def __init__(self, query: Optional[SQLWithParams]):
# self.query = query
# self.original_attrs: Dict[str, Optional[SQLWithParams]] = dict(
# query=self.query
# )
which might include code, classes, or functions. Output only the next line. | or is_sql(view_query) |
Predict the next line for this snippet: <|code_start|> new_class.add_to_class("_view_meta", view_meta)
return new_class
@staticmethod
def _view_query_as_sql_with_params(
model: Model, view_query: ViewQuery
) -> Optional[SQLWithParams]:
"""Gets the query associated with the view as a raw SQL query with bind
parameters.
The query can be specified as a query set, raw SQL with params
or without params. The query can also be specified as a callable
which returns any of the above.
When copying the meta options from the model, we convert any
from the above to a raw SQL query with bind parameters. We do
this is because it is what the SQL driver understands and
we can easily serialize it into a migration.
"""
# might be a callable to support delayed imports
view_query = view_query() if callable(view_query) else view_query
# make sure we don't do a boolean check on query sets,
# because that might evaluate the query set
if not is_query_set(view_query) and not view_query:
return None
is_valid_view_query = (
is_query_set(view_query)
<|code_end|>
with the help of current file imports:
from typing import Callable, Optional, Union
from django.core.exceptions import ImproperlyConfigured
from django.db import connections
from django.db.models import Model
from django.db.models.base import ModelBase
from django.db.models.query import QuerySet
from psqlextra.type_assertions import is_query_set, is_sql, is_sql_with_params
from psqlextra.types import SQL, SQLWithParams
from .base import PostgresModel
from .options import PostgresViewOptions
and context from other files:
# Path: psqlextra/type_assertions.py
# def is_query_set(value: Any) -> bool:
# """Gets whether the specified value is a :see:QuerySet."""
#
# return isinstance(value, QuerySet)
#
# def is_sql(value: Any) -> bool:
# """Gets whether the specified value could be a raw SQL query."""
#
# return isinstance(value, str)
#
# def is_sql_with_params(value: Any) -> bool:
# """Gets whether the specified value is a tuple of a SQL query (as a string)
# and a tuple of bind parameters."""
#
# return (
# isinstance(value, tuple)
# and len(value) == 2
# and is_sql(value[0])
# and isinstance(value[1], Iterable)
# and not isinstance(value[1], (str, bytes, bytearray))
# )
#
# Path: psqlextra/types.py
# SQL = str
# NOTHING = "NOTHING"
# UPDATE = "UPDATE"
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
# class StrEnum(str, Enum):
# class ConflictAction(Enum):
# class PostgresPartitioningMethod(StrEnum):
# def all(cls) -> List["StrEnum"]:
# def values(cls) -> List[str]:
# def __str__(self) -> str:
# def all(cls) -> List["ConflictAction"]:
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/options.py
# class PostgresViewOptions:
# """Container for :see:PostgresView and :see:PostgresMaterializedView
# options.
#
# This is where attributes copied from the model's `ViewMeta` are
# held.
# """
#
# def __init__(self, query: Optional[SQLWithParams]):
# self.query = query
# self.original_attrs: Dict[str, Optional[SQLWithParams]] = dict(
# query=self.query
# )
, which may contain function names, class names, or code. Output only the next line. | or is_sql_with_params(view_query) |
Predict the next line after this snippet: <|code_start|> return None
is_valid_view_query = (
is_query_set(view_query)
or is_sql_with_params(view_query)
or is_sql(view_query)
)
if not is_valid_view_query:
raise ImproperlyConfigured(
(
"Model '%s' is not properly configured to be a view."
" Set the `query` attribute on the `ViewMeta` class"
" to be a valid `django.db.models.query.QuerySet`"
" SQL string, or tuple of SQL string and params."
)
% (model.__name__)
)
# querysets can easily be converted into sql, params
if is_query_set(view_query):
return view_query.query.sql_with_params()
# query was already specified in the target format
if is_sql_with_params(view_query):
return view_query
return view_query, tuple()
<|code_end|>
using the current file's imports:
from typing import Callable, Optional, Union
from django.core.exceptions import ImproperlyConfigured
from django.db import connections
from django.db.models import Model
from django.db.models.base import ModelBase
from django.db.models.query import QuerySet
from psqlextra.type_assertions import is_query_set, is_sql, is_sql_with_params
from psqlextra.types import SQL, SQLWithParams
from .base import PostgresModel
from .options import PostgresViewOptions
and any relevant context from other files:
# Path: psqlextra/type_assertions.py
# def is_query_set(value: Any) -> bool:
# """Gets whether the specified value is a :see:QuerySet."""
#
# return isinstance(value, QuerySet)
#
# def is_sql(value: Any) -> bool:
# """Gets whether the specified value could be a raw SQL query."""
#
# return isinstance(value, str)
#
# def is_sql_with_params(value: Any) -> bool:
# """Gets whether the specified value is a tuple of a SQL query (as a string)
# and a tuple of bind parameters."""
#
# return (
# isinstance(value, tuple)
# and len(value) == 2
# and is_sql(value[0])
# and isinstance(value[1], Iterable)
# and not isinstance(value[1], (str, bytes, bytearray))
# )
#
# Path: psqlextra/types.py
# SQL = str
# NOTHING = "NOTHING"
# UPDATE = "UPDATE"
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
# class StrEnum(str, Enum):
# class ConflictAction(Enum):
# class PostgresPartitioningMethod(StrEnum):
# def all(cls) -> List["StrEnum"]:
# def values(cls) -> List[str]:
# def __str__(self) -> str:
# def all(cls) -> List["ConflictAction"]:
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/options.py
# class PostgresViewOptions:
# """Container for :see:PostgresView and :see:PostgresMaterializedView
# options.
#
# This is where attributes copied from the model's `ViewMeta` are
# held.
# """
#
# def __init__(self, query: Optional[SQLWithParams]):
# self.query = query
# self.original_attrs: Dict[str, Optional[SQLWithParams]] = dict(
# query=self.query
# )
. Output only the next line. | class PostgresViewModel(PostgresModel, metaclass=PostgresViewModelMeta): |
Based on the snippet: <|code_start|>
ViewQueryValue = Union[QuerySet, SQLWithParams, SQL]
ViewQuery = Optional[Union[ViewQueryValue, Callable[[], ViewQueryValue]]]
class PostgresViewModelMeta(ModelBase):
"""Custom meta class for :see:PostgresView and
:see:PostgresMaterializedView.
This meta class extracts attributes from the inner
`ViewMeta` class and copies it onto a `_vew_meta`
attribute. This is similar to how Django's `_meta` works.
"""
def __new__(cls, name, bases, attrs, **kwargs):
new_class = super().__new__(cls, name, bases, attrs, **kwargs)
meta_class = attrs.pop("ViewMeta", None)
view_query = getattr(meta_class, "query", None)
sql_with_params = cls._view_query_as_sql_with_params(
new_class, view_query
)
<|code_end|>
, predict the immediate next line with the help of imports:
from typing import Callable, Optional, Union
from django.core.exceptions import ImproperlyConfigured
from django.db import connections
from django.db.models import Model
from django.db.models.base import ModelBase
from django.db.models.query import QuerySet
from psqlextra.type_assertions import is_query_set, is_sql, is_sql_with_params
from psqlextra.types import SQL, SQLWithParams
from .base import PostgresModel
from .options import PostgresViewOptions
and context (classes, functions, sometimes code) from other files:
# Path: psqlextra/type_assertions.py
# def is_query_set(value: Any) -> bool:
# """Gets whether the specified value is a :see:QuerySet."""
#
# return isinstance(value, QuerySet)
#
# def is_sql(value: Any) -> bool:
# """Gets whether the specified value could be a raw SQL query."""
#
# return isinstance(value, str)
#
# def is_sql_with_params(value: Any) -> bool:
# """Gets whether the specified value is a tuple of a SQL query (as a string)
# and a tuple of bind parameters."""
#
# return (
# isinstance(value, tuple)
# and len(value) == 2
# and is_sql(value[0])
# and isinstance(value[1], Iterable)
# and not isinstance(value[1], (str, bytes, bytearray))
# )
#
# Path: psqlextra/types.py
# SQL = str
# NOTHING = "NOTHING"
# UPDATE = "UPDATE"
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
# class StrEnum(str, Enum):
# class ConflictAction(Enum):
# class PostgresPartitioningMethod(StrEnum):
# def all(cls) -> List["StrEnum"]:
# def values(cls) -> List[str]:
# def __str__(self) -> str:
# def all(cls) -> List["ConflictAction"]:
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/options.py
# class PostgresViewOptions:
# """Container for :see:PostgresView and :see:PostgresMaterializedView
# options.
#
# This is where attributes copied from the model's `ViewMeta` are
# held.
# """
#
# def __init__(self, query: Optional[SQLWithParams]):
# self.query = query
# self.original_attrs: Dict[str, Optional[SQLWithParams]] = dict(
# query=self.query
# )
. Output only the next line. | view_meta = PostgresViewOptions(query=sql_with_params) |
Given snippet: <|code_start|>
def test_hstore_field_deconstruct():
"""Tests whether the :see:HStoreField's deconstruct() method works
properly."""
original_kwargs = dict(uniqueness=["beer", "other"], required=[])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from psqlextra.fields import HStoreField
and context:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
which might include code, classes, or functions. Output only the next line. | _, _, _, new_kwargs = HStoreField(**original_kwargs).deconstruct() |
Given the code snippet: <|code_start|>
ROW_COUNT = 10000
@pytest.mark.benchmark()
def test_upsert_bulk_naive(benchmark):
model = get_fake_model(
{"field": models.CharField(max_length=255, unique=True)}
)
rows = []
random_values = []
for i in range(0, ROW_COUNT):
random_value = str(uuid.uuid4())
random_values.append(random_value)
rows.append(model(field=random_value))
model.objects.bulk_create(rows)
def _native_upsert(model, random_values):
"""Performs a concurrency safe upsert using the native PostgreSQL
upsert."""
rows = [dict(field=random_value) for random_value in random_values]
for row in rows:
<|code_end|>
, generate the next line using the imports in this file:
import uuid
import pytest
from django.db import models
from psqlextra.query import ConflictAction
from ..fake_model import get_fake_model
and context (functions, classes, or occasionally code) from other files:
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | model.objects.on_conflict(["field"], ConflictAction.UPDATE).insert( |
Given the following code snippet before the placeholder: <|code_start|>
ROW_COUNT = 10000
@pytest.mark.benchmark()
def test_upsert_bulk_naive(benchmark):
<|code_end|>
, predict the next line using imports from the current file:
import uuid
import pytest
from django.db import models
from psqlextra.query import ConflictAction
from ..fake_model import get_fake_model
and context including class names, function names, and sometimes code from other files:
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | model = get_fake_model( |
Predict the next line after this snippet: <|code_start|>
class HStoreUniqueSchemaEditorSideEffect:
sql_hstore_unique_create = (
"CREATE UNIQUE INDEX IF NOT EXISTS " "{name} ON {table} " "({columns})"
)
sql_hstore_unique_rename = (
"ALTER INDEX " "{old_name} " "RENAME TO " "{new_name}"
)
sql_hstore_unique_drop = "DROP INDEX IF EXISTS {name}"
def create_model(self, model):
"""Ran when a new model is created."""
for field in model._meta.local_fields:
<|code_end|>
using the current file's imports:
from psqlextra.fields import HStoreField
and any relevant context from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
. Output only the next line. | if not isinstance(field, HStoreField): |
Next line prediction: <|code_start|>
class PostgresMaterializedViewModelState(PostgresViewModelState):
"""Represents the state of a :see:PostgresMaterializedViewModel in the
migrations."""
@classmethod
<|code_end|>
. Use current file imports:
(from typing import Type
from psqlextra.models import PostgresMaterializedViewModel
from .view import PostgresViewModelState)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/models/view.py
# class PostgresMaterializedViewModel(
# PostgresViewModel, metaclass=PostgresViewModelMeta
# ):
# """Base class for creating a model that is a materialized view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# @classmethod
# def refresh(
# cls, concurrently: bool = False, using: Optional[str] = None
# ) -> None:
# """Refreshes this materialized view.
#
# Arguments:
# concurrently:
# Whether to tell PostgreSQL to refresh this
# materialized view concurrently.
#
# using:
# Optionally, the name of the database connection
# to use for refreshing the materialized view.
# """
#
# conn_name = using or "default"
#
# with connections[conn_name].schema_editor() as schema_editor:
# schema_editor.refresh_materialized_view_model(cls, concurrently)
#
# Path: psqlextra/backend/migrations/state/view.py
# class PostgresViewModelState(PostgresModelState):
# """Represents the state of a :see:PostgresViewModel in the migrations."""
#
# def __init__(self, *args, view_options={}, **kwargs):
# """Initializes a new instance of :see:PostgresViewModelState.
#
# Arguments:
# view_options:
# Dictionary of options for views.
# See: PostgresViewModelMeta for a list.
# """
#
# super().__init__(*args, **kwargs)
#
# self.view_options = dict(view_options)
#
# @classmethod
# def _pre_new(
# cls, model: PostgresViewModel, model_state: "PostgresViewModelState"
# ) -> "PostgresViewModelState":
# """Called when a new model state is created from the specified
# model."""
#
# model_state.view_options = dict(model._view_meta.original_attrs)
# return model_state
#
# def _pre_clone(
# self, model_state: "PostgresViewModelState"
# ) -> "PostgresViewModelState":
# """Called when this model state is cloned."""
#
# model_state.view_options = dict(self.view_options)
# return model_state
#
# def _pre_render(self, name: str, bases, attributes):
# """Called when this model state is rendered into a model."""
#
# view_meta = type("ViewMeta", (), dict(self.view_options))
# return name, bases, {**attributes, "ViewMeta": view_meta}
#
# @classmethod
# def _get_base_model_class(self) -> Type[PostgresViewModel]:
# """Gets the class to use as a base class for rendered models."""
#
# return PostgresViewModel
. Output only the next line. | def _get_base_model_class(self) -> Type[PostgresMaterializedViewModel]: |
Next line prediction: <|code_start|>
def partition_by_current_time(
model: PostgresPartitionedModel,
count: int,
years: Optional[int] = None,
months: Optional[int] = None,
weeks: Optional[int] = None,
days: Optional[int] = None,
max_age: Optional[relativedelta] = None,
<|code_end|>
. Use current file imports:
(from typing import Optional
from dateutil.relativedelta import relativedelta
from psqlextra.models import PostgresPartitionedModel
from .config import PostgresPartitioningConfig
from .current_time_strategy import PostgresCurrentTimePartitioningStrategy
from .time_partition_size import PostgresTimePartitionSize)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/partitioning/config.py
# class PostgresPartitioningConfig:
# """Configuration for partitioning a specific model according to the
# specified strategy."""
#
# def __init__(
# self,
# model: PostgresPartitionedModel,
# strategy: PostgresPartitioningStrategy,
# ) -> None:
# self.model = model
# self.strategy = strategy
#
# Path: psqlextra/partitioning/current_time_strategy.py
# class PostgresCurrentTimePartitioningStrategy(
# PostgresRangePartitioningStrategy
# ):
# """Implments a time based partitioning strategy where each partition
# contains values for a specific time period.
#
# All buckets will be equal in size and start at the start of the
# unit. With monthly partitioning, partitions start on the 1st and
# with weekly partitioning, partitions start on monday.
# """
#
# def __init__(
# self,
# size: PostgresTimePartitionSize,
# count: int,
# max_age: Optional[relativedelta] = None,
# ) -> None:
# """Initializes a new instance of :see:PostgresTimePartitioningStrategy.
#
# Arguments:
# size:
# The size of each partition.
#
# count:
# The amount of partitions to create ahead
# from the current date/time.
#
# max_age:
# Maximum age of a partition. Partitions
# older than this are deleted during
# auto cleanup.
# """
#
# self.size = size
# self.count = count
# self.max_age = max_age
#
# def to_create(self) -> Generator[PostgresTimePartition, None, None]:
# current_datetime = self.size.start(self.get_start_datetime())
#
# for _ in range(self.count):
# yield PostgresTimePartition(
# start_datetime=current_datetime, size=self.size
# )
#
# current_datetime += self.size.as_delta()
#
# def to_delete(self) -> Generator[PostgresTimePartition, None, None]:
# if not self.max_age:
# return
#
# current_datetime = self.size.start(
# self.get_start_datetime() - self.max_age
# )
#
# while True:
# yield PostgresTimePartition(
# start_datetime=current_datetime, size=self.size
# )
#
# current_datetime -= self.size.as_delta()
#
# def get_start_datetime(self) -> datetime:
# return datetime.now(timezone.utc)
#
# Path: psqlextra/partitioning/time_partition_size.py
# class PostgresTimePartitionSize:
# """Size of a time-based range partition table."""
#
# unit: PostgresTimePartitionUnit
# value: int
#
# def __init__(
# self,
# years: Optional[int] = None,
# months: Optional[int] = None,
# weeks: Optional[int] = None,
# days: Optional[int] = None,
# ) -> None:
# sizes = [years, months, weeks, days]
#
# if not any(sizes):
# raise PostgresPartitioningError("Partition cannot be 0 in size.")
#
# if len([size for size in sizes if size and size > 0]) > 1:
# raise PostgresPartitioningError(
# "Partition can only have on size unit."
# )
#
# if years:
# self.unit = PostgresTimePartitionUnit.YEARS
# self.value = years
# elif months:
# self.unit = PostgresTimePartitionUnit.MONTHS
# self.value = months
# elif weeks:
# self.unit = PostgresTimePartitionUnit.WEEKS
# self.value = weeks
# elif days:
# self.unit = PostgresTimePartitionUnit.DAYS
# self.value = days
# else:
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit"
# )
#
# def as_delta(self) -> relativedelta:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return relativedelta(years=self.value)
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return relativedelta(months=self.value)
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return relativedelta(weeks=self.value)
#
# if self.unit == PostgresTimePartitionUnit.DAYS:
# return relativedelta(days=self.value)
#
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit: %s" % self.unit
# )
#
# def start(self, dt: datetime) -> datetime:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return self._ensure_datetime(dt.replace(month=1, day=1))
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return self._ensure_datetime(dt.replace(day=1))
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return self._ensure_datetime(dt - relativedelta(days=dt.weekday()))
#
# return self._ensure_datetime(dt)
#
# @staticmethod
# def _ensure_datetime(dt: Union[date, datetime]) -> datetime:
# return datetime(year=dt.year, month=dt.month, day=dt.day)
#
# def __repr__(self) -> str:
# return "PostgresTimePartitionSize<%s, %s>" % (self.unit, self.value)
. Output only the next line. | ) -> PostgresPartitioningConfig: |
Using the snippet: <|code_start|>
class PostgresAddListPartition(PostgresPartitionOperation):
"""Adds a new list partition to a :see:PartitionedPostgresModel."""
def __init__(self, model_name, name, values):
"""Initializes new instance of :see:AddListPartition.
Arguments:
model_name:
The name of the :see:PartitionedPostgresModel.
name:
The name to give to the new partition table.
values:
Partition key values that should be
stored in this partition.
"""
super().__init__(model_name, name)
self.values = values
def state_forwards(self, app_label, state):
model = state.models[(app_label, self.model_name_lower)]
model.add_partition(
<|code_end|>
, determine the next line of code. You have imports:
from psqlextra.backend.migrations.state import PostgresListPartitionState
from .partition import PostgresPartitionOperation
and context (class names, function names, or code) available:
# Path: psqlextra/backend/migrations/state/partitioning.py
# class PostgresListPartitionState(PostgresPartitionState):
# """Represents the state of a list partition for a
# :see:PostgresPartitionedModel during a migration."""
#
# def __init__(self, app_label: str, model_name: str, name: str, values):
# super().__init__(app_label, model_name, name)
#
# self.values = values
#
# Path: psqlextra/backend/migrations/operations/partition.py
# class PostgresPartitionOperation(Operation):
# def __init__(self, model_name: str, name: str) -> None:
# """Initializes new instance of :see:AddDefaultPartition.
#
# Arguments:
# model_name:
# The name of the :see:PartitionedPostgresModel.
#
# name:
# The name to give to the new partition table.
# """
#
# self.model_name = model_name
# self.model_name_lower = model_name.lower()
# self.name = name
#
# def deconstruct(self):
# kwargs = {"model_name": self.model_name, "name": self.name}
# return (self.__class__.__qualname__, [], kwargs)
#
# def state_forwards(self, *args, **kwargs):
# pass
#
# def state_backwards(self, *args, **kwargs):
# pass
#
# def reduce(self, *args, **kwargs):
# # PartitionOperation doesn't break migrations optimizations
# return True
. Output only the next line. | PostgresListPartitionState( |
Here is a snippet: <|code_start|>
PartitionList = List[Tuple[PostgresPartitionedModel, List[PostgresPartition]]]
class PostgresPartitioningManager:
"""Helps managing partitions by automatically creating new partitions and
deleting old ones according to the configuration."""
<|code_end|>
. Write the next line using the current file imports:
from typing import List, Optional, Tuple
from django.db import connections
from psqlextra.models import PostgresPartitionedModel
from .config import PostgresPartitioningConfig
from .constants import AUTO_PARTITIONED_COMMENT
from .error import PostgresPartitioningError
from .partition import PostgresPartition
from .plan import PostgresModelPartitioningPlan, PostgresPartitioningPlan
and context from other files:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/partitioning/config.py
# class PostgresPartitioningConfig:
# """Configuration for partitioning a specific model according to the
# specified strategy."""
#
# def __init__(
# self,
# model: PostgresPartitionedModel,
# strategy: PostgresPartitioningStrategy,
# ) -> None:
# self.model = model
# self.strategy = strategy
#
# Path: psqlextra/partitioning/constants.py
# AUTO_PARTITIONED_COMMENT = "psqlextra_auto_partitioned"
#
# Path: psqlextra/partitioning/error.py
# class PostgresPartitioningError(RuntimeError):
# """Raised when the partitioning configuration is broken or automatically
# creating/deleting partitions fails."""
#
# Path: psqlextra/partitioning/partition.py
# class PostgresPartition:
# """Base class for a PostgreSQL table partition."""
#
# @abstractmethod
# def name(self) -> str:
# """Generates/computes the name for this partition."""
#
# @abstractmethod
# def create(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# comment: Optional[str] = None,
# ) -> None:
# """Creates this partition in the database."""
#
# @abstractmethod
# def delete(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# ) -> None:
# """Deletes this partition from the database."""
#
# def deconstruct(self) -> dict:
# """Deconstructs this partition into a dict of attributes/fields."""
#
# return {"name": self.name()}
#
# Path: psqlextra/partitioning/plan.py
# class PostgresModelPartitioningPlan:
# """Describes the partitions that are going to be created/deleted for a
# particular partitioning config.
#
# A "partitioning config" applies to one model.
# """
#
# config: PostgresPartitioningConfig
# creations: List[PostgresPartition] = field(default_factory=list)
# deletions: List[PostgresPartition] = field(default_factory=list)
#
# def apply(self, using: Optional[str]) -> None:
# """Applies this partitioning plan by creating and deleting the planned
# partitions.
#
# Applying the plan runs in a transaction.
#
# Arguments:
# using:
# Name of the database connection to use.
# """
#
# connection = connections[using or "default"]
#
# with transaction.atomic():
# with connection.schema_editor() as schema_editor:
# for partition in self.creations:
# partition.create(
# self.config.model,
# schema_editor,
# comment=AUTO_PARTITIONED_COMMENT,
# )
#
# for partition in self.deletions:
# partition.delete(self.config.model, schema_editor)
#
# def print(self) -> None:
# """Prints this model plan to the terminal in a readable format."""
#
# print(f"{self.config.model.__name__}:")
#
# for partition in self.deletions:
# print(" - %s" % partition.name())
# for key, value in partition.deconstruct().items():
# print(f" {key}: {value}")
#
# for partition in self.creations:
# print(" + %s" % partition.name())
# for key, value in partition.deconstruct().items():
# print(f" {key}: {value}")
#
# class PostgresPartitioningPlan:
# """Describes the partitions that are going to be created/deleted."""
#
# model_plans: List[PostgresModelPartitioningPlan]
#
# @property
# def creations(self) -> List[PostgresPartition]:
# """Gets a complete flat list of the partitions that are going to be
# created."""
#
# creations = []
# for model_plan in self.model_plans:
# creations.extend(model_plan.creations)
# return creations
#
# @property
# def deletions(self) -> List[PostgresPartition]:
# """Gets a complete flat list of the partitions that are going to be
# deleted."""
#
# deletions = []
# for model_plan in self.model_plans:
# deletions.extend(model_plan.deletions)
# return deletions
#
# def apply(self, using: Optional[str] = None) -> None:
# """Applies this plan by creating/deleting all planned partitions."""
#
# for model_plan in self.model_plans:
# model_plan.apply(using=using)
#
# def print(self) -> None:
# """Prints this plan to the terminal in a readable format."""
#
# for model_plan in self.model_plans:
# model_plan.print()
# print("")
#
# create_count = len(self.creations)
# delete_count = len(self.deletions)
#
# print(f"{delete_count} partitions will be deleted")
# print(f"{create_count} partitions will be created")
, which may include functions, classes, or code. Output only the next line. | def __init__(self, configs: List[PostgresPartitioningConfig]) -> None: |
Given snippet: <|code_start|>
PartitionList = List[Tuple[PostgresPartitionedModel, List[PostgresPartition]]]
class PostgresPartitioningManager:
"""Helps managing partitions by automatically creating new partitions and
deleting old ones according to the configuration."""
def __init__(self, configs: List[PostgresPartitioningConfig]) -> None:
self.configs = configs
self._validate_configs(self.configs)
def plan(
self,
skip_create: bool = False,
skip_delete: bool = False,
using: Optional[str] = None,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from typing import List, Optional, Tuple
from django.db import connections
from psqlextra.models import PostgresPartitionedModel
from .config import PostgresPartitioningConfig
from .constants import AUTO_PARTITIONED_COMMENT
from .error import PostgresPartitioningError
from .partition import PostgresPartition
from .plan import PostgresModelPartitioningPlan, PostgresPartitioningPlan
and context:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/partitioning/config.py
# class PostgresPartitioningConfig:
# """Configuration for partitioning a specific model according to the
# specified strategy."""
#
# def __init__(
# self,
# model: PostgresPartitionedModel,
# strategy: PostgresPartitioningStrategy,
# ) -> None:
# self.model = model
# self.strategy = strategy
#
# Path: psqlextra/partitioning/constants.py
# AUTO_PARTITIONED_COMMENT = "psqlextra_auto_partitioned"
#
# Path: psqlextra/partitioning/error.py
# class PostgresPartitioningError(RuntimeError):
# """Raised when the partitioning configuration is broken or automatically
# creating/deleting partitions fails."""
#
# Path: psqlextra/partitioning/partition.py
# class PostgresPartition:
# """Base class for a PostgreSQL table partition."""
#
# @abstractmethod
# def name(self) -> str:
# """Generates/computes the name for this partition."""
#
# @abstractmethod
# def create(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# comment: Optional[str] = None,
# ) -> None:
# """Creates this partition in the database."""
#
# @abstractmethod
# def delete(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# ) -> None:
# """Deletes this partition from the database."""
#
# def deconstruct(self) -> dict:
# """Deconstructs this partition into a dict of attributes/fields."""
#
# return {"name": self.name()}
#
# Path: psqlextra/partitioning/plan.py
# class PostgresModelPartitioningPlan:
# """Describes the partitions that are going to be created/deleted for a
# particular partitioning config.
#
# A "partitioning config" applies to one model.
# """
#
# config: PostgresPartitioningConfig
# creations: List[PostgresPartition] = field(default_factory=list)
# deletions: List[PostgresPartition] = field(default_factory=list)
#
# def apply(self, using: Optional[str]) -> None:
# """Applies this partitioning plan by creating and deleting the planned
# partitions.
#
# Applying the plan runs in a transaction.
#
# Arguments:
# using:
# Name of the database connection to use.
# """
#
# connection = connections[using or "default"]
#
# with transaction.atomic():
# with connection.schema_editor() as schema_editor:
# for partition in self.creations:
# partition.create(
# self.config.model,
# schema_editor,
# comment=AUTO_PARTITIONED_COMMENT,
# )
#
# for partition in self.deletions:
# partition.delete(self.config.model, schema_editor)
#
# def print(self) -> None:
# """Prints this model plan to the terminal in a readable format."""
#
# print(f"{self.config.model.__name__}:")
#
# for partition in self.deletions:
# print(" - %s" % partition.name())
# for key, value in partition.deconstruct().items():
# print(f" {key}: {value}")
#
# for partition in self.creations:
# print(" + %s" % partition.name())
# for key, value in partition.deconstruct().items():
# print(f" {key}: {value}")
#
# class PostgresPartitioningPlan:
# """Describes the partitions that are going to be created/deleted."""
#
# model_plans: List[PostgresModelPartitioningPlan]
#
# @property
# def creations(self) -> List[PostgresPartition]:
# """Gets a complete flat list of the partitions that are going to be
# created."""
#
# creations = []
# for model_plan in self.model_plans:
# creations.extend(model_plan.creations)
# return creations
#
# @property
# def deletions(self) -> List[PostgresPartition]:
# """Gets a complete flat list of the partitions that are going to be
# deleted."""
#
# deletions = []
# for model_plan in self.model_plans:
# deletions.extend(model_plan.deletions)
# return deletions
#
# def apply(self, using: Optional[str] = None) -> None:
# """Applies this plan by creating/deleting all planned partitions."""
#
# for model_plan in self.model_plans:
# model_plan.apply(using=using)
#
# def print(self) -> None:
# """Prints this plan to the terminal in a readable format."""
#
# for model_plan in self.model_plans:
# model_plan.print()
# print("")
#
# create_count = len(self.creations)
# delete_count = len(self.deletions)
#
# print(f"{delete_count} partitions will be deleted")
# print(f"{create_count} partitions will be created")
which might include code, classes, or functions. Output only the next line. | ) -> PostgresPartitioningPlan: |
Given snippet: <|code_start|> parser.add_argument(
"app_label",
type=str,
help="Label of the app the materialized view model is in.",
)
parser.add_argument(
"model_name",
type=str,
help="Name of the materialized view model to refresh.",
)
parser.add_argument(
"--concurrently",
"-c",
action="store_true",
help="Whether to refresh the materialized view model concurrently.",
required=False,
default=False,
)
def handle(self, *app_labels, **options):
app_label = options.get("app_label")
model_name = options.get("model_name")
concurrently = options.get("concurrently")
model = apps.get_model(app_label, model_name)
if not model:
raise OperationalError(f"Cannot find a model named '{model_name}'")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.apps import apps
from django.core.management.base import BaseCommand
from django.db.utils import NotSupportedError, OperationalError
from psqlextra.models import PostgresMaterializedViewModel
and context:
# Path: psqlextra/models/view.py
# class PostgresMaterializedViewModel(
# PostgresViewModel, metaclass=PostgresViewModelMeta
# ):
# """Base class for creating a model that is a materialized view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# @classmethod
# def refresh(
# cls, concurrently: bool = False, using: Optional[str] = None
# ) -> None:
# """Refreshes this materialized view.
#
# Arguments:
# concurrently:
# Whether to tell PostgreSQL to refresh this
# materialized view concurrently.
#
# using:
# Optionally, the name of the database connection
# to use for refreshing the materialized view.
# """
#
# conn_name = using or "default"
#
# with connections[conn_name].schema_editor() as schema_editor:
# schema_editor.refresh_materialized_view_model(cls, concurrently)
which might include code, classes, or functions. Output only the next line. | if not issubclass(model, PostgresMaterializedViewModel): |
Here is a snippet: <|code_start|>
def test_hstore_required_migration_create_drop_model():
"""Tests whether constraints are properly created and dropped when creating
and dropping a model."""
required = ["beer", "cookies"]
test = migrations.create_drop_model(
<|code_end|>
. Write the next line using the current file imports:
import pytest
from django.db.utils import IntegrityError
from psqlextra.fields import HStoreField
from . import migrations
from .fake_model import get_fake_model
and context from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
, which may include functions, classes, or code. Output only the next line. | HStoreField(required=required), ["ADD CONSTRAINT", "DROP CONSTRAINT"] |
Given snippet: <|code_start|>
test = migrations.alter_field(
HStoreField(required=["beer"]),
HStoreField(required=[]),
["ADD CONSTRAINT", "DROP CONSTRAINT"],
)
with test as calls:
assert len(calls.get("ADD CONSTRAINT", [])) == 0
assert len(calls.get("DROP CONSTRAINT", [])) == 1
def test_hstore_required_rename_field():
"""Tests whether renaming a field doesn't cause the constraint to be re-
created."""
test = migrations.rename_field(
HStoreField(required=["beer", "cookies"]),
["RENAME CONSTRAINT", "ADD CONSTRAINT", "DROP CONSTRAINT"],
)
with test as calls:
assert len(calls.get("RENAME CONSTRAINT", [])) == 2
assert len(calls.get("ADD CONSTRAINT", [])) == 0
assert len(calls.get("DROP CONSTRAINT", [])) == 0
def test_hstore_required_required_enforcement():
"""Tests whether the constraints are actually properly enforced."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from django.db.utils import IntegrityError
from psqlextra.fields import HStoreField
from . import migrations
from .fake_model import get_fake_model
and context:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
which might include code, classes, or functions. Output only the next line. | model = get_fake_model({"title": HStoreField(required=["en"])}) |
Next line prediction: <|code_start|> unit. With monthly partitioning, partitions start on the 1st and
with weekly partitioning, partitions start on monday.
"""
def __init__(
self,
size: PostgresTimePartitionSize,
count: int,
max_age: Optional[relativedelta] = None,
) -> None:
"""Initializes a new instance of :see:PostgresTimePartitioningStrategy.
Arguments:
size:
The size of each partition.
count:
The amount of partitions to create ahead
from the current date/time.
max_age:
Maximum age of a partition. Partitions
older than this are deleted during
auto cleanup.
"""
self.size = size
self.count = count
self.max_age = max_age
<|code_end|>
. Use current file imports:
(from datetime import datetime, timezone
from typing import Generator, Optional
from dateutil.relativedelta import relativedelta
from .range_strategy import PostgresRangePartitioningStrategy
from .time_partition import PostgresTimePartition
from .time_partition_size import PostgresTimePartitionSize)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/partitioning/range_strategy.py
# class PostgresRangePartitioningStrategy(PostgresPartitioningStrategy):
# """Base class for implementing a partitioning strategy for a range
# partitioned table."""
#
# Path: psqlextra/partitioning/time_partition.py
# class PostgresTimePartition(PostgresRangePartition):
# """Time-based range table partition.
#
# :see:PostgresTimePartitioningStrategy for more info.
# """
#
# _unit_name_format = {
# PostgresTimePartitionUnit.YEARS: "%Y",
# PostgresTimePartitionUnit.MONTHS: "%Y_%b",
# PostgresTimePartitionUnit.WEEKS: "%Y_week_%W",
# PostgresTimePartitionUnit.DAYS: "%Y_%b_%d",
# }
#
# def __init__(
# self, size: PostgresTimePartitionSize, start_datetime: datetime
# ) -> None:
# end_datetime = start_datetime + size.as_delta()
#
# super().__init__(
# from_values=start_datetime.strftime("%Y-%m-%d"),
# to_values=end_datetime.strftime("%Y-%m-%d"),
# )
#
# self.size = size
# self.start_datetime = start_datetime
# self.end_datetime = end_datetime
#
# def name(self) -> str:
# name_format = self._unit_name_format.get(self.size.unit)
# if not name_format:
# raise PostgresPartitioningError("Unknown size/unit")
#
# return self.start_datetime.strftime(name_format).lower()
#
# def deconstruct(self) -> dict:
# return {
# **super().deconstruct(),
# "size_unit": self.size.unit.value,
# "size_value": self.size.value,
# }
#
# Path: psqlextra/partitioning/time_partition_size.py
# class PostgresTimePartitionSize:
# """Size of a time-based range partition table."""
#
# unit: PostgresTimePartitionUnit
# value: int
#
# def __init__(
# self,
# years: Optional[int] = None,
# months: Optional[int] = None,
# weeks: Optional[int] = None,
# days: Optional[int] = None,
# ) -> None:
# sizes = [years, months, weeks, days]
#
# if not any(sizes):
# raise PostgresPartitioningError("Partition cannot be 0 in size.")
#
# if len([size for size in sizes if size and size > 0]) > 1:
# raise PostgresPartitioningError(
# "Partition can only have on size unit."
# )
#
# if years:
# self.unit = PostgresTimePartitionUnit.YEARS
# self.value = years
# elif months:
# self.unit = PostgresTimePartitionUnit.MONTHS
# self.value = months
# elif weeks:
# self.unit = PostgresTimePartitionUnit.WEEKS
# self.value = weeks
# elif days:
# self.unit = PostgresTimePartitionUnit.DAYS
# self.value = days
# else:
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit"
# )
#
# def as_delta(self) -> relativedelta:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return relativedelta(years=self.value)
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return relativedelta(months=self.value)
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return relativedelta(weeks=self.value)
#
# if self.unit == PostgresTimePartitionUnit.DAYS:
# return relativedelta(days=self.value)
#
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit: %s" % self.unit
# )
#
# def start(self, dt: datetime) -> datetime:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return self._ensure_datetime(dt.replace(month=1, day=1))
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return self._ensure_datetime(dt.replace(day=1))
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return self._ensure_datetime(dt - relativedelta(days=dt.weekday()))
#
# return self._ensure_datetime(dt)
#
# @staticmethod
# def _ensure_datetime(dt: Union[date, datetime]) -> datetime:
# return datetime(year=dt.year, month=dt.month, day=dt.day)
#
# def __repr__(self) -> str:
# return "PostgresTimePartitionSize<%s, %s>" % (self.unit, self.value)
. Output only the next line. | def to_create(self) -> Generator[PostgresTimePartition, None, None]: |
Given snippet: <|code_start|>
class PostgresCurrentTimePartitioningStrategy(
PostgresRangePartitioningStrategy
):
"""Implments a time based partitioning strategy where each partition
contains values for a specific time period.
All buckets will be equal in size and start at the start of the
unit. With monthly partitioning, partitions start on the 1st and
with weekly partitioning, partitions start on monday.
"""
def __init__(
self,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import datetime, timezone
from typing import Generator, Optional
from dateutil.relativedelta import relativedelta
from .range_strategy import PostgresRangePartitioningStrategy
from .time_partition import PostgresTimePartition
from .time_partition_size import PostgresTimePartitionSize
and context:
# Path: psqlextra/partitioning/range_strategy.py
# class PostgresRangePartitioningStrategy(PostgresPartitioningStrategy):
# """Base class for implementing a partitioning strategy for a range
# partitioned table."""
#
# Path: psqlextra/partitioning/time_partition.py
# class PostgresTimePartition(PostgresRangePartition):
# """Time-based range table partition.
#
# :see:PostgresTimePartitioningStrategy for more info.
# """
#
# _unit_name_format = {
# PostgresTimePartitionUnit.YEARS: "%Y",
# PostgresTimePartitionUnit.MONTHS: "%Y_%b",
# PostgresTimePartitionUnit.WEEKS: "%Y_week_%W",
# PostgresTimePartitionUnit.DAYS: "%Y_%b_%d",
# }
#
# def __init__(
# self, size: PostgresTimePartitionSize, start_datetime: datetime
# ) -> None:
# end_datetime = start_datetime + size.as_delta()
#
# super().__init__(
# from_values=start_datetime.strftime("%Y-%m-%d"),
# to_values=end_datetime.strftime("%Y-%m-%d"),
# )
#
# self.size = size
# self.start_datetime = start_datetime
# self.end_datetime = end_datetime
#
# def name(self) -> str:
# name_format = self._unit_name_format.get(self.size.unit)
# if not name_format:
# raise PostgresPartitioningError("Unknown size/unit")
#
# return self.start_datetime.strftime(name_format).lower()
#
# def deconstruct(self) -> dict:
# return {
# **super().deconstruct(),
# "size_unit": self.size.unit.value,
# "size_value": self.size.value,
# }
#
# Path: psqlextra/partitioning/time_partition_size.py
# class PostgresTimePartitionSize:
# """Size of a time-based range partition table."""
#
# unit: PostgresTimePartitionUnit
# value: int
#
# def __init__(
# self,
# years: Optional[int] = None,
# months: Optional[int] = None,
# weeks: Optional[int] = None,
# days: Optional[int] = None,
# ) -> None:
# sizes = [years, months, weeks, days]
#
# if not any(sizes):
# raise PostgresPartitioningError("Partition cannot be 0 in size.")
#
# if len([size for size in sizes if size and size > 0]) > 1:
# raise PostgresPartitioningError(
# "Partition can only have on size unit."
# )
#
# if years:
# self.unit = PostgresTimePartitionUnit.YEARS
# self.value = years
# elif months:
# self.unit = PostgresTimePartitionUnit.MONTHS
# self.value = months
# elif weeks:
# self.unit = PostgresTimePartitionUnit.WEEKS
# self.value = weeks
# elif days:
# self.unit = PostgresTimePartitionUnit.DAYS
# self.value = days
# else:
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit"
# )
#
# def as_delta(self) -> relativedelta:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return relativedelta(years=self.value)
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return relativedelta(months=self.value)
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return relativedelta(weeks=self.value)
#
# if self.unit == PostgresTimePartitionUnit.DAYS:
# return relativedelta(days=self.value)
#
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit: %s" % self.unit
# )
#
# def start(self, dt: datetime) -> datetime:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return self._ensure_datetime(dt.replace(month=1, day=1))
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return self._ensure_datetime(dt.replace(day=1))
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return self._ensure_datetime(dt - relativedelta(days=dt.weekday()))
#
# return self._ensure_datetime(dt)
#
# @staticmethod
# def _ensure_datetime(dt: Union[date, datetime]) -> datetime:
# return datetime(year=dt.year, month=dt.month, day=dt.day)
#
# def __repr__(self) -> str:
# return "PostgresTimePartitionSize<%s, %s>" % (self.unit, self.value)
which might include code, classes, or functions. Output only the next line. | size: PostgresTimePartitionSize, |
Next line prediction: <|code_start|>
class PostgresPartitionedModelMeta(ModelBase):
"""Custom meta class for :see:PostgresPartitionedModel.
This meta class extracts attributes from the inner
`PartitioningMeta` class and copies it onto a `_partitioning_meta`
attribute. This is similar to how Django's `_meta` works.
"""
<|code_end|>
. Use current file imports:
(from django.db.models.base import ModelBase
from psqlextra.types import PostgresPartitioningMethod
from .base import PostgresModel
from .options import PostgresPartitionedModelOptions)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/types.py
# class PostgresPartitioningMethod(StrEnum):
# """Methods of partitioning supported by PostgreSQL 11.x native support for
# table partitioning."""
#
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/options.py
# class PostgresPartitionedModelOptions:
# """Container for :see:PostgresPartitionedModel options.
#
# This is where attributes copied from the model's `PartitioningMeta`
# are held.
# """
#
# def __init__(self, method: PostgresPartitioningMethod, key: List[str]):
# self.method = method
# self.key = key
# self.original_attrs: Dict[
# str, Union[PostgresPartitioningMethod, List[str]]
# ] = dict(method=method, key=key)
. Output only the next line. | default_method = PostgresPartitioningMethod.RANGE |
Given snippet: <|code_start|>
class PostgresPartitionedModelMeta(ModelBase):
"""Custom meta class for :see:PostgresPartitionedModel.
This meta class extracts attributes from the inner
`PartitioningMeta` class and copies it onto a `_partitioning_meta`
attribute. This is similar to how Django's `_meta` works.
"""
default_method = PostgresPartitioningMethod.RANGE
default_key = []
def __new__(cls, name, bases, attrs, **kwargs):
new_class = super().__new__(cls, name, bases, attrs, **kwargs)
meta_class = attrs.pop("PartitioningMeta", None)
method = getattr(meta_class, "method", None)
key = getattr(meta_class, "key", None)
patitioning_meta = PostgresPartitionedModelOptions(
method=method or cls.default_method, key=key or cls.default_key
)
new_class.add_to_class("_partitioning_meta", patitioning_meta)
return new_class
class PostgresPartitionedModel(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.db.models.base import ModelBase
from psqlextra.types import PostgresPartitioningMethod
from .base import PostgresModel
from .options import PostgresPartitionedModelOptions
and context:
# Path: psqlextra/types.py
# class PostgresPartitioningMethod(StrEnum):
# """Methods of partitioning supported by PostgreSQL 11.x native support for
# table partitioning."""
#
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/options.py
# class PostgresPartitionedModelOptions:
# """Container for :see:PostgresPartitionedModel options.
#
# This is where attributes copied from the model's `PartitioningMeta`
# are held.
# """
#
# def __init__(self, method: PostgresPartitioningMethod, key: List[str]):
# self.method = method
# self.key = key
# self.original_attrs: Dict[
# str, Union[PostgresPartitioningMethod, List[str]]
# ] = dict(method=method, key=key)
which might include code, classes, or functions. Output only the next line. | PostgresModel, metaclass=PostgresPartitionedModelMeta |
Predict the next line for this snippet: <|code_start|>
class PostgresPartitionedModelMeta(ModelBase):
"""Custom meta class for :see:PostgresPartitionedModel.
This meta class extracts attributes from the inner
`PartitioningMeta` class and copies it onto a `_partitioning_meta`
attribute. This is similar to how Django's `_meta` works.
"""
default_method = PostgresPartitioningMethod.RANGE
default_key = []
def __new__(cls, name, bases, attrs, **kwargs):
new_class = super().__new__(cls, name, bases, attrs, **kwargs)
meta_class = attrs.pop("PartitioningMeta", None)
method = getattr(meta_class, "method", None)
key = getattr(meta_class, "key", None)
<|code_end|>
with the help of current file imports:
from django.db.models.base import ModelBase
from psqlextra.types import PostgresPartitioningMethod
from .base import PostgresModel
from .options import PostgresPartitionedModelOptions
and context from other files:
# Path: psqlextra/types.py
# class PostgresPartitioningMethod(StrEnum):
# """Methods of partitioning supported by PostgreSQL 11.x native support for
# table partitioning."""
#
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
#
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
# """Base class for for taking advantage of PostgreSQL specific features."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# objects = PostgresManager()
#
# Path: psqlextra/models/options.py
# class PostgresPartitionedModelOptions:
# """Container for :see:PostgresPartitionedModel options.
#
# This is where attributes copied from the model's `PartitioningMeta`
# are held.
# """
#
# def __init__(self, method: PostgresPartitioningMethod, key: List[str]):
# self.method = method
# self.key = key
# self.original_attrs: Dict[
# str, Union[PostgresPartitioningMethod, List[str]]
# ] = dict(method=method, key=key)
, which may contain function names, class names, or code. Output only the next line. | patitioning_meta = PostgresPartitionedModelOptions( |
Given snippet: <|code_start|>
def test_partitioned_model_abstract():
"""Tests whether :see:PostgresPartitionedModel is abstract."""
assert PostgresPartitionedModel._meta.abstract
def test_partitioning_model_options_meta():
"""Tests whether the `_partitioning_meta` attribute is available on the
class (created by the meta class) and not just creating when the model is
instantiated."""
assert PostgresPartitionedModel._partitioning_meta
def test_partitioned_model_default_options():
"""Tests whether the default partitioning options are set as expected on.
:see:PostgresPartitionedModel.
"""
model = define_fake_partitioned_model()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from psqlextra.models import PostgresPartitionedModel
from psqlextra.types import PostgresPartitioningMethod
from .fake_model import define_fake_partitioned_model
and context:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/types.py
# class PostgresPartitioningMethod(StrEnum):
# """Methods of partitioning supported by PostgreSQL 11.x native support for
# table partitioning."""
#
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
#
# Path: tests/fake_model.py
# def define_fake_partitioned_model(
# fields=None, partitioning_options={}, meta_options={}
# ):
# """Defines a fake partitioned model."""
#
# model = define_fake_model(
# fields=fields,
# model_base=PostgresPartitionedModel,
# meta_options=meta_options,
# PartitioningMeta=type(
# "PartitioningMeta", (object,), partitioning_options
# ),
# )
#
# return model
which might include code, classes, or functions. Output only the next line. | assert model._partitioning_meta.method == PostgresPartitioningMethod.RANGE |
Based on the snippet: <|code_start|>
def test_partitioned_model_abstract():
"""Tests whether :see:PostgresPartitionedModel is abstract."""
assert PostgresPartitionedModel._meta.abstract
def test_partitioning_model_options_meta():
"""Tests whether the `_partitioning_meta` attribute is available on the
class (created by the meta class) and not just creating when the model is
instantiated."""
assert PostgresPartitionedModel._partitioning_meta
def test_partitioned_model_default_options():
"""Tests whether the default partitioning options are set as expected on.
:see:PostgresPartitionedModel.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from psqlextra.models import PostgresPartitionedModel
from psqlextra.types import PostgresPartitioningMethod
from .fake_model import define_fake_partitioned_model
and context (classes, functions, sometimes code) from other files:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/types.py
# class PostgresPartitioningMethod(StrEnum):
# """Methods of partitioning supported by PostgreSQL 11.x native support for
# table partitioning."""
#
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
#
# Path: tests/fake_model.py
# def define_fake_partitioned_model(
# fields=None, partitioning_options={}, meta_options={}
# ):
# """Defines a fake partitioned model."""
#
# model = define_fake_model(
# fields=fields,
# model_base=PostgresPartitionedModel,
# meta_options=meta_options,
# PartitioningMeta=type(
# "PartitioningMeta", (object,), partitioning_options
# ),
# )
#
# return model
. Output only the next line. | model = define_fake_partitioned_model() |
Next line prediction: <|code_start|>
def test_on_conflict_nothing():
"""Tests whether simple insert NOTHING works correctly."""
model = get_fake_model(
{
<|code_end|>
. Use current file imports:
(import pytest
from django.db import models
from psqlextra.fields import HStoreField
from psqlextra.query import ConflictAction
from .fake_model import get_fake_model)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | "title": HStoreField(uniqueness=["key1"]), |
Next line prediction: <|code_start|>
def test_on_conflict_nothing():
"""Tests whether simple insert NOTHING works correctly."""
model = get_fake_model(
{
"title": HStoreField(uniqueness=["key1"]),
"cookies": models.CharField(max_length=255, null=True),
}
)
# row does not conflict, new row should be created
obj1 = model.objects.on_conflict(
<|code_end|>
. Use current file imports:
(import pytest
from django.db import models
from psqlextra.fields import HStoreField
from psqlextra.query import ConflictAction
from .fake_model import get_fake_model)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | [("title", "key1")], ConflictAction.NOTHING |
Using the snippet: <|code_start|>class PostgresTimePartition(PostgresRangePartition):
"""Time-based range table partition.
:see:PostgresTimePartitioningStrategy for more info.
"""
_unit_name_format = {
PostgresTimePartitionUnit.YEARS: "%Y",
PostgresTimePartitionUnit.MONTHS: "%Y_%b",
PostgresTimePartitionUnit.WEEKS: "%Y_week_%W",
PostgresTimePartitionUnit.DAYS: "%Y_%b_%d",
}
def __init__(
self, size: PostgresTimePartitionSize, start_datetime: datetime
) -> None:
end_datetime = start_datetime + size.as_delta()
super().__init__(
from_values=start_datetime.strftime("%Y-%m-%d"),
to_values=end_datetime.strftime("%Y-%m-%d"),
)
self.size = size
self.start_datetime = start_datetime
self.end_datetime = end_datetime
def name(self) -> str:
name_format = self._unit_name_format.get(self.size.unit)
if not name_format:
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime
from .error import PostgresPartitioningError
from .range_partition import PostgresRangePartition
from .time_partition_size import (
PostgresTimePartitionSize,
PostgresTimePartitionUnit,
)
and context (class names, function names, or code) available:
# Path: psqlextra/partitioning/error.py
# class PostgresPartitioningError(RuntimeError):
# """Raised when the partitioning configuration is broken or automatically
# creating/deleting partitions fails."""
#
# Path: psqlextra/partitioning/range_partition.py
# class PostgresRangePartition(PostgresPartition):
# """Base class for a PostgreSQL table partition in a range partitioned
# table."""
#
# def __init__(self, from_values: Any, to_values: Any) -> None:
# self.from_values = from_values
# self.to_values = to_values
#
# def deconstruct(self) -> dict:
# return {
# **super().deconstruct(),
# "from_values": self.from_values,
# "to_values": self.to_values,
# }
#
# def create(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# comment: Optional[str] = None,
# ) -> None:
# schema_editor.add_range_partition(
# model=model,
# name=self.name(),
# from_values=self.from_values,
# to_values=self.to_values,
# comment=comment,
# )
#
# def delete(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# ) -> None:
# schema_editor.delete_partition(model, self.name())
#
# Path: psqlextra/partitioning/time_partition_size.py
# class PostgresTimePartitionSize:
# """Size of a time-based range partition table."""
#
# unit: PostgresTimePartitionUnit
# value: int
#
# def __init__(
# self,
# years: Optional[int] = None,
# months: Optional[int] = None,
# weeks: Optional[int] = None,
# days: Optional[int] = None,
# ) -> None:
# sizes = [years, months, weeks, days]
#
# if not any(sizes):
# raise PostgresPartitioningError("Partition cannot be 0 in size.")
#
# if len([size for size in sizes if size and size > 0]) > 1:
# raise PostgresPartitioningError(
# "Partition can only have on size unit."
# )
#
# if years:
# self.unit = PostgresTimePartitionUnit.YEARS
# self.value = years
# elif months:
# self.unit = PostgresTimePartitionUnit.MONTHS
# self.value = months
# elif weeks:
# self.unit = PostgresTimePartitionUnit.WEEKS
# self.value = weeks
# elif days:
# self.unit = PostgresTimePartitionUnit.DAYS
# self.value = days
# else:
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit"
# )
#
# def as_delta(self) -> relativedelta:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return relativedelta(years=self.value)
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return relativedelta(months=self.value)
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return relativedelta(weeks=self.value)
#
# if self.unit == PostgresTimePartitionUnit.DAYS:
# return relativedelta(days=self.value)
#
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit: %s" % self.unit
# )
#
# def start(self, dt: datetime) -> datetime:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return self._ensure_datetime(dt.replace(month=1, day=1))
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return self._ensure_datetime(dt.replace(day=1))
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return self._ensure_datetime(dt - relativedelta(days=dt.weekday()))
#
# return self._ensure_datetime(dt)
#
# @staticmethod
# def _ensure_datetime(dt: Union[date, datetime]) -> datetime:
# return datetime(year=dt.year, month=dt.month, day=dt.day)
#
# def __repr__(self) -> str:
# return "PostgresTimePartitionSize<%s, %s>" % (self.unit, self.value)
#
# class PostgresTimePartitionUnit(enum.Enum):
# YEARS = "years"
# MONTHS = "months"
# WEEKS = "weeks"
# DAYS = "days"
. Output only the next line. | raise PostgresPartitioningError("Unknown size/unit") |
Next line prediction: <|code_start|>
class PostgresTimePartition(PostgresRangePartition):
"""Time-based range table partition.
:see:PostgresTimePartitioningStrategy for more info.
"""
_unit_name_format = {
PostgresTimePartitionUnit.YEARS: "%Y",
PostgresTimePartitionUnit.MONTHS: "%Y_%b",
PostgresTimePartitionUnit.WEEKS: "%Y_week_%W",
PostgresTimePartitionUnit.DAYS: "%Y_%b_%d",
}
def __init__(
<|code_end|>
. Use current file imports:
(from datetime import datetime
from .error import PostgresPartitioningError
from .range_partition import PostgresRangePartition
from .time_partition_size import (
PostgresTimePartitionSize,
PostgresTimePartitionUnit,
))
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/partitioning/error.py
# class PostgresPartitioningError(RuntimeError):
# """Raised when the partitioning configuration is broken or automatically
# creating/deleting partitions fails."""
#
# Path: psqlextra/partitioning/range_partition.py
# class PostgresRangePartition(PostgresPartition):
# """Base class for a PostgreSQL table partition in a range partitioned
# table."""
#
# def __init__(self, from_values: Any, to_values: Any) -> None:
# self.from_values = from_values
# self.to_values = to_values
#
# def deconstruct(self) -> dict:
# return {
# **super().deconstruct(),
# "from_values": self.from_values,
# "to_values": self.to_values,
# }
#
# def create(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# comment: Optional[str] = None,
# ) -> None:
# schema_editor.add_range_partition(
# model=model,
# name=self.name(),
# from_values=self.from_values,
# to_values=self.to_values,
# comment=comment,
# )
#
# def delete(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# ) -> None:
# schema_editor.delete_partition(model, self.name())
#
# Path: psqlextra/partitioning/time_partition_size.py
# class PostgresTimePartitionSize:
# """Size of a time-based range partition table."""
#
# unit: PostgresTimePartitionUnit
# value: int
#
# def __init__(
# self,
# years: Optional[int] = None,
# months: Optional[int] = None,
# weeks: Optional[int] = None,
# days: Optional[int] = None,
# ) -> None:
# sizes = [years, months, weeks, days]
#
# if not any(sizes):
# raise PostgresPartitioningError("Partition cannot be 0 in size.")
#
# if len([size for size in sizes if size and size > 0]) > 1:
# raise PostgresPartitioningError(
# "Partition can only have on size unit."
# )
#
# if years:
# self.unit = PostgresTimePartitionUnit.YEARS
# self.value = years
# elif months:
# self.unit = PostgresTimePartitionUnit.MONTHS
# self.value = months
# elif weeks:
# self.unit = PostgresTimePartitionUnit.WEEKS
# self.value = weeks
# elif days:
# self.unit = PostgresTimePartitionUnit.DAYS
# self.value = days
# else:
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit"
# )
#
# def as_delta(self) -> relativedelta:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return relativedelta(years=self.value)
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return relativedelta(months=self.value)
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return relativedelta(weeks=self.value)
#
# if self.unit == PostgresTimePartitionUnit.DAYS:
# return relativedelta(days=self.value)
#
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit: %s" % self.unit
# )
#
# def start(self, dt: datetime) -> datetime:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return self._ensure_datetime(dt.replace(month=1, day=1))
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return self._ensure_datetime(dt.replace(day=1))
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return self._ensure_datetime(dt - relativedelta(days=dt.weekday()))
#
# return self._ensure_datetime(dt)
#
# @staticmethod
# def _ensure_datetime(dt: Union[date, datetime]) -> datetime:
# return datetime(year=dt.year, month=dt.month, day=dt.day)
#
# def __repr__(self) -> str:
# return "PostgresTimePartitionSize<%s, %s>" % (self.unit, self.value)
#
# class PostgresTimePartitionUnit(enum.Enum):
# YEARS = "years"
# MONTHS = "months"
# WEEKS = "weeks"
# DAYS = "days"
. Output only the next line. | self, size: PostgresTimePartitionSize, start_datetime: datetime |
Predict the next line for this snippet: <|code_start|>
class PostgresTimePartition(PostgresRangePartition):
"""Time-based range table partition.
:see:PostgresTimePartitioningStrategy for more info.
"""
_unit_name_format = {
<|code_end|>
with the help of current file imports:
from datetime import datetime
from .error import PostgresPartitioningError
from .range_partition import PostgresRangePartition
from .time_partition_size import (
PostgresTimePartitionSize,
PostgresTimePartitionUnit,
)
and context from other files:
# Path: psqlextra/partitioning/error.py
# class PostgresPartitioningError(RuntimeError):
# """Raised when the partitioning configuration is broken or automatically
# creating/deleting partitions fails."""
#
# Path: psqlextra/partitioning/range_partition.py
# class PostgresRangePartition(PostgresPartition):
# """Base class for a PostgreSQL table partition in a range partitioned
# table."""
#
# def __init__(self, from_values: Any, to_values: Any) -> None:
# self.from_values = from_values
# self.to_values = to_values
#
# def deconstruct(self) -> dict:
# return {
# **super().deconstruct(),
# "from_values": self.from_values,
# "to_values": self.to_values,
# }
#
# def create(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# comment: Optional[str] = None,
# ) -> None:
# schema_editor.add_range_partition(
# model=model,
# name=self.name(),
# from_values=self.from_values,
# to_values=self.to_values,
# comment=comment,
# )
#
# def delete(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# ) -> None:
# schema_editor.delete_partition(model, self.name())
#
# Path: psqlextra/partitioning/time_partition_size.py
# class PostgresTimePartitionSize:
# """Size of a time-based range partition table."""
#
# unit: PostgresTimePartitionUnit
# value: int
#
# def __init__(
# self,
# years: Optional[int] = None,
# months: Optional[int] = None,
# weeks: Optional[int] = None,
# days: Optional[int] = None,
# ) -> None:
# sizes = [years, months, weeks, days]
#
# if not any(sizes):
# raise PostgresPartitioningError("Partition cannot be 0 in size.")
#
# if len([size for size in sizes if size and size > 0]) > 1:
# raise PostgresPartitioningError(
# "Partition can only have on size unit."
# )
#
# if years:
# self.unit = PostgresTimePartitionUnit.YEARS
# self.value = years
# elif months:
# self.unit = PostgresTimePartitionUnit.MONTHS
# self.value = months
# elif weeks:
# self.unit = PostgresTimePartitionUnit.WEEKS
# self.value = weeks
# elif days:
# self.unit = PostgresTimePartitionUnit.DAYS
# self.value = days
# else:
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit"
# )
#
# def as_delta(self) -> relativedelta:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return relativedelta(years=self.value)
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return relativedelta(months=self.value)
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return relativedelta(weeks=self.value)
#
# if self.unit == PostgresTimePartitionUnit.DAYS:
# return relativedelta(days=self.value)
#
# raise PostgresPartitioningError(
# "Unsupported time partitioning unit: %s" % self.unit
# )
#
# def start(self, dt: datetime) -> datetime:
# if self.unit == PostgresTimePartitionUnit.YEARS:
# return self._ensure_datetime(dt.replace(month=1, day=1))
#
# if self.unit == PostgresTimePartitionUnit.MONTHS:
# return self._ensure_datetime(dt.replace(day=1))
#
# if self.unit == PostgresTimePartitionUnit.WEEKS:
# return self._ensure_datetime(dt - relativedelta(days=dt.weekday()))
#
# return self._ensure_datetime(dt)
#
# @staticmethod
# def _ensure_datetime(dt: Union[date, datetime]) -> datetime:
# return datetime(year=dt.year, month=dt.month, day=dt.day)
#
# def __repr__(self) -> str:
# return "PostgresTimePartitionSize<%s, %s>" % (self.unit, self.value)
#
# class PostgresTimePartitionUnit(enum.Enum):
# YEARS = "years"
# MONTHS = "months"
# WEEKS = "weeks"
# DAYS = "days"
, which may contain function names, class names, or code. Output only the next line. | PostgresTimePartitionUnit.YEARS: "%Y", |
Using the snippet: <|code_start|> if dry:
return
if not yes:
print("Do you want to proceed? (y/N) ")
if not self._ask_for_confirmation():
print("Operation aborted.")
return
plan.apply(using=using)
print("Operations applied.")
@staticmethod
def _ask_for_confirmation() -> bool:
answer = input("").lower()
if not answer:
return False
if answer[0] == "y" or answer == "yes":
return True
return False
@staticmethod
def _partitioning_manager():
partitioning_manager = getattr(
settings, "PSQLEXTRA_PARTITIONING_MANAGER", None
)
if not partitioning_manager:
<|code_end|>
, determine the next line of code. You have imports:
from typing import Optional
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.module_loading import import_string
from psqlextra.partitioning import PostgresPartitioningError
and context (class names, function names, or code) available:
# Path: psqlextra/partitioning/error.py
# class PostgresPartitioningError(RuntimeError):
# """Raised when the partitioning configuration is broken or automatically
# creating/deleting partitions fails."""
. Output only the next line. | raise PostgresPartitioningError( |
Given the code snippet: <|code_start|>
class PostgresViewModelState(PostgresModelState):
"""Represents the state of a :see:PostgresViewModel in the migrations."""
def __init__(self, *args, view_options={}, **kwargs):
"""Initializes a new instance of :see:PostgresViewModelState.
Arguments:
view_options:
Dictionary of options for views.
See: PostgresViewModelMeta for a list.
"""
super().__init__(*args, **kwargs)
self.view_options = dict(view_options)
@classmethod
def _pre_new(
<|code_end|>
, generate the next line using the imports in this file:
from typing import Type
from psqlextra.models import PostgresViewModel
from .model import PostgresModelState
and context (functions, classes, or occasionally code) from other files:
# Path: psqlextra/models/view.py
# class PostgresViewModel(PostgresModel, metaclass=PostgresViewModelMeta):
# """Base class for creating a model that is a view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/backend/migrations/state/model.py
# class PostgresModelState(ModelState):
# """Base for custom model states.
#
# We need this base class to create some hooks into rendering models,
# creating new states and cloning state. Most of the logic resides
# here in the base class. Our derived classes implement the `_pre_*`
# methods.
# """
#
# @classmethod
# def from_model(
# cls, model: PostgresModel, *args, **kwargs
# ) -> "PostgresModelState":
# """Creates a new :see:PostgresModelState object from the specified
# model.
#
# We override this so derived classes get the chance to attach
# additional information to the newly created model state.
#
# We also need to patch up the base class for the model.
# """
#
# model_state = super().from_model(model, *args, **kwargs)
# model_state = cls._pre_new(model, model_state)
#
# # django does not add abstract bases as a base in migrations
# # because it assumes the base does not add anything important
# # in a migration.. but it does, so we replace the Model
# # base with the actual base
# bases = tuple()
# for base in model_state.bases:
# if issubclass(base, Model):
# bases += (cls._get_base_model_class(),)
# else:
# bases += (base,)
#
# model_state.bases = bases
# return model_state
#
# def clone(self) -> "PostgresModelState":
# """Gets an exact copy of this :see:PostgresModelState."""
#
# model_state = super().clone()
# return self._pre_clone(model_state)
#
# def render(self, apps):
# """Renders this state into an actual model."""
#
# # TODO: figure out a way to do this witout pretty much
# # copying the base class's implementation
#
# try:
# bases = tuple(
# (apps.get_model(base) if isinstance(base, str) else base)
# for base in self.bases
# )
# except LookupError:
# # TODO: this should be a InvalidBaseError
# raise ValueError(
# "Cannot resolve one or more bases from %r" % (self.bases,)
# )
#
# if isinstance(self.fields, Mapping):
# # In Django 3.1 `self.fields` became a `dict`
# fields = {
# name: field.clone() for name, field in self.fields.items()
# }
# else:
# # In Django < 3.1 `self.fields` is a list of (name, field) tuples
# fields = {name: field.clone() for name, field in self.fields}
#
# meta = type(
# "Meta",
# (),
# {"app_label": self.app_label, "apps": apps, **self.options},
# )
#
# attributes = {
# **fields,
# "Meta": meta,
# "__module__": "__fake__",
# **dict(self.construct_managers()),
# }
#
# return type(*self._pre_render(self.name, bases, attributes))
#
# @classmethod
# def _pre_new(
# cls, model: PostgresModel, model_state: "PostgresModelState"
# ) -> "PostgresModelState":
# """Called when a new model state is created from the specified
# model."""
#
# return model_state
#
# def _pre_clone(
# self, model_state: "PostgresModelState"
# ) -> "PostgresModelState":
# """Called when this model state is cloned."""
#
# return model_state
#
# def _pre_render(self, name: str, bases, attributes):
# """Called when this model state is rendered into a model."""
#
# return name, bases, attributes
#
# @classmethod
# def _get_base_model_class(self) -> Type[PostgresModel]:
# """Gets the class to use as a base class for rendered models."""
#
# return PostgresModel
. Output only the next line. | cls, model: PostgresViewModel, model_state: "PostgresViewModelState" |
Continue the code snippet: <|code_start|>
class PostgresPartitioningConfig:
"""Configuration for partitioning a specific model according to the
specified strategy."""
def __init__(
self,
<|code_end|>
. Use current file imports:
from psqlextra.models import PostgresPartitionedModel
from .strategy import PostgresPartitioningStrategy
and context (classes, functions, or code) from other files:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/partitioning/strategy.py
# class PostgresPartitioningStrategy:
# """Base class for implementing a partitioning strategy for a partitioned
# table."""
#
# @abstractmethod
# def to_create(
# self,
# ) -> Generator[PostgresPartition, None, None]:
# """Generates a list of partitions to be created."""
#
# @abstractmethod
# def to_delete(
# self,
# ) -> Generator[PostgresPartition, None, None]:
# """Generates a list of partitions to be deleted."""
. Output only the next line. | model: PostgresPartitionedModel, |
Continue the code snippet: <|code_start|>
class PostgresPartitioningConfig:
"""Configuration for partitioning a specific model according to the
specified strategy."""
def __init__(
self,
model: PostgresPartitionedModel,
<|code_end|>
. Use current file imports:
from psqlextra.models import PostgresPartitionedModel
from .strategy import PostgresPartitioningStrategy
and context (classes, functions, or code) from other files:
# Path: psqlextra/models/partitioned.py
# class PostgresPartitionedModel(
# PostgresModel, metaclass=PostgresPartitionedModelMeta
# ):
# """Base class for taking advantage of PostgreSQL's 11.x native support for
# table partitioning."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: psqlextra/partitioning/strategy.py
# class PostgresPartitioningStrategy:
# """Base class for implementing a partitioning strategy for a partitioned
# table."""
#
# @abstractmethod
# def to_create(
# self,
# ) -> Generator[PostgresPartition, None, None]:
# """Generates a list of partitions to be created."""
#
# @abstractmethod
# def to_delete(
# self,
# ) -> Generator[PostgresPartition, None, None]:
# """Generates a list of partitions to be deleted."""
. Output only the next line. | strategy: PostgresPartitioningStrategy, |
Based on the snippet: <|code_start|>
def test_on_conflict_update():
"""Tests whether simple upserts works correctly."""
model = get_fake_model(
{
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from django.db import models
from psqlextra.fields import HStoreField
from psqlextra.query import ConflictAction
from .fake_model import get_fake_model
and context (classes, functions, sometimes code) from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | "title": HStoreField(uniqueness=["key1"]), |
Based on the snippet: <|code_start|>
def test_on_conflict_update():
"""Tests whether simple upserts works correctly."""
model = get_fake_model(
{
"title": HStoreField(uniqueness=["key1"]),
"cookies": models.CharField(max_length=255, null=True),
}
)
obj1 = model.objects.on_conflict(
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from django.db import models
from psqlextra.fields import HStoreField
from psqlextra.query import ConflictAction
from .fake_model import get_fake_model
and context (classes, functions, sometimes code) from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
#
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | [("title", "key1")], ConflictAction.UPDATE |
Given the code snippet: <|code_start|> """Tests whether inserts works when the primary key is explicitly
specified."""
model = get_fake_model(
{
"name": models.CharField(max_length=255, primary_key=True),
"cookies": models.CharField(max_length=255, null=True),
}
)
pk = model.objects.all().insert(name="the-object", cookies="some-cookies")
assert pk == "the-object"
obj1 = model.objects.get()
assert obj1.pk == "the-object"
assert obj1.name == "the-object"
assert obj1.cookies == "some-cookies"
def test_insert_on_conflict():
"""Tests whether inserts works when a conflict is anticipated."""
model = get_fake_model(
{
"name": models.CharField(max_length=255, unique=True),
"cookies": models.CharField(max_length=255, null=True),
}
)
<|code_end|>
, generate the next line using the imports in this file:
from django.db import models
from psqlextra.query import ConflictAction
from .fake_model import get_fake_model
and context (functions, classes, or occasionally code) from other files:
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | pk = model.objects.on_conflict([("pk")], ConflictAction.NOTHING).insert( |
Given the following code snippet before the placeholder: <|code_start|>
random_value = str(uuid.uuid4())[:8]
model.objects.create(field=random_value)
def _traditional_insert(model, random_value):
"""Performs a concurrency safe insert the traditional way."""
try:
with transaction.atomic():
return model.objects.create(field=random_value)
except IntegrityError:
return model.objects.filter(field=random_value).first()
benchmark(_traditional_insert, model, random_value)
@pytest.mark.benchmark()
def test_insert_nothing_native(benchmark):
model = get_fake_model(
{"field": models.CharField(max_length=255, unique=True)}
)
random_value = str(uuid.uuid4())[:8]
model.objects.create(field=random_value)
def _native_insert(model, random_value):
"""Performs a concurrency safeinsert using the native PostgreSQL
conflict resolution."""
return model.objects.on_conflict(
<|code_end|>
, predict the next line using imports from the current file:
import uuid
import pytest
from django.db import models, transaction
from django.db.utils import IntegrityError
from psqlextra.query import ConflictAction
from ..fake_model import get_fake_model
and context including class names, function names, and sometimes code from other files:
# Path: psqlextra/query.py
# class PostgresQuerySet(models.QuerySet):
# def __init__(self, model=None, query=None, using=None, hints=None):
# def annotate(self, **annotations):
# def rename_annotations(self, **annotations):
# def on_conflict(
# self,
# fields: ConflictTarget,
# action: ConflictAction,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_insert(
# self,
# rows: List[dict],
# return_model: bool = False,
# using: Optional[str] = None,
# ):
# def insert(self, using: Optional[str] = None, **fields):
# def insert_and_get(self, using: Optional[str] = None, **fields):
# def upsert(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ) -> int:
# def upsert_and_get(
# self,
# conflict_target: ConflictTarget,
# fields: dict,
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def bulk_upsert(
# self,
# conflict_target: ConflictTarget,
# rows: Iterable[Dict],
# index_predicate: Optional[Union[Expression, Q, str]] = None,
# return_model: bool = False,
# using: Optional[str] = None,
# update_condition: Optional[Union[Expression, Q, str]] = None,
# ):
# def is_empty(r):
# def _create_model_instance(
# self, field_values: dict, using: str, apply_converters: bool = True
# ):
# def _build_insert_compiler(
# self, rows: Iterable[Dict], using: Optional[str] = None
# ):
# def _is_magical_field(self, model_instance, field, is_insert: bool):
# def _get_upsert_fields(self, kwargs):
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | ["field"], ConflictAction.NOTHING |
Next line prediction: <|code_start|>
def test_manager_context():
"""Tests whether the :see:postgres_manager context manager can be used to
get access to :see:PostgresManager on a model that does not use it directly
or inherits from :see:PostgresModel."""
model = get_fake_model(
{"myfield": models.CharField(max_length=255, unique=True)}, models.Model
)
<|code_end|>
. Use current file imports:
(from django.db import models
from psqlextra.util import postgres_manager
from .fake_model import get_fake_model)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/util.py
# @contextmanager
# def postgres_manager(model):
# """Allows you to use the :see:PostgresManager with the specified model
# instance on the fly.
#
# Arguments:
# model:
# The model or model instance to use this on.
# """
#
# manager = PostgresManager()
# manager.model = model
#
# yield manager
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
. Output only the next line. | with postgres_manager(model) as manager: |
Given snippet: <|code_start|>
def test_manager_context():
"""Tests whether the :see:postgres_manager context manager can be used to
get access to :see:PostgresManager on a model that does not use it directly
or inherits from :see:PostgresModel."""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.db import models
from psqlextra.util import postgres_manager
from .fake_model import get_fake_model
and context:
# Path: psqlextra/util.py
# @contextmanager
# def postgres_manager(model):
# """Allows you to use the :see:PostgresManager with the specified model
# instance on the fly.
#
# Arguments:
# model:
# The model or model instance to use this on.
# """
#
# manager = PostgresManager()
# manager.model = model
#
# yield manager
#
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
# """Defines a fake model and creates it in the database."""
#
# model = define_fake_model(fields, model_base, meta_options)
#
# with connection.schema_editor() as schema_editor:
# schema_editor.create_model(model)
#
# return model
which might include code, classes, or functions. Output only the next line. | model = get_fake_model( |
Given the code snippet: <|code_start|>
@pytest.mark.parametrize(
"model_base", [PostgresViewModel, PostgresMaterializedViewModel]
)
def test_view_model_meta_query_set(model_base):
"""Tests whether you can set a :see:QuerySet to be used as the underlying
query for a view."""
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from psqlextra.models import PostgresMaterializedViewModel, PostgresViewModel
from .fake_model import define_fake_model, define_fake_view_model
and context (functions, classes, or occasionally code) from other files:
# Path: psqlextra/models/view.py
# class PostgresMaterializedViewModel(
# PostgresViewModel, metaclass=PostgresViewModelMeta
# ):
# """Base class for creating a model that is a materialized view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# @classmethod
# def refresh(
# cls, concurrently: bool = False, using: Optional[str] = None
# ) -> None:
# """Refreshes this materialized view.
#
# Arguments:
# concurrently:
# Whether to tell PostgreSQL to refresh this
# materialized view concurrently.
#
# using:
# Optionally, the name of the database connection
# to use for refreshing the materialized view.
# """
#
# conn_name = using or "default"
#
# with connections[conn_name].schema_editor() as schema_editor:
# schema_editor.refresh_materialized_view_model(cls, concurrently)
#
# class PostgresViewModel(PostgresModel, metaclass=PostgresViewModelMeta):
# """Base class for creating a model that is a view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: tests/fake_model.py
# def define_fake_model(
# fields=None, model_base=PostgresModel, meta_options={}, **attributes
# ):
# """Defines a fake model (but does not create it in the database)."""
#
# name = str(uuid.uuid4()).replace("-", "")[:8].title()
#
# attributes = {
# "app_label": meta_options.get("app_label") or "tests",
# "__module__": __name__,
# "__name__": name,
# "Meta": type("Meta", (object,), meta_options),
# **attributes,
# }
#
# if fields:
# attributes.update(fields)
#
# model = type(name, (model_base,), attributes)
#
# apps.app_configs[attributes["app_label"]].models[name] = model
# return model
#
# def define_fake_view_model(
# fields=None, view_options={}, meta_options={}, model_base=PostgresViewModel
# ):
# """Defines a fake view model."""
#
# model = define_fake_model(
# fields=fields,
# model_base=model_base,
# meta_options=meta_options,
# ViewMeta=type("ViewMeta", (object,), view_options),
# )
#
# return model
. Output only the next line. | model = define_fake_model({"name": models.TextField()}) |
Using the snippet: <|code_start|>
@pytest.mark.parametrize(
"model_base", [PostgresViewModel, PostgresMaterializedViewModel]
)
def test_view_model_meta_query_set(model_base):
"""Tests whether you can set a :see:QuerySet to be used as the underlying
query for a view."""
model = define_fake_model({"name": models.TextField()})
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from psqlextra.models import PostgresMaterializedViewModel, PostgresViewModel
from .fake_model import define_fake_model, define_fake_view_model
and context (class names, function names, or code) available:
# Path: psqlextra/models/view.py
# class PostgresMaterializedViewModel(
# PostgresViewModel, metaclass=PostgresViewModelMeta
# ):
# """Base class for creating a model that is a materialized view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# @classmethod
# def refresh(
# cls, concurrently: bool = False, using: Optional[str] = None
# ) -> None:
# """Refreshes this materialized view.
#
# Arguments:
# concurrently:
# Whether to tell PostgreSQL to refresh this
# materialized view concurrently.
#
# using:
# Optionally, the name of the database connection
# to use for refreshing the materialized view.
# """
#
# conn_name = using or "default"
#
# with connections[conn_name].schema_editor() as schema_editor:
# schema_editor.refresh_materialized_view_model(cls, concurrently)
#
# class PostgresViewModel(PostgresModel, metaclass=PostgresViewModelMeta):
# """Base class for creating a model that is a view."""
#
# class Meta:
# abstract = True
# base_manager_name = "objects"
#
# Path: tests/fake_model.py
# def define_fake_model(
# fields=None, model_base=PostgresModel, meta_options={}, **attributes
# ):
# """Defines a fake model (but does not create it in the database)."""
#
# name = str(uuid.uuid4()).replace("-", "")[:8].title()
#
# attributes = {
# "app_label": meta_options.get("app_label") or "tests",
# "__module__": __name__,
# "__name__": name,
# "Meta": type("Meta", (object,), meta_options),
# **attributes,
# }
#
# if fields:
# attributes.update(fields)
#
# model = type(name, (model_base,), attributes)
#
# apps.app_configs[attributes["app_label"]].models[name] = model
# return model
#
# def define_fake_view_model(
# fields=None, view_options={}, meta_options={}, model_base=PostgresViewModel
# ):
# """Defines a fake view model."""
#
# model = define_fake_model(
# fields=fields,
# model_base=model_base,
# meta_options=meta_options,
# ViewMeta=type("ViewMeta", (object,), view_options),
# )
#
# return model
. Output only the next line. | view_model = define_fake_view_model( |
Next line prediction: <|code_start|>
class PostgresTimePartitionUnit(enum.Enum):
YEARS = "years"
MONTHS = "months"
WEEKS = "weeks"
DAYS = "days"
class PostgresTimePartitionSize:
"""Size of a time-based range partition table."""
unit: PostgresTimePartitionUnit
value: int
def __init__(
self,
years: Optional[int] = None,
months: Optional[int] = None,
weeks: Optional[int] = None,
days: Optional[int] = None,
) -> None:
sizes = [years, months, weeks, days]
if not any(sizes):
<|code_end|>
. Use current file imports:
(import enum
from datetime import date, datetime
from typing import Optional, Union
from dateutil.relativedelta import relativedelta
from .error import PostgresPartitioningError)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/partitioning/error.py
# class PostgresPartitioningError(RuntimeError):
# """Raised when the partitioning configuration is broken or automatically
# creating/deleting partitions fails."""
. Output only the next line. | raise PostgresPartitioningError("Partition cannot be 0 in size.") |
Here is a snippet: <|code_start|>
class PostgresCreateViewModel(CreateModel):
"""Creates the model as a native PostgreSQL 11.x view."""
serialization_expand_args = [
"fields",
"options",
"managers",
"view_options",
]
def __init__(
self,
name,
fields,
options=None,
view_options={},
bases=None,
managers=None,
):
super().__init__(name, fields, options, bases, managers)
self.view_options = view_options or {}
def state_forwards(self, app_label, state):
state.add_model(
<|code_end|>
. Write the next line using the current file imports:
from django.db.migrations.operations.models import CreateModel
from psqlextra.backend.migrations.state import PostgresViewModelState
and context from other files:
# Path: psqlextra/backend/migrations/state/view.py
# class PostgresViewModelState(PostgresModelState):
# """Represents the state of a :see:PostgresViewModel in the migrations."""
#
# def __init__(self, *args, view_options={}, **kwargs):
# """Initializes a new instance of :see:PostgresViewModelState.
#
# Arguments:
# view_options:
# Dictionary of options for views.
# See: PostgresViewModelMeta for a list.
# """
#
# super().__init__(*args, **kwargs)
#
# self.view_options = dict(view_options)
#
# @classmethod
# def _pre_new(
# cls, model: PostgresViewModel, model_state: "PostgresViewModelState"
# ) -> "PostgresViewModelState":
# """Called when a new model state is created from the specified
# model."""
#
# model_state.view_options = dict(model._view_meta.original_attrs)
# return model_state
#
# def _pre_clone(
# self, model_state: "PostgresViewModelState"
# ) -> "PostgresViewModelState":
# """Called when this model state is cloned."""
#
# model_state.view_options = dict(self.view_options)
# return model_state
#
# def _pre_render(self, name: str, bases, attributes):
# """Called when this model state is rendered into a model."""
#
# view_meta = type("ViewMeta", (), dict(self.view_options))
# return name, bases, {**attributes, "ViewMeta": view_meta}
#
# @classmethod
# def _get_base_model_class(self) -> Type[PostgresViewModel]:
# """Gets the class to use as a base class for rendered models."""
#
# return PostgresViewModel
, which may include functions, classes, or code. Output only the next line. | PostgresViewModelState( |
Here is a snippet: <|code_start|>
def test_unique_index_migrations():
index = UniqueIndex(fields=["name", "other_name"], name="index1")
ops = [
CreateModel(
name="mymodel",
fields=[
("name", models.TextField()),
("other_name", models.TextField()),
],
options={
# "indexes": [index],
},
),
AddIndex(model_name="mymodel", index=index),
]
with filtered_schema_editor("CREATE UNIQUE INDEX") as calls:
<|code_end|>
. Write the next line using the current file imports:
from django.db import models
from django.db.migrations import AddIndex, CreateModel
from psqlextra.indexes import UniqueIndex
from .migrations import apply_migration, filtered_schema_editor
and context from other files:
# Path: psqlextra/indexes/unique_index.py
# class UniqueIndex(Index):
# def create_sql(self, *args, **kwargs):
# if django.VERSION >= (2, 0):
# statement = super().create_sql(*args, **kwargs)
# statement.template = self._rewrite_sql(statement.template)
# return statement
#
# sql = super().create_sql(*args, **kwargs)
# return self._rewrite_sql(sql)
#
# @staticmethod
# def _rewrite_sql(sql: str) -> str:
# return sql.replace("CREATE INDEX", "CREATE UNIQUE INDEX")
#
# Path: tests/migrations.py
# def apply_migration(operations, state=None, backwards: bool = False):
# """Executes the specified migration operations using the specified schema
# editor.
#
# Arguments:
# operations:
# The migration operations to execute.
#
# state:
# The state state to use during the
# migrations.
#
# backwards:
# Whether to apply the operations
# in reverse (backwards).
# """
#
# state = state or migrations.state.ProjectState.from_apps(apps)
#
# class Migration(migrations.Migration):
# pass
#
# Migration.operations = operations
#
# migration = Migration("migration", "tests")
# executor = MigrationExecutor(connection)
#
# if not backwards:
# executor.apply_migration(state, migration)
# else:
# executor.unapply_migration(state, migration)
#
# return migration
#
# @contextmanager
# def filtered_schema_editor(*filters: List[str]):
# """Gets a schema editor, but filters executed SQL statements based on the
# specified text filters.
#
# Arguments:
# filters:
# List of strings to filter SQL
# statements on.
# """
#
# with connection.schema_editor() as schema_editor:
# wrapper_for = schema_editor.execute
# with mock.patch.object(
# PostgresSchemaEditor, "execute", wraps=wrapper_for
# ) as execute:
# filter_results = {}
# yield filter_results
#
# for filter_text in filters:
# filter_results[filter_text] = [
# call for call in execute.mock_calls if filter_text in str(call)
# ]
, which may include functions, classes, or code. Output only the next line. | apply_migration(ops) |
Here is a snippet: <|code_start|>
def test_unique_index_migrations():
index = UniqueIndex(fields=["name", "other_name"], name="index1")
ops = [
CreateModel(
name="mymodel",
fields=[
("name", models.TextField()),
("other_name", models.TextField()),
],
options={
# "indexes": [index],
},
),
AddIndex(model_name="mymodel", index=index),
]
<|code_end|>
. Write the next line using the current file imports:
from django.db import models
from django.db.migrations import AddIndex, CreateModel
from psqlextra.indexes import UniqueIndex
from .migrations import apply_migration, filtered_schema_editor
and context from other files:
# Path: psqlextra/indexes/unique_index.py
# class UniqueIndex(Index):
# def create_sql(self, *args, **kwargs):
# if django.VERSION >= (2, 0):
# statement = super().create_sql(*args, **kwargs)
# statement.template = self._rewrite_sql(statement.template)
# return statement
#
# sql = super().create_sql(*args, **kwargs)
# return self._rewrite_sql(sql)
#
# @staticmethod
# def _rewrite_sql(sql: str) -> str:
# return sql.replace("CREATE INDEX", "CREATE UNIQUE INDEX")
#
# Path: tests/migrations.py
# def apply_migration(operations, state=None, backwards: bool = False):
# """Executes the specified migration operations using the specified schema
# editor.
#
# Arguments:
# operations:
# The migration operations to execute.
#
# state:
# The state state to use during the
# migrations.
#
# backwards:
# Whether to apply the operations
# in reverse (backwards).
# """
#
# state = state or migrations.state.ProjectState.from_apps(apps)
#
# class Migration(migrations.Migration):
# pass
#
# Migration.operations = operations
#
# migration = Migration("migration", "tests")
# executor = MigrationExecutor(connection)
#
# if not backwards:
# executor.apply_migration(state, migration)
# else:
# executor.unapply_migration(state, migration)
#
# return migration
#
# @contextmanager
# def filtered_schema_editor(*filters: List[str]):
# """Gets a schema editor, but filters executed SQL statements based on the
# specified text filters.
#
# Arguments:
# filters:
# List of strings to filter SQL
# statements on.
# """
#
# with connection.schema_editor() as schema_editor:
# wrapper_for = schema_editor.execute
# with mock.patch.object(
# PostgresSchemaEditor, "execute", wraps=wrapper_for
# ) as execute:
# filter_results = {}
# yield filter_results
#
# for filter_text in filters:
# filter_results[filter_text] = [
# call for call in execute.mock_calls if filter_text in str(call)
# ]
, which may include functions, classes, or code. Output only the next line. | with filtered_schema_editor("CREATE UNIQUE INDEX") as calls: |
Predict the next line after this snippet: <|code_start|>
def _assert_autodetector(changes, expected):
"""Asserts whether the results of the auto detector are as expected."""
assert "tests" in changes
assert len("tests") > 0
operations = changes["tests"][0].operations
for i, expected_operation in enumerate(expected):
real_operation = operations[i]
_, _, real_args, real_kwargs = real_operation.field.deconstruct()
(
_,
_,
expected_args,
expected_kwargs,
) = expected_operation.field.deconstruct()
assert real_args == expected_args
assert real_kwargs == expected_kwargs
def test_hstore_autodetect_uniqueness():
"""Tests whether changes in the `uniqueness` option are properly detected
by the auto detector."""
before = [
migrations.state.ModelState(
<|code_end|>
using the current file's imports:
from django.db import migrations
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.state import ProjectState
from psqlextra.fields import HStoreField
and any relevant context from other files:
# Path: psqlextra/fields/hstore_field.py
# class HStoreField(DjangoHStoreField):
# """Improved version of Django's :see:HStoreField that adds support for
# database-level constraints.
#
# Notes:
# - For the implementation of uniqueness, see the
# custom database back-end.
# """
#
# def __init__(
# self,
# *args,
# uniqueness: Optional[List[Union[str, Tuple[str, ...]]]] = None,
# required: Optional[List[str]] = None,
# **kwargs
# ):
# """Initializes a new instance of :see:HStoreField.
#
# Arguments:
# uniqueness:
# List of keys to enforce as unique. Use tuples
# to enforce multiple keys together to be unique.
#
# required:
# List of keys that should be enforced as required.
# """
#
# super(HStoreField, self).__init__(*args, **kwargs)
#
# self.uniqueness = uniqueness
# self.required = required
#
# def get_prep_value(self, value):
# """Override the base class so it doesn't cast all values to strings.
#
# psqlextra supports expressions in hstore fields, so casting all
# values to strings is a bad idea.
# """
#
# value = Field.get_prep_value(self, value)
#
# if isinstance(value, dict):
# prep_value = {}
# for key, val in value.items():
# if isinstance(val, Expression):
# prep_value[key] = val
# elif val is not None:
# prep_value[key] = str(val)
# else:
# prep_value[key] = val
#
# value = prep_value
#
# if isinstance(value, list):
# value = [str(item) for item in value]
#
# return value
#
# def deconstruct(self):
# """Gets the values to pass to :see:__init__ when re-creating this
# object."""
#
# name, path, args, kwargs = super(HStoreField, self).deconstruct()
#
# if self.uniqueness is not None:
# kwargs["uniqueness"] = self.uniqueness
#
# if self.required is not None:
# kwargs["required"] = self.required
#
# return name, path, args, kwargs
. Output only the next line. | "tests", "Model1", [("title", HStoreField())] |
Predict the next line after this snippet: <|code_start|>
class PostgresPartitionedModelOptions:
"""Container for :see:PostgresPartitionedModel options.
This is where attributes copied from the model's `PartitioningMeta`
are held.
"""
<|code_end|>
using the current file's imports:
from typing import Dict, List, Optional, Union
from psqlextra.types import PostgresPartitioningMethod, SQLWithParams
and any relevant context from other files:
# Path: psqlextra/types.py
# SQL = str
# NOTHING = "NOTHING"
# UPDATE = "UPDATE"
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
# class StrEnum(str, Enum):
# class ConflictAction(Enum):
# class PostgresPartitioningMethod(StrEnum):
# def all(cls) -> List["StrEnum"]:
# def values(cls) -> List[str]:
# def __str__(self) -> str:
# def all(cls) -> List["ConflictAction"]:
. Output only the next line. | def __init__(self, method: PostgresPartitioningMethod, key: List[str]): |
Next line prediction: <|code_start|>
class PostgresPartitionedModelOptions:
"""Container for :see:PostgresPartitionedModel options.
This is where attributes copied from the model's `PartitioningMeta`
are held.
"""
def __init__(self, method: PostgresPartitioningMethod, key: List[str]):
self.method = method
self.key = key
self.original_attrs: Dict[
str, Union[PostgresPartitioningMethod, List[str]]
] = dict(method=method, key=key)
class PostgresViewOptions:
"""Container for :see:PostgresView and :see:PostgresMaterializedView
options.
This is where attributes copied from the model's `ViewMeta` are
held.
"""
<|code_end|>
. Use current file imports:
(from typing import Dict, List, Optional, Union
from psqlextra.types import PostgresPartitioningMethod, SQLWithParams)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/types.py
# SQL = str
# NOTHING = "NOTHING"
# UPDATE = "UPDATE"
# RANGE = "range"
# LIST = "list"
# HASH = "hash"
# class StrEnum(str, Enum):
# class ConflictAction(Enum):
# class PostgresPartitioningMethod(StrEnum):
# def all(cls) -> List["StrEnum"]:
# def values(cls) -> List[str]:
# def __str__(self) -> str:
# def all(cls) -> List["ConflictAction"]:
. Output only the next line. | def __init__(self, query: Optional[SQLWithParams]): |
Continue the code snippet: <|code_start|>
@contextmanager
def postgres_patched_migrations():
"""Patches migration related classes/functions to extend how Django
generates and applies migrations.
This adds support for automatically detecting changes in Postgres
specific models.
"""
with patched_project_state():
<|code_end|>
. Use current file imports:
from contextlib import contextmanager
from .patched_autodetector import patched_autodetector
from .patched_project_state import patched_project_state
and context (classes, functions, or code) from other files:
# Path: psqlextra/backend/migrations/patched_autodetector.py
# @contextmanager
# def patched_autodetector():
# """Patches the standard Django :seee:MigrationAutodetector for the duration
# of the context.
#
# The patch intercepts the `add_operation` function to
# customize how new operations are added.
#
# We have to do this because there is no way in Django
# to extend the auto detector otherwise.
# """
#
# autodetector_module_path = "django.db.migrations.autodetector"
# autodetector_class_path = (
# f"{autodetector_module_path}.MigrationAutodetector"
# )
# add_operation_path = f"{autodetector_class_path}.add_operation"
#
# def _patched(autodetector, app_label, operation, *args, **kwargs):
# handler = AddOperationHandler(autodetector, app_label, args, kwargs)
#
# if isinstance(operation, CreateModel):
# return handler.add_create_model(operation)
#
# if isinstance(operation, DeleteModel):
# return handler.add_delete_model(operation)
#
# if isinstance(operation, AddField):
# return handler.add_field(operation)
#
# if isinstance(operation, RemoveField):
# return handler.remove_field(operation)
#
# if isinstance(operation, AlterField):
# return handler.alter_field(operation)
#
# if isinstance(operation, RenameField):
# return handler.rename_field(operation)
#
# return handler.add(operation)
#
# with mock.patch(add_operation_path, new=_patched):
# yield
#
# Path: psqlextra/backend/migrations/patched_project_state.py
# @contextmanager
# def patched_project_state():
# """Patches the standard Django :see:ProjectState.from_apps for the duration
# of the context.
#
# The patch intercepts the `from_apps` function to control
# how model state is creatd. We want to use our custom
# model state classes for certain types of models.
#
# We have to do this because there is no way in Django
# to extend the project state otherwise.
# """
#
# from_apps_module_path = "django.db.migrations.state"
# from_apps_class_path = f"{from_apps_module_path}.ProjectState"
# from_apps_path = f"{from_apps_class_path}.from_apps"
#
# with mock.patch(from_apps_path, new=project_state_from_apps):
# yield
. Output only the next line. | with patched_autodetector(): |
Next line prediction: <|code_start|>
@contextmanager
def postgres_patched_migrations():
"""Patches migration related classes/functions to extend how Django
generates and applies migrations.
This adds support for automatically detecting changes in Postgres
specific models.
"""
<|code_end|>
. Use current file imports:
(from contextlib import contextmanager
from .patched_autodetector import patched_autodetector
from .patched_project_state import patched_project_state)
and context including class names, function names, or small code snippets from other files:
# Path: psqlextra/backend/migrations/patched_autodetector.py
# @contextmanager
# def patched_autodetector():
# """Patches the standard Django :seee:MigrationAutodetector for the duration
# of the context.
#
# The patch intercepts the `add_operation` function to
# customize how new operations are added.
#
# We have to do this because there is no way in Django
# to extend the auto detector otherwise.
# """
#
# autodetector_module_path = "django.db.migrations.autodetector"
# autodetector_class_path = (
# f"{autodetector_module_path}.MigrationAutodetector"
# )
# add_operation_path = f"{autodetector_class_path}.add_operation"
#
# def _patched(autodetector, app_label, operation, *args, **kwargs):
# handler = AddOperationHandler(autodetector, app_label, args, kwargs)
#
# if isinstance(operation, CreateModel):
# return handler.add_create_model(operation)
#
# if isinstance(operation, DeleteModel):
# return handler.add_delete_model(operation)
#
# if isinstance(operation, AddField):
# return handler.add_field(operation)
#
# if isinstance(operation, RemoveField):
# return handler.remove_field(operation)
#
# if isinstance(operation, AlterField):
# return handler.alter_field(operation)
#
# if isinstance(operation, RenameField):
# return handler.rename_field(operation)
#
# return handler.add(operation)
#
# with mock.patch(add_operation_path, new=_patched):
# yield
#
# Path: psqlextra/backend/migrations/patched_project_state.py
# @contextmanager
# def patched_project_state():
# """Patches the standard Django :see:ProjectState.from_apps for the duration
# of the context.
#
# The patch intercepts the `from_apps` function to control
# how model state is creatd. We want to use our custom
# model state classes for certain types of models.
#
# We have to do this because there is no way in Django
# to extend the project state otherwise.
# """
#
# from_apps_module_path = "django.db.migrations.state"
# from_apps_class_path = f"{from_apps_module_path}.ProjectState"
# from_apps_path = f"{from_apps_class_path}.from_apps"
#
# with mock.patch(from_apps_path, new=project_state_from_apps):
# yield
. Output only the next line. | with patched_project_state(): |
Given the following code snippet before the placeholder: <|code_start|>
@dataclass
class PostgresModelPartitioningPlan:
"""Describes the partitions that are going to be created/deleted for a
particular partitioning config.
A "partitioning config" applies to one model.
"""
<|code_end|>
, predict the next line using imports from the current file:
from dataclasses import dataclass, field
from typing import List, Optional
from django.db import connections, transaction
from .config import PostgresPartitioningConfig
from .constants import AUTO_PARTITIONED_COMMENT
from .partition import PostgresPartition
and context including class names, function names, and sometimes code from other files:
# Path: psqlextra/partitioning/config.py
# class PostgresPartitioningConfig:
# """Configuration for partitioning a specific model according to the
# specified strategy."""
#
# def __init__(
# self,
# model: PostgresPartitionedModel,
# strategy: PostgresPartitioningStrategy,
# ) -> None:
# self.model = model
# self.strategy = strategy
#
# Path: psqlextra/partitioning/constants.py
# AUTO_PARTITIONED_COMMENT = "psqlextra_auto_partitioned"
#
# Path: psqlextra/partitioning/partition.py
# class PostgresPartition:
# """Base class for a PostgreSQL table partition."""
#
# @abstractmethod
# def name(self) -> str:
# """Generates/computes the name for this partition."""
#
# @abstractmethod
# def create(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# comment: Optional[str] = None,
# ) -> None:
# """Creates this partition in the database."""
#
# @abstractmethod
# def delete(
# self,
# model: PostgresPartitionedModel,
# schema_editor: PostgresSchemaEditor,
# ) -> None:
# """Deletes this partition from the database."""
#
# def deconstruct(self) -> dict:
# """Deconstructs this partition into a dict of attributes/fields."""
#
# return {"name": self.name()}
. Output only the next line. | config: PostgresPartitioningConfig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.