index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
15,927 | netapp_ontap.host_connection | HostConnection | The HostConnection allows the client application to store their credentials
and reuse them for each operation. There are three ways to use a connection
object:
* The first is to use the connection object as a context manager. Any operations
on a resource that are called within the scope of the block will use that
connection.
* The second is to call set_connection() on a resource object. This
will then be the connection used for all actions for that object only.
* The third way is to call netapp_ontap.config.CONNECTION = connection. This
connection instance will now be used for all actions on all resource
objects (that do not otherwise set their own connection). This reduces
the need to pass the connection around the application.
Connections will be searched for in this order when executing an action.
| class HostConnection: # pylint: disable=too-many-instance-attributes
"""The HostConnection allows the client application to store their credentials
and reuse them for each operation. There are three ways to use a connection
object:
* The first is to use the connection object as a context manager. Any operations
on a resource that are called within the scope of the block will use that
connection.
* The second is to call set_connection() on a resource object. This
will then be the connection used for all actions for that object only.
* The third way is to call netapp_ontap.config.CONNECTION = connection. This
connection instance will now be used for all actions on all resource
objects (that do not otherwise set their own connection). This reduces
the need to pass the connection around the application.
Connections will be searched for in this order when executing an action.
"""
# pylint: disable=bad-continuation,too-many-arguments
def __init__(
self,
host,
username: str = None,
password: str = None,
cert: str = None,
key: str = None,
verify: bool = True,
poll_timeout: int = 30,
poll_interval: int = 5,
headers: dict = None,
port: int = 443,
):
"""Store information needed to contact the API host
Either username and password must be provided or certificate and key must
be provided or the 'Authorization' must be provided in the headers.
If verify is set to False, urllib3's InsecureRequestWarnings will also be
silenced in the logs.
Args:
host: The API host that the library should talk to
username: The user identifier known to the host
password: The secret for the user
cert: The file path to the users public certificate. The common
name in the certificate must match the account name.
key: A private key in PEM format
verify: If an SSL connection is made to the host, this parameter
controls how the validity of the trust chain of the certificate
is handled. See the documentation for the requests library for more information:
https://2.python-requests.org/en/master/user/advanced/#ssl-cert-verification
poll_timeout: Time in seconds to poll on a job. This setting applies to all polling
that uses this connection unless overridden as a parameter to poll(). Defaults
to 30 seconds.
poll_interval: Time in seconds to wait between polls on a job. This setting applies
to all polling that uses this connection unless overridden as a parameter to
poll(). Defaults to 5 seconds.
headers: Any custom headers to be passed to each request using this connection object.
port: The port that the library should talk to
"""
authentication_methods = 0
if username and password is not None:
authentication_methods += 1
if cert and key:
authentication_methods += 1
elif headers and 'Authorization' in headers:
authentication_methods += 1
if authentication_methods != 1:
from netapp_ontap.error import NetAppRestError # pylint: disable=cyclic-import
raise NetAppRestError(
"There must be only one authentication method provided. The following four"
" methods are the only types of authentication methods currently accepted."
" 1. Username and password. 2. Cert and key. 3. An 'Authorization' header."
" 4. An 'Authorization' header and a cert and key"
)
self.scheme = "https"
self.host = host
self.port = port
self.username = username
self.password = password
self.cert = cert
self.key = key
self.verify = verify
self.poll_timeout = poll_timeout
self.poll_interval = poll_interval
self.headers = headers
self.protocol_timeouts = None
self._old_context = None # type: Optional[HostConnection]
self._request_session = None # type: Optional[requests.Session]
if not self.verify:
import urllib3 # type: ignore
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
@staticmethod
def get_host_context() -> "Optional[HostConnection]":
"""Get the current host context, if any.
Returns:
A HostConnection object or None if not in a host connection context.
"""
return _HOST_CONTEXT
@property
def basic_auth(self) -> Optional[Tuple[str, str]]:
"""Pulls the credentials out of the connection object.
Returns:
A tuple of username and password sufficient for passing to the requests library. Returns None if this connection is not configured for basic auth with a username and password.
"""
if self.username and self.password is not None:
return (self.username, self.password)
return None
@property
def cert_auth(self) -> Optional[Tuple[str, str]]:
"""Pulls the certificate details out of the connection object.
Returns:
A tuple of cert and key sufficient for passing to the requests library. Returns None if this connection is not configured for cert auth with a cert and key.
"""
if self.cert and self.key:
return (self.cert, self.key)
return None
@property
def bearer_auth(self) -> Optional[Tuple[str, str]]:
"""Pulls the header name and token out of the connection object.
Returns:
A tuple of the header name and token for passing to the requests library. Returns None if this connection is not configured for oauth2 yet
"""
if not self.headers or self.headers.get('Authorization', '').split()[0] != 'Bearer':
return None
# Right now NetApp only supports 3 IDP (keycloak, auth0, adfs) which all use the JWT format
# The following code checks to make sure that the token generally follows the JWT format before returning the tuple
# The steps are taken from https://www.rfc-editor.org/rfc/rfc7519#section-7.2
token = self.headers['Authorization'].split()[1]
#1 Verify that the JWT contains at least one period ('.') character.
if '.' not in token:
return None
#2 Let the Encoded JOSE Header be the portion of the JWT before the first period ('.') character.
header = token.split(".")[0]
message = token.split(".")[1]
#3~9 Base64url decode the Encoded JOSE Header and Message following the restriction that no line breaks, whitespace, or other additional characters have been used.
if ' ' in header or '\n' in header or ' ' in message or '\n' in message:
return None
try:
for b64 in (header, message):
b64 += "=" * ((4 - len(b64) % 4) % 4) #add padding as required to properly encode and decode with base64
if base64.b64encode(base64.b64decode(b64)) != bytes(b64, "utf-8"):
return None
except (ValueError, TypeError, binascii.Error):
return None
# Success! The our tuple is most likely a valid JWT
return (self.headers['Authorization'].split()[0], self.headers['Authorization'].split()[1])
@property
def origin(self) -> str:
"""The beginning of any REST endpoint.
Returns:
The origin part of the URL. For example, `http://1.2.3.4:8080`.
"""
return f"{self.scheme}://{self.host}:{self.port}"
@property
def request_headers(self) -> Optional[dict]:
"""Retrieves the headers set out of the connection object
Returns:
A dictionary consisting of header names and values for passing to the requests library. Returns None if no headers are configured.
"""
if self.headers:
return self.headers
return None
@request_headers.setter
def request_headers(self, headers):
"""Set the request headers for the connection object"""
if isinstance(headers, dict):
self.headers = headers
else:
raise TypeError("Request headers must be specified as a 'dict' type")
@contextmanager
def with_headers(self, headers: dict) -> Generator["HostConnection", None, None]:
""" Manually set the headers field of the connection object """
old_headers = copy.deepcopy(self.request_headers)
self.headers = headers
yield self
self.headers = old_headers
self._request_session = None
def __enter__(self):
global _HOST_CONTEXT # pylint: disable=global-statement
self._old_context = _HOST_CONTEXT
_HOST_CONTEXT = self
return self
def __exit__(self, exception_type, exception_value, traceback):
global _HOST_CONTEXT # pylint: disable=global-statement
_HOST_CONTEXT = self._old_context
@property
def session(self) -> requests.Session:
"""A `requests.Session` object which is used for all API calls.
This session is reused for each API call made with this connection. Multiple
requests may therefore be sent through the same TCP connection assuming
the host supports keep-alive.
Returns:
A `requests.Session` object which is used for all API calls.
"""
current_session = getattr(self, "_request_session", None)
if not current_session:
current_session = WrappedSession()
if self.origin not in current_session.adapters:
from netapp_ontap import config
if config.RETRY_API_ON_ERROR:
retry_strategy = LoggingRetry(
total=config.RETRY_API_ATTEMPTS,
status_forcelist=config.RETRY_API_ERROR_CODES,
allowed_methods=config.RETRY_API_HTTP_METHODS,
backoff_factor=config.RETRY_API_BACKOFF_FACTOR,
)
else:
retry_strategy = LoggingRetry.from_int(5)
current_session.mount(
self.origin,
LoggingAdapter(self, max_retries=retry_strategy, timeout=self.protocol_timeouts)
)
if self.basic_auth:
current_session.auth = self.basic_auth
else:
current_session.cert = self.cert_auth
if self.request_headers:
current_session.headers.update(self.request_headers)
current_session.verify = self.verify
import netapp_ontap # pylint: disable=cyclic-import
current_session.headers.update(
{"X-Dot-Client-App": f"netapp-ontap-python-{netapp_ontap.__version__}"}
)
self._request_session = current_session
return current_session
| (host, username: str = None, password: str = None, cert: str = None, key: str = None, verify: bool = True, poll_timeout: int = 30, poll_interval: int = 5, headers: dict = None, port: int = 443) |
15,928 | netapp_ontap.host_connection | __enter__ | null | def __enter__(self):
global _HOST_CONTEXT # pylint: disable=global-statement
self._old_context = _HOST_CONTEXT
_HOST_CONTEXT = self
return self
| (self) |
15,929 | netapp_ontap.host_connection | __exit__ | null | def __exit__(self, exception_type, exception_value, traceback):
global _HOST_CONTEXT # pylint: disable=global-statement
_HOST_CONTEXT = self._old_context
| (self, exception_type, exception_value, traceback) |
15,930 | netapp_ontap.host_connection | __init__ | Store information needed to contact the API host
Either username and password must be provided or certificate and key must
be provided or the 'Authorization' must be provided in the headers.
If verify is set to False, urllib3's InsecureRequestWarnings will also be
silenced in the logs.
Args:
host: The API host that the library should talk to
username: The user identifier known to the host
password: The secret for the user
cert: The file path to the users public certificate. The common
name in the certificate must match the account name.
key: A private key in PEM format
verify: If an SSL connection is made to the host, this parameter
controls how the validity of the trust chain of the certificate
is handled. See the documentation for the requests library for more information:
https://2.python-requests.org/en/master/user/advanced/#ssl-cert-verification
poll_timeout: Time in seconds to poll on a job. This setting applies to all polling
that uses this connection unless overridden as a parameter to poll(). Defaults
to 30 seconds.
poll_interval: Time in seconds to wait between polls on a job. This setting applies
to all polling that uses this connection unless overridden as a parameter to
poll(). Defaults to 5 seconds.
headers: Any custom headers to be passed to each request using this connection object.
port: The port that the library should talk to
| def __init__(
self,
host,
username: str = None,
password: str = None,
cert: str = None,
key: str = None,
verify: bool = True,
poll_timeout: int = 30,
poll_interval: int = 5,
headers: dict = None,
port: int = 443,
):
"""Store information needed to contact the API host
Either username and password must be provided or certificate and key must
be provided or the 'Authorization' must be provided in the headers.
If verify is set to False, urllib3's InsecureRequestWarnings will also be
silenced in the logs.
Args:
host: The API host that the library should talk to
username: The user identifier known to the host
password: The secret for the user
cert: The file path to the users public certificate. The common
name in the certificate must match the account name.
key: A private key in PEM format
verify: If an SSL connection is made to the host, this parameter
controls how the validity of the trust chain of the certificate
is handled. See the documentation for the requests library for more information:
https://2.python-requests.org/en/master/user/advanced/#ssl-cert-verification
poll_timeout: Time in seconds to poll on a job. This setting applies to all polling
that uses this connection unless overridden as a parameter to poll(). Defaults
to 30 seconds.
poll_interval: Time in seconds to wait between polls on a job. This setting applies
to all polling that uses this connection unless overridden as a parameter to
poll(). Defaults to 5 seconds.
headers: Any custom headers to be passed to each request using this connection object.
port: The port that the library should talk to
"""
authentication_methods = 0
if username and password is not None:
authentication_methods += 1
if cert and key:
authentication_methods += 1
elif headers and 'Authorization' in headers:
authentication_methods += 1
if authentication_methods != 1:
from netapp_ontap.error import NetAppRestError # pylint: disable=cyclic-import
raise NetAppRestError(
"There must be only one authentication method provided. The following four"
" methods are the only types of authentication methods currently accepted."
" 1. Username and password. 2. Cert and key. 3. An 'Authorization' header."
" 4. An 'Authorization' header and a cert and key"
)
self.scheme = "https"
self.host = host
self.port = port
self.username = username
self.password = password
self.cert = cert
self.key = key
self.verify = verify
self.poll_timeout = poll_timeout
self.poll_interval = poll_interval
self.headers = headers
self.protocol_timeouts = None
self._old_context = None # type: Optional[HostConnection]
self._request_session = None # type: Optional[requests.Session]
if not self.verify:
import urllib3 # type: ignore
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
| (self, host, username: Optional[str] = None, password: Optional[str] = None, cert: Optional[str] = None, key: Optional[str] = None, verify: bool = True, poll_timeout: int = 30, poll_interval: int = 5, headers: Optional[dict] = None, port: int = 443) |
15,931 | netapp_ontap.host_connection | get_host_context | Get the current host context, if any.
Returns:
A HostConnection object or None if not in a host connection context.
| @staticmethod
def get_host_context() -> "Optional[HostConnection]":
"""Get the current host context, if any.
Returns:
A HostConnection object or None if not in a host connection context.
"""
return _HOST_CONTEXT
| () -> Optional[netapp_ontap.host_connection.HostConnection] |
15,932 | netapp_ontap.host_connection | with_headers | Manually set the headers field of the connection object | @property
def session(self) -> requests.Session:
"""A `requests.Session` object which is used for all API calls.
This session is reused for each API call made with this connection. Multiple
requests may therefore be sent through the same TCP connection assuming
the host supports keep-alive.
Returns:
A `requests.Session` object which is used for all API calls.
"""
current_session = getattr(self, "_request_session", None)
if not current_session:
current_session = WrappedSession()
if self.origin not in current_session.adapters:
from netapp_ontap import config
if config.RETRY_API_ON_ERROR:
retry_strategy = LoggingRetry(
total=config.RETRY_API_ATTEMPTS,
status_forcelist=config.RETRY_API_ERROR_CODES,
allowed_methods=config.RETRY_API_HTTP_METHODS,
backoff_factor=config.RETRY_API_BACKOFF_FACTOR,
)
else:
retry_strategy = LoggingRetry.from_int(5)
current_session.mount(
self.origin,
LoggingAdapter(self, max_retries=retry_strategy, timeout=self.protocol_timeouts)
)
if self.basic_auth:
current_session.auth = self.basic_auth
else:
current_session.cert = self.cert_auth
if self.request_headers:
current_session.headers.update(self.request_headers)
current_session.verify = self.verify
import netapp_ontap # pylint: disable=cyclic-import
current_session.headers.update(
{"X-Dot-Client-App": f"netapp-ontap-python-{netapp_ontap.__version__}"}
)
self._request_session = current_session
return current_session
| (self, headers: dict) -> Generator[netapp_ontap.host_connection.HostConnection, NoneType, NoneType] |
15,933 | netapp_ontap.response | NetAppResponse | Contains the HTTP response received by a client from a server
for a specific action. The object allows all responses to be examined
in a consistent way. For example, is this an error or is an ongoing job?
| class NetAppResponse:
"""Contains the HTTP response received by a client from a server
for a specific action. The object allows all responses to be examined
in a consistent way. For example, is this an error or is an ongoing job?
"""
def __init__(self, http_response: requests.Response, connection: HostConnection = None) -> None:
"""Create and initialize a NetAppResponse object based on the result of an API call.
Args:
http_response: The API response to wrap
"""
self.http_response = http_response
self.connection = connection
@property
def is_job(self) -> bool:
"""Examine to determine if the response is a job.
Returns:
True if the HTTP status code returned was 202, else it will return False.
"""
try:
job_link = self.http_response.json()["job"]["_links"]["self"]["href"]
return job_link is not None
except: # pylint: disable=bare-except
return False
@property
def is_err(self) -> bool:
"""Examine to determine if the response is an error.
Returns:
True if the HTTP status code was 400 or greater, else it will return False.
"""
return self.http_response.status_code > 399
def poll(
self, connection: HostConnection = None, timeout: int = None, interval: int = None
) -> "NetAppResponse":
"""Wait for the job associated with the response to complete.
Calls 'utils.poll' with the response object and blocks until the job
completes (that is reaches a terminal state).
Args:
connection: The host containing the job to connect to.
timeout: Seconds to wait before timing out of a poll request. If set,
the value overrides the timeout set in connection. Otherwise, the
timeout set in the connection is used.
interval: Seconds to wait between making REST API calls to check the
the job status. If set, the value overrides the interval set in the
connection object. Otherwise, the interval set in connection object
is used.
Returns:
The response received after the job completes. This is normally a success or failure indication for the job.
"""
from netapp_ontap import utils # pylint: disable=cyclic-import
my_connection = connection if connection is not None else self.connection
return utils.poll(
self.http_response,
connection=my_connection,
timeout=timeout,
interval=interval
)
| (http_response: requests.models.Response, connection: netapp_ontap.host_connection.HostConnection = None) -> None |
15,934 | netapp_ontap.response | __init__ | Create and initialize a NetAppResponse object based on the result of an API call.
Args:
http_response: The API response to wrap
| def __init__(self, http_response: requests.Response, connection: HostConnection = None) -> None:
"""Create and initialize a NetAppResponse object based on the result of an API call.
Args:
http_response: The API response to wrap
"""
self.http_response = http_response
self.connection = connection
| (self, http_response: requests.models.Response, connection: Optional[netapp_ontap.host_connection.HostConnection] = None) -> NoneType |
15,935 | netapp_ontap.response | poll | Wait for the job associated with the response to complete.
Calls 'utils.poll' with the response object and blocks until the job
completes (that is reaches a terminal state).
Args:
connection: The host containing the job to connect to.
timeout: Seconds to wait before timing out of a poll request. If set,
the value overrides the timeout set in connection. Otherwise, the
timeout set in the connection is used.
interval: Seconds to wait between making REST API calls to check the
the job status. If set, the value overrides the interval set in the
connection object. Otherwise, the interval set in connection object
is used.
Returns:
The response received after the job completes. This is normally a success or failure indication for the job.
| def poll(
self, connection: HostConnection = None, timeout: int = None, interval: int = None
) -> "NetAppResponse":
"""Wait for the job associated with the response to complete.
Calls 'utils.poll' with the response object and blocks until the job
completes (that is reaches a terminal state).
Args:
connection: The host containing the job to connect to.
timeout: Seconds to wait before timing out of a poll request. If set,
the value overrides the timeout set in connection. Otherwise, the
timeout set in the connection is used.
interval: Seconds to wait between making REST API calls to check the
the job status. If set, the value overrides the interval set in the
connection object. Otherwise, the interval set in connection object
is used.
Returns:
The response received after the job completes. This is normally a success or failure indication for the job.
"""
from netapp_ontap import utils # pylint: disable=cyclic-import
my_connection = connection if connection is not None else self.connection
return utils.poll(
self.http_response,
connection=my_connection,
timeout=timeout,
interval=interval
)
| (self, connection: Optional[netapp_ontap.host_connection.HostConnection] = None, timeout: Optional[int] = None, interval: Optional[int] = None) -> netapp_ontap.response.NetAppResponse |
15,936 | netapp_ontap.error | NetAppRestError | Common base class for all exceptions raised by the library functions. All
custom exceptions are derived from this type.
| class NetAppRestError(Exception):
"""Common base class for all exceptions raised by the library functions. All
custom exceptions are derived from this type.
"""
def __init__(self, message: str = None, cause: Exception = None) -> None:
"""Initalize the error object.
Optionally accepts a custom message and cause. If provided, the cause is
the exception object that was handled when this exception is created.
Args:
message: A human readable message that explains the error.
cause: An exception object that caused this exception to be raised.
"""
msg = message if message else ""
if cause:
self.cause = cause
msg += f" Caused by {cause!r}"
if getattr(cause, "response", None) is not None:
try:
self._response = NetAppResponse(cause.response) # type: ignore
err_msg = cause.response.json().get("error", {}).get("message") # type: ignore
if err_msg:
msg += f": {err_msg}"
except Exception: # pylint: disable=broad-except
# the error response wasn't json so there's nothing additional
# we will add
pass
super().__init__(msg.strip())
@property
def http_err_response(self) -> Optional[NetAppResponse]:
"""Describes a response to an API request that contains an error.
Returns:
Response object if the exception was raised because of an API failure (HTTP status code of 400 or higher). None if the exception was not related to an API error.
"""
return getattr(self, "_response", None)
@property
def status_code(self) -> Optional[int]:
"""Return the status code of the HTTP response if this error was generated
from a failed HTTP request. Otherwise, returns None
"""
if not getattr(self, "_response", None):
return None
return self._response.http_response.status_code
@property
def response_body(self) -> Optional[dict]:
"""Return the HTTP response body if this error was generated from a failed
HTTP request. The body will be in dictionary form. If this exception is
not from a failed request or the body cannot be parsed as JSON, returns None
"""
if not getattr(self, "_response", None):
return None
try:
return self._response.http_response.json()
except ValueError:
return None
@property
def response_text(self) -> Optional[str]:
"""Return the HTTP response body if this error was generated from a failed
HTTP request. This will be the raw text of the response body. This is useful
when the response body cannot be parsed as JSON.
"""
if not getattr(self, "_response", None):
return None
return self._response.http_response.text
| (message: str = None, cause: Exception = None) -> None |
15,937 | netapp_ontap.error | __init__ | Initalize the error object.
Optionally accepts a custom message and cause. If provided, the cause is
the exception object that was handled when this exception is created.
Args:
message: A human readable message that explains the error.
cause: An exception object that caused this exception to be raised.
| def __init__(self, message: str = None, cause: Exception = None) -> None:
"""Initalize the error object.
Optionally accepts a custom message and cause. If provided, the cause is
the exception object that was handled when this exception is created.
Args:
message: A human readable message that explains the error.
cause: An exception object that caused this exception to be raised.
"""
msg = message if message else ""
if cause:
self.cause = cause
msg += f" Caused by {cause!r}"
if getattr(cause, "response", None) is not None:
try:
self._response = NetAppResponse(cause.response) # type: ignore
err_msg = cause.response.json().get("error", {}).get("message") # type: ignore
if err_msg:
msg += f": {err_msg}"
except Exception: # pylint: disable=broad-except
# the error response wasn't json so there's nothing additional
# we will add
pass
super().__init__(msg.strip())
| (self, message: Optional[str] = None, cause: Optional[Exception] = None) -> NoneType |
15,941 | sqlalchemy_utc.sqltypes | UtcDateTime | Almost equivalent to :class:`~sqlalchemy.types.DateTime` with
``timezone=True`` option, but it differs from that by:
- Never silently take naive :class:`~datetime.datetime`, instead it
always raise :exc:`ValueError` unless time zone aware value.
- :class:`~datetime.datetime` value's :attr:`~datetime.datetime.tzinfo`
is always converted to UTC.
- Unlike SQLAlchemy's built-in :class:`~sqlalchemy.types.DateTime`,
it never return naive :class:`~datetime.datetime`, but time zone
aware value, even with SQLite or MySQL.
| class UtcDateTime(TypeDecorator):
"""Almost equivalent to :class:`~sqlalchemy.types.DateTime` with
``timezone=True`` option, but it differs from that by:
- Never silently take naive :class:`~datetime.datetime`, instead it
always raise :exc:`ValueError` unless time zone aware value.
- :class:`~datetime.datetime` value's :attr:`~datetime.datetime.tzinfo`
is always converted to UTC.
- Unlike SQLAlchemy's built-in :class:`~sqlalchemy.types.DateTime`,
it never return naive :class:`~datetime.datetime`, but time zone
aware value, even with SQLite or MySQL.
"""
impl = DateTime(timezone=True)
cache_ok = True
def process_bind_param(self, value, dialect):
if value is not None:
if not isinstance(value, datetime.datetime):
raise TypeError('expected datetime.datetime, not ' +
repr(value))
elif value.tzinfo is None:
raise ValueError('naive datetime is disallowed')
return value.astimezone(utc)
def process_result_value(self, value, dialect):
if value is not None:
if value.tzinfo is None:
value = value.replace(tzinfo=utc)
else:
value = value.astimezone(utc)
return value
| (*args: 'Any', **kwargs: 'Any') |
15,942 | sqlalchemy.sql.type_api | __getattr__ | Proxy all other undefined accessors to the underlying
implementation. | def __getattr__(self, key: str) -> Any:
"""Proxy all other undefined accessors to the underlying
implementation."""
return getattr(self.impl_instance, key)
| (self, key: str) -> Any |
15,943 | sqlalchemy.sql.type_api | __init__ | Construct a :class:`.TypeDecorator`.
Arguments sent here are passed to the constructor
of the class assigned to the ``impl`` class level attribute,
assuming the ``impl`` is a callable, and the resulting
object is assigned to the ``self.impl`` instance attribute
(thus overriding the class attribute of the same name).
If the class level ``impl`` is not a callable (the unusual case),
it will be assigned to the same instance attribute 'as-is',
ignoring those arguments passed to the constructor.
Subclasses can override this to customize the generation
of ``self.impl`` entirely.
| def __init__(self, *args: Any, **kwargs: Any):
"""Construct a :class:`.TypeDecorator`.
Arguments sent here are passed to the constructor
of the class assigned to the ``impl`` class level attribute,
assuming the ``impl`` is a callable, and the resulting
object is assigned to the ``self.impl`` instance attribute
(thus overriding the class attribute of the same name).
If the class level ``impl`` is not a callable (the unusual case),
it will be assigned to the same instance attribute 'as-is',
ignoring those arguments passed to the constructor.
Subclasses can override this to customize the generation
of ``self.impl`` entirely.
"""
if not hasattr(self.__class__, "impl"):
raise AssertionError(
"TypeDecorator implementations "
"require a class-level variable "
"'impl' which refers to the class of "
"type being decorated"
)
self.impl = to_instance(self.__class__.impl, *args, **kwargs)
| (self, *args: Any, **kwargs: Any) |
15,944 | sqlalchemy.sql.type_api | __repr__ | null | def __repr__(self) -> str:
return util.generic_repr(self, to_inspect=self.impl_instance)
| (self) -> str |
15,945 | sqlalchemy.sql.type_api | __str__ | null | def __str__(self) -> str:
return str(self.compile())
| (self) -> str |
15,946 | sqlalchemy.sql.type_api | _cached_bind_processor | Return a dialect-specific bind processor for this type. | def _cached_bind_processor(
self, dialect: Dialect
) -> Optional[_BindProcessorType[_T]]:
"""Return a dialect-specific bind processor for this type."""
try:
return dialect._type_memos[self]["bind"]
except KeyError:
pass
# avoid KeyError context coming into bind_processor() function
# raises
d = self._dialect_info(dialect)
d["bind"] = bp = d["impl"].bind_processor(dialect)
return bp
| (self, dialect: 'Dialect') -> 'Optional[_BindProcessorType[_T]]' |
15,947 | sqlalchemy.sql.type_api | _cached_custom_processor | return a dialect-specific processing object for
custom purposes.
The cx_Oracle dialect uses this at the moment.
| def _cached_custom_processor(
self, dialect: Dialect, key: str, fn: Callable[[TypeEngine[_T]], _O]
) -> _O:
"""return a dialect-specific processing object for
custom purposes.
The cx_Oracle dialect uses this at the moment.
"""
try:
return cast(_O, dialect._type_memos[self]["custom"][key])
except KeyError:
pass
# avoid KeyError context coming into fn() function
# raises
d = self._dialect_info(dialect)
impl = d["impl"]
custom_dict = d.setdefault("custom", {})
custom_dict[key] = result = fn(impl)
return result
| (self, dialect: 'Dialect', key: 'str', fn: 'Callable[[TypeEngine[_T]], _O]') -> '_O' |
15,948 | sqlalchemy.sql.type_api | _cached_literal_processor | Return a dialect-specific literal processor for this type. | def _cached_literal_processor(
self, dialect: Dialect
) -> Optional[_LiteralProcessorType[_T]]:
"""Return a dialect-specific literal processor for this type."""
try:
return dialect._type_memos[self]["literal"]
except KeyError:
pass
# avoid KeyError context coming into literal_processor() function
# raises
d = self._dialect_info(dialect)
d["literal"] = lp = d["impl"].literal_processor(dialect)
return lp
| (self, dialect: 'Dialect') -> 'Optional[_LiteralProcessorType[_T]]' |
15,949 | sqlalchemy.sql.type_api | _cached_result_processor | Return a dialect-specific result processor for this type. | def _cached_result_processor(
self, dialect: Dialect, coltype: Any
) -> Optional[_ResultProcessorType[_T]]:
"""Return a dialect-specific result processor for this type."""
try:
return dialect._type_memos[self]["result"][coltype]
except KeyError:
pass
# avoid KeyError context coming into result_processor() function
# raises
d = self._dialect_info(dialect)
# key assumption: DBAPI type codes are
# constants. Else this dictionary would
# grow unbounded.
rp = d["impl"].result_processor(dialect, coltype)
d["result"][coltype] = rp
return rp
| (self, dialect: 'Dialect', coltype: 'Any') -> 'Optional[_ResultProcessorType[_T]]' |
15,950 | sqlalchemy.sql.type_api | _compare_type_affinity | null | def _compare_type_affinity(self, other: TypeEngine[Any]) -> bool:
return self._type_affinity is other._type_affinity
| (self, other: sqlalchemy.sql.type_api.TypeEngine) -> bool |
15,951 | sqlalchemy.sql.visitors | _compiler_dispatch | Look for an attribute named "visit_<visit_name>" on the
visitor, and call it with the same kw params.
| @classmethod
def _generate_compiler_dispatch(cls) -> None:
visit_name = cls.__visit_name__
if "_compiler_dispatch" in cls.__dict__:
# class has a fixed _compiler_dispatch() method.
# copy it to "original" so that we can get it back if
# sqlalchemy.ext.compiles overrides it.
cls._original_compiler_dispatch = cls._compiler_dispatch
return
if not isinstance(visit_name, str):
raise exc.InvalidRequestError(
f"__visit_name__ on class {cls.__name__} must be a string "
"at the class level"
)
name = "visit_%s" % visit_name
getter = operator.attrgetter(name)
def _compiler_dispatch(
self: Visitable, visitor: Any, **kw: Any
) -> str:
"""Look for an attribute named "visit_<visit_name>" on the
visitor, and call it with the same kw params.
"""
try:
meth = getter(visitor)
except AttributeError as err:
return visitor.visit_unsupported_compilation(self, err, **kw) # type: ignore # noqa: E501
else:
return meth(self, **kw) # type: ignore # noqa: E501
cls._compiler_dispatch = ( # type: ignore
cls._original_compiler_dispatch
) = _compiler_dispatch
| (self: sqlalchemy.sql.visitors.Visitable, visitor: Any, **kw: Any) -> str |
15,952 | sqlalchemy.sql.type_api | _default_dialect | null | @util.preload_module("sqlalchemy.engine.default")
def _default_dialect(self) -> Dialect:
default = util.preloaded.engine_default
# dmypy / mypy seems to sporadically keep thinking this line is
# returning Any, which seems to be caused by the @deprecated_params
# decorator on the DefaultDialect constructor
return default.StrCompileDialect() # type: ignore
| (self) -> 'Dialect' |
15,953 | sqlalchemy.sql.type_api | _dialect_info | Return a dialect-specific registry which
caches a dialect-specific implementation, bind processing
function, and one or more result processing functions. | def _dialect_info(self, dialect: Dialect) -> _TypeMemoDict:
"""Return a dialect-specific registry which
caches a dialect-specific implementation, bind processing
function, and one or more result processing functions."""
if self in dialect._type_memos:
return dialect._type_memos[self]
else:
impl = self._gen_dialect_impl(dialect)
if impl is self:
impl = self.adapt(type(self))
# this can't be self, else we create a cycle
assert impl is not self
d: _TypeMemoDict = {"impl": impl, "result": {}}
dialect._type_memos[self] = d
return d
| (self, dialect: 'Dialect') -> '_TypeMemoDict' |
15,954 | sqlalchemy.sql.type_api | _gen_dialect_impl | null | def _gen_dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
if dialect.name in self._variant_mapping:
adapted = dialect.type_descriptor(
self._variant_mapping[dialect.name]
)
else:
adapted = dialect.type_descriptor(self)
if adapted is not self:
return adapted
# otherwise adapt the impl type, link
# to a copy of this TypeDecorator and return
# that.
typedesc = self.load_dialect_impl(dialect).dialect_impl(dialect)
tt = self.copy()
if not isinstance(tt, self.__class__):
raise AssertionError(
"Type object %s does not properly "
"implement the copy() method, it must "
"return an object of type %s" % (self, self.__class__)
)
tt.impl = tt.impl_instance = typedesc
return tt
| (self, dialect: 'Dialect') -> 'TypeEngine[_T]' |
15,956 | sqlalchemy.sql.type_api | _resolve_for_literal | adjust this type given a literal Python value that will be
stored in a bound parameter.
Used exclusively by _resolve_value_to_type().
.. versionadded:: 1.4.30 or 2.0
TODO: this should be part of public API
.. seealso::
:meth:`.TypeEngine._resolve_for_python_type`
| def _resolve_for_literal(self, value: Any) -> Self:
"""adjust this type given a literal Python value that will be
stored in a bound parameter.
Used exclusively by _resolve_value_to_type().
.. versionadded:: 1.4.30 or 2.0
TODO: this should be part of public API
.. seealso::
:meth:`.TypeEngine._resolve_for_python_type`
"""
return self
| (self, value: Any) -> typing_extensions.Self |
15,957 | sqlalchemy.sql.type_api | _resolve_for_python_type | given a Python type (e.g. ``int``, ``str``, etc. ) return an
instance of this :class:`.TypeEngine` that's appropriate for this type.
An additional argument ``matched_on`` is passed, which indicates an
entry from the ``__mro__`` of the given ``python_type`` that more
specifically matches how the caller located this :class:`.TypeEngine`
object. Such as, if a lookup of some kind links the ``int`` Python
type to the :class:`.Integer` SQL type, and the original object
was some custom subclass of ``int`` such as ``MyInt(int)``, the
arguments passed would be ``(MyInt, int)``.
If the given Python type does not correspond to this
:class:`.TypeEngine`, or the Python type is otherwise ambiguous, the
method should return None.
For simple cases, the method checks that the ``python_type``
and ``matched_on`` types are the same (i.e. not a subclass), and
returns self; for all other cases, it returns ``None``.
The initial use case here is for the ORM to link user-defined
Python standard library ``enum.Enum`` classes to the SQLAlchemy
:class:`.Enum` SQL type when constructing ORM Declarative mappings.
:param python_type: the Python type we want to use
:param matched_on: the Python type that led us to choose this
particular :class:`.TypeEngine` class, which would be a supertype
of ``python_type``. By default, the request is rejected if
``python_type`` doesn't match ``matched_on`` (None is returned).
.. versionadded:: 2.0.0b4
TODO: this should be part of public API
.. seealso::
:meth:`.TypeEngine._resolve_for_literal`
| def _resolve_for_python_type(
self,
python_type: Type[Any],
matched_on: _MatchedOnType,
matched_on_flattened: Type[Any],
) -> Optional[Self]:
"""given a Python type (e.g. ``int``, ``str``, etc. ) return an
instance of this :class:`.TypeEngine` that's appropriate for this type.
An additional argument ``matched_on`` is passed, which indicates an
entry from the ``__mro__`` of the given ``python_type`` that more
specifically matches how the caller located this :class:`.TypeEngine`
object. Such as, if a lookup of some kind links the ``int`` Python
type to the :class:`.Integer` SQL type, and the original object
was some custom subclass of ``int`` such as ``MyInt(int)``, the
arguments passed would be ``(MyInt, int)``.
If the given Python type does not correspond to this
:class:`.TypeEngine`, or the Python type is otherwise ambiguous, the
method should return None.
For simple cases, the method checks that the ``python_type``
and ``matched_on`` types are the same (i.e. not a subclass), and
returns self; for all other cases, it returns ``None``.
The initial use case here is for the ORM to link user-defined
Python standard library ``enum.Enum`` classes to the SQLAlchemy
:class:`.Enum` SQL type when constructing ORM Declarative mappings.
:param python_type: the Python type we want to use
:param matched_on: the Python type that led us to choose this
particular :class:`.TypeEngine` class, which would be a supertype
of ``python_type``. By default, the request is rejected if
``python_type`` doesn't match ``matched_on`` (None is returned).
.. versionadded:: 2.0.0b4
TODO: this should be part of public API
.. seealso::
:meth:`.TypeEngine._resolve_for_literal`
"""
if python_type is not matched_on_flattened:
return None
return self
| (self, python_type: 'Type[Any]', matched_on: '_MatchedOnType', matched_on_flattened: 'Type[Any]') -> 'Optional[Self]' |
15,958 | sqlalchemy.sql.type_api | _set_parent | Support SchemaEventTarget | def _set_parent(
self, parent: SchemaEventTarget, outer: bool = False, **kw: Any
) -> None:
"""Support SchemaEventTarget"""
super()._set_parent(parent)
if not outer and isinstance(self.impl_instance, SchemaEventTarget):
self.impl_instance._set_parent(parent, outer=False, **kw)
| (self, parent: sqlalchemy.sql.base.SchemaEventTarget, outer: bool = False, **kw: Any) -> NoneType |
15,959 | sqlalchemy.sql.type_api | _set_parent_with_dispatch | Support SchemaEventTarget | def _set_parent_with_dispatch(
self, parent: SchemaEventTarget, **kw: Any
) -> None:
"""Support SchemaEventTarget"""
super()._set_parent_with_dispatch(parent, outer=True, **kw)
if isinstance(self.impl_instance, SchemaEventTarget):
self.impl_instance._set_parent_with_dispatch(parent)
| (self, parent: sqlalchemy.sql.base.SchemaEventTarget, **kw: Any) -> NoneType |
15,960 | sqlalchemy.sql.type_api | _to_instance | null | @staticmethod
def _to_instance(cls_or_self: Union[Type[_TE], _TE]) -> _TE:
return to_instance(cls_or_self)
| (cls_or_self: Union[Type[~_TE], ~_TE]) -> ~_TE |
15,961 | sqlalchemy.sql.type_api | _unwrapped_dialect_impl | Return the 'unwrapped' dialect impl for this type.
This is used by the :meth:`.DefaultDialect.set_input_sizes`
method.
| def _unwrapped_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
"""Return the 'unwrapped' dialect impl for this type.
This is used by the :meth:`.DefaultDialect.set_input_sizes`
method.
"""
# some dialects have a lookup for a TypeDecorator subclass directly.
# postgresql.INTERVAL being the main example
typ = self.dialect_impl(dialect)
# if we are still a type decorator, load the per-dialect switch
# (such as what Variant uses), then get the dialect impl for that.
if isinstance(typ, self.__class__):
return typ.load_dialect_impl(dialect).dialect_impl(dialect)
else:
return typ
| (self, dialect: 'Dialect') -> 'TypeEngine[Any]' |
15,962 | sqlalchemy.sql.type_api | adapt | Produce an "adapted" form of this type, given an "impl" class
to work with.
This method is used internally to associate generic
types with "implementation" types that are specific to a particular
dialect.
| def adapt(
self, cls: Type[Union[TypeEngine[Any], TypeEngineMixin]], **kw: Any
) -> TypeEngine[Any]:
"""Produce an "adapted" form of this type, given an "impl" class
to work with.
This method is used internally to associate generic
types with "implementation" types that are specific to a particular
dialect.
"""
typ = util.constructor_copy(
self, cast(Type[TypeEngine[Any]], cls), **kw
)
typ._variant_mapping = self._variant_mapping
return typ
| (self, cls: Type[Union[sqlalchemy.sql.type_api.TypeEngine, sqlalchemy.sql.type_api.TypeEngineMixin]], **kw: Any) -> sqlalchemy.sql.type_api.TypeEngine |
15,963 | sqlalchemy.sql.type_api | as_generic |
Return an instance of the generic type corresponding to this type
using heuristic rule. The method may be overridden if this
heuristic rule is not sufficient.
>>> from sqlalchemy.dialects.mysql import INTEGER
>>> INTEGER(display_width=4).as_generic()
Integer()
>>> from sqlalchemy.dialects.mysql import NVARCHAR
>>> NVARCHAR(length=100).as_generic()
Unicode(length=100)
.. versionadded:: 1.4.0b2
.. seealso::
:ref:`metadata_reflection_dbagnostic_types` - describes the
use of :meth:`_types.TypeEngine.as_generic` in conjunction with
the :meth:`_sql.DDLEvents.column_reflect` event, which is its
intended use.
| def as_generic(self, allow_nulltype: bool = False) -> TypeEngine[_T]:
"""
Return an instance of the generic type corresponding to this type
using heuristic rule. The method may be overridden if this
heuristic rule is not sufficient.
>>> from sqlalchemy.dialects.mysql import INTEGER
>>> INTEGER(display_width=4).as_generic()
Integer()
>>> from sqlalchemy.dialects.mysql import NVARCHAR
>>> NVARCHAR(length=100).as_generic()
Unicode(length=100)
.. versionadded:: 1.4.0b2
.. seealso::
:ref:`metadata_reflection_dbagnostic_types` - describes the
use of :meth:`_types.TypeEngine.as_generic` in conjunction with
the :meth:`_sql.DDLEvents.column_reflect` event, which is its
intended use.
"""
if (
not allow_nulltype
and self._generic_type_affinity == NULLTYPE.__class__
):
raise NotImplementedError(
"Default TypeEngine.as_generic() "
"heuristic method was unsuccessful for {}. A custom "
"as_generic() method must be implemented for this "
"type class.".format(
self.__class__.__module__ + "." + self.__class__.__name__
)
)
return util.constructor_copy(self, self._generic_type_affinity)
| (self, allow_nulltype: bool = False) -> sqlalchemy.sql.type_api.TypeEngine |
15,964 | sqlalchemy.sql.type_api | bind_expression | Given a bind value (i.e. a :class:`.BindParameter` instance),
return a SQL expression which will typically wrap the given parameter.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. It is **not** necessarily
called against specific values, and should not be confused with the
:meth:`_types.TypeDecorator.process_bind_param` method, which is
the more typical method that processes the actual value passed to a
particular parameter at statement execution time.
Subclasses of :class:`_types.TypeDecorator` can override this method
to provide custom bind expression behavior for the type. This
implementation will **replace** that of the underlying implementation
type.
| def bind_expression(
self, bindparam: BindParameter[_T]
) -> Optional[ColumnElement[_T]]:
"""Given a bind value (i.e. a :class:`.BindParameter` instance),
return a SQL expression which will typically wrap the given parameter.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. It is **not** necessarily
called against specific values, and should not be confused with the
:meth:`_types.TypeDecorator.process_bind_param` method, which is
the more typical method that processes the actual value passed to a
particular parameter at statement execution time.
Subclasses of :class:`_types.TypeDecorator` can override this method
to provide custom bind expression behavior for the type. This
implementation will **replace** that of the underlying implementation
type.
"""
return self.impl_instance.bind_expression(bindparam)
| (self, bindparam: 'BindParameter[_T]') -> 'Optional[ColumnElement[_T]]' |
15,965 | sqlalchemy.sql.type_api | bind_processor | Provide a bound value processing function for the
given :class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for bound value conversion which normally occurs via
the :meth:`_types.TypeEngine.bind_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_bind_param` so that the "inner"
processing provided by the implementing type is maintained.
:param dialect: Dialect instance in use.
| def bind_processor(
self, dialect: Dialect
) -> Optional[_BindProcessorType[_T]]:
"""Provide a bound value processing function for the
given :class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for bound value conversion which normally occurs via
the :meth:`_types.TypeEngine.bind_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_bind_param` so that the "inner"
processing provided by the implementing type is maintained.
:param dialect: Dialect instance in use.
"""
if self._has_bind_processor:
process_param = self.process_bind_param
impl_processor = self.impl_instance.bind_processor(dialect)
if impl_processor:
fixed_impl_processor = impl_processor
fixed_process_param = process_param
def process(value: Optional[_T]) -> Any:
return fixed_impl_processor(
fixed_process_param(value, dialect)
)
else:
fixed_process_param = process_param
def process(value: Optional[_T]) -> Any:
return fixed_process_param(value, dialect)
return process
else:
return self.impl_instance.bind_processor(dialect)
| (self, dialect: 'Dialect') -> 'Optional[_BindProcessorType[_T]]' |
15,966 | sqlalchemy.sql.type_api | coerce_compared_value | Suggest a type for a 'coerced' Python value in an expression.
By default, returns self. This method is called by
the expression system when an object using this type is
on the left or right side of an expression against a plain Python
object which does not yet have a SQLAlchemy type assigned::
expr = table.c.somecolumn + 35
Where above, if ``somecolumn`` uses this type, this method will
be called with the value ``operator.add``
and ``35``. The return value is whatever SQLAlchemy type should
be used for ``35`` for this particular operation.
| def coerce_compared_value(
self, op: Optional[OperatorType], value: Any
) -> Any:
"""Suggest a type for a 'coerced' Python value in an expression.
By default, returns self. This method is called by
the expression system when an object using this type is
on the left or right side of an expression against a plain Python
object which does not yet have a SQLAlchemy type assigned::
expr = table.c.somecolumn + 35
Where above, if ``somecolumn`` uses this type, this method will
be called with the value ``operator.add``
and ``35``. The return value is whatever SQLAlchemy type should
be used for ``35`` for this particular operation.
"""
return self
| (self, op: 'Optional[OperatorType]', value: 'Any') -> 'Any' |
15,967 | sqlalchemy.sql.type_api | column_expression | Given a SELECT column expression, return a wrapping SQL expression.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. It is **not** called
against specific values, and should not be confused with the
:meth:`_types.TypeDecorator.process_result_value` method, which is
the more typical method that processes the actual value returned
in a result row subsequent to statement execution time.
Subclasses of :class:`_types.TypeDecorator` can override this method
to provide custom column expression behavior for the type. This
implementation will **replace** that of the underlying implementation
type.
See the description of :meth:`_types.TypeEngine.column_expression`
for a complete description of the method's use.
| def column_expression(
self, column: ColumnElement[_T]
) -> Optional[ColumnElement[_T]]:
"""Given a SELECT column expression, return a wrapping SQL expression.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. It is **not** called
against specific values, and should not be confused with the
:meth:`_types.TypeDecorator.process_result_value` method, which is
the more typical method that processes the actual value returned
in a result row subsequent to statement execution time.
Subclasses of :class:`_types.TypeDecorator` can override this method
to provide custom column expression behavior for the type. This
implementation will **replace** that of the underlying implementation
type.
See the description of :meth:`_types.TypeEngine.column_expression`
for a complete description of the method's use.
"""
return self.impl_instance.column_expression(column)
| (self, column: 'ColumnElement[_T]') -> 'Optional[ColumnElement[_T]]' |
15,968 | sqlalchemy.sql.type_api | compare_values | Given two values, compare them for equality.
By default this calls upon :meth:`.TypeEngine.compare_values`
of the underlying "impl", which in turn usually
uses the Python equals operator ``==``.
This function is used by the ORM to compare
an original-loaded value with an intercepted
"changed" value, to determine if a net change
has occurred.
| def compare_values(self, x: Any, y: Any) -> bool:
"""Given two values, compare them for equality.
By default this calls upon :meth:`.TypeEngine.compare_values`
of the underlying "impl", which in turn usually
uses the Python equals operator ``==``.
This function is used by the ORM to compare
an original-loaded value with an intercepted
"changed" value, to determine if a net change
has occurred.
"""
return self.impl_instance.compare_values(x, y)
| (self, x: Any, y: Any) -> bool |
15,969 | sqlalchemy.sql.type_api | compile | Produce a string-compiled form of this :class:`.TypeEngine`.
When called with no arguments, uses a "default" dialect
to produce a string result.
:param dialect: a :class:`.Dialect` instance.
| def compile(self, dialect: Optional[Dialect] = None) -> str:
"""Produce a string-compiled form of this :class:`.TypeEngine`.
When called with no arguments, uses a "default" dialect
to produce a string result.
:param dialect: a :class:`.Dialect` instance.
"""
# arg, return value is inconsistent with
# ClauseElement.compile()....this is a mistake.
if dialect is None:
dialect = self._default_dialect()
return dialect.type_compiler_instance.process(self)
| (self, dialect: 'Optional[Dialect]' = None) -> 'str' |
15,970 | sqlalchemy.sql.type_api | copy | Produce a copy of this :class:`.TypeDecorator` instance.
This is a shallow copy and is provided to fulfill part of
the :class:`.TypeEngine` contract. It usually does not
need to be overridden unless the user-defined :class:`.TypeDecorator`
has local state that should be deep-copied.
| def copy(self, **kw: Any) -> Self:
"""Produce a copy of this :class:`.TypeDecorator` instance.
This is a shallow copy and is provided to fulfill part of
the :class:`.TypeEngine` contract. It usually does not
need to be overridden unless the user-defined :class:`.TypeDecorator`
has local state that should be deep-copied.
"""
instance = self.__class__.__new__(self.__class__)
instance.__dict__.update(self.__dict__)
return instance
| (self, **kw: Any) -> typing_extensions.Self |
15,971 | sqlalchemy.sql.type_api | copy_value | null | def copy_value(self, value: Any) -> Any:
return value
| (self, value: Any) -> Any |
15,972 | sqlalchemy.sql.type_api | dialect_impl | Return a dialect-specific implementation for this
:class:`.TypeEngine`.
| def dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
"""Return a dialect-specific implementation for this
:class:`.TypeEngine`.
"""
try:
tm = dialect._type_memos[self]
except KeyError:
pass
else:
return tm["impl"]
return self._dialect_info(dialect)["impl"]
| (self, dialect: 'Dialect') -> 'TypeEngine[_T]' |
15,973 | sqlalchemy.sql.type_api | evaluates_none | Return a copy of this type which has the
:attr:`.should_evaluate_none` flag set to True.
E.g.::
Table(
'some_table', metadata,
Column(
String(50).evaluates_none(),
nullable=True,
server_default='no value')
)
The ORM uses this flag to indicate that a positive value of ``None``
is passed to the column in an INSERT statement, rather than omitting
the column from the INSERT statement which has the effect of firing
off column-level defaults. It also allows for types which have
special behavior associated with the Python None value to indicate
that the value doesn't necessarily translate into SQL NULL; a
prime example of this is a JSON type which may wish to persist the
JSON value ``'null'``.
In all cases, the actual NULL SQL value can be always be
persisted in any column by using
the :obj:`_expression.null` SQL construct in an INSERT statement
or associated with an ORM-mapped attribute.
.. note::
The "evaluates none" flag does **not** apply to a value
of ``None`` passed to :paramref:`_schema.Column.default` or
:paramref:`_schema.Column.server_default`; in these cases,
``None``
still means "no default".
.. seealso::
:ref:`session_forcing_null` - in the ORM documentation
:paramref:`.postgresql.JSON.none_as_null` - PostgreSQL JSON
interaction with this flag.
:attr:`.TypeEngine.should_evaluate_none` - class-level flag
| def evaluates_none(self) -> Self:
"""Return a copy of this type which has the
:attr:`.should_evaluate_none` flag set to True.
E.g.::
Table(
'some_table', metadata,
Column(
String(50).evaluates_none(),
nullable=True,
server_default='no value')
)
The ORM uses this flag to indicate that a positive value of ``None``
is passed to the column in an INSERT statement, rather than omitting
the column from the INSERT statement which has the effect of firing
off column-level defaults. It also allows for types which have
special behavior associated with the Python None value to indicate
that the value doesn't necessarily translate into SQL NULL; a
prime example of this is a JSON type which may wish to persist the
JSON value ``'null'``.
In all cases, the actual NULL SQL value can be always be
persisted in any column by using
the :obj:`_expression.null` SQL construct in an INSERT statement
or associated with an ORM-mapped attribute.
.. note::
The "evaluates none" flag does **not** apply to a value
of ``None`` passed to :paramref:`_schema.Column.default` or
:paramref:`_schema.Column.server_default`; in these cases,
``None``
still means "no default".
.. seealso::
:ref:`session_forcing_null` - in the ORM documentation
:paramref:`.postgresql.JSON.none_as_null` - PostgreSQL JSON
interaction with this flag.
:attr:`.TypeEngine.should_evaluate_none` - class-level flag
"""
typ = self.copy()
typ.should_evaluate_none = True
return typ
| (self) -> typing_extensions.Self |
15,974 | sqlalchemy.sql.type_api | get_dbapi_type | Return the DBAPI type object represented by this
:class:`.TypeDecorator`.
By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the
underlying "impl".
| def get_dbapi_type(self, dbapi: ModuleType) -> Optional[Any]:
"""Return the DBAPI type object represented by this
:class:`.TypeDecorator`.
By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the
underlying "impl".
"""
return self.impl_instance.get_dbapi_type(dbapi)
| (self, dbapi: module) -> Optional[Any] |
15,975 | sqlalchemy.sql.type_api | literal_processor | Provide a literal processing function for the given
:class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for literal value conversion which normally occurs via
the :meth:`_types.TypeEngine.literal_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_literal_param` so that the
"inner" processing provided by the implementing type is maintained.
| def literal_processor(
self, dialect: Dialect
) -> Optional[_LiteralProcessorType[_T]]:
"""Provide a literal processing function for the given
:class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for literal value conversion which normally occurs via
the :meth:`_types.TypeEngine.literal_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_literal_param` so that the
"inner" processing provided by the implementing type is maintained.
"""
if self._has_literal_processor:
process_literal_param = self.process_literal_param
process_bind_param = None
elif self._has_bind_processor:
# use the bind processor if dont have a literal processor,
# but we have an impl literal processor
process_literal_param = None
process_bind_param = self.process_bind_param
else:
process_literal_param = None
process_bind_param = None
if process_literal_param is not None:
impl_processor = self.impl_instance.literal_processor(dialect)
if impl_processor:
fixed_impl_processor = impl_processor
fixed_process_literal_param = process_literal_param
def process(value: Any) -> str:
return fixed_impl_processor(
fixed_process_literal_param(value, dialect)
)
else:
fixed_process_literal_param = process_literal_param
def process(value: Any) -> str:
return fixed_process_literal_param(value, dialect)
return process
elif process_bind_param is not None:
impl_processor = self.impl_instance.literal_processor(dialect)
if not impl_processor:
return None
else:
fixed_impl_processor = impl_processor
fixed_process_bind_param = process_bind_param
def process(value: Any) -> str:
return fixed_impl_processor(
fixed_process_bind_param(value, dialect)
)
return process
else:
return self.impl_instance.literal_processor(dialect)
| (self, dialect: 'Dialect') -> 'Optional[_LiteralProcessorType[_T]]' |
15,976 | sqlalchemy.sql.type_api | load_dialect_impl | Return a :class:`.TypeEngine` object corresponding to a dialect.
This is an end-user override hook that can be used to provide
differing types depending on the given dialect. It is used
by the :class:`.TypeDecorator` implementation of :meth:`type_engine`
to help determine what type should ultimately be returned
for a given :class:`.TypeDecorator`.
By default returns ``self.impl``.
| def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
"""Return a :class:`.TypeEngine` object corresponding to a dialect.
This is an end-user override hook that can be used to provide
differing types depending on the given dialect. It is used
by the :class:`.TypeDecorator` implementation of :meth:`type_engine`
to help determine what type should ultimately be returned
for a given :class:`.TypeDecorator`.
By default returns ``self.impl``.
"""
return self.impl_instance
| (self, dialect: 'Dialect') -> 'TypeEngine[Any]' |
15,977 | sqlalchemy_utc.sqltypes | process_bind_param | null | def process_bind_param(self, value, dialect):
if value is not None:
if not isinstance(value, datetime.datetime):
raise TypeError('expected datetime.datetime, not ' +
repr(value))
elif value.tzinfo is None:
raise ValueError('naive datetime is disallowed')
return value.astimezone(utc)
| (self, value, dialect) |
15,978 | sqlalchemy.sql.type_api | process_literal_param | Receive a literal parameter value to be rendered inline within
a statement.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. Unlike other SQL
compilation methods, it is passed a specific Python value to be
rendered as a string. However it should not be confused with the
:meth:`_types.TypeDecorator.process_bind_param` method, which is
the more typical method that processes the actual value passed to a
particular parameter at statement execution time.
Custom subclasses of :class:`_types.TypeDecorator` should override
this method to provide custom behaviors for incoming data values
that are in the special case of being rendered as literals.
The returned string will be rendered into the output string.
| def process_literal_param(
self, value: Optional[_T], dialect: Dialect
) -> str:
"""Receive a literal parameter value to be rendered inline within
a statement.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. Unlike other SQL
compilation methods, it is passed a specific Python value to be
rendered as a string. However it should not be confused with the
:meth:`_types.TypeDecorator.process_bind_param` method, which is
the more typical method that processes the actual value passed to a
particular parameter at statement execution time.
Custom subclasses of :class:`_types.TypeDecorator` should override
this method to provide custom behaviors for incoming data values
that are in the special case of being rendered as literals.
The returned string will be rendered into the output string.
"""
raise NotImplementedError()
| (self, value: 'Optional[_T]', dialect: 'Dialect') -> 'str' |
15,979 | sqlalchemy_utc.sqltypes | process_result_value | null | def process_result_value(self, value, dialect):
if value is not None:
if value.tzinfo is None:
value = value.replace(tzinfo=utc)
else:
value = value.astimezone(utc)
return value
| (self, value, dialect) |
15,980 | sqlalchemy.sql.type_api | result_processor | Provide a result value processing function for the given
:class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for bound value conversion which normally occurs via
the :meth:`_types.TypeEngine.result_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_result_value` so that the
"inner" processing provided by the implementing type is maintained.
:param dialect: Dialect instance in use.
:param coltype: A SQLAlchemy data type
| def result_processor(
self, dialect: Dialect, coltype: Any
) -> Optional[_ResultProcessorType[_T]]:
"""Provide a result value processing function for the given
:class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for bound value conversion which normally occurs via
the :meth:`_types.TypeEngine.result_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_result_value` so that the
"inner" processing provided by the implementing type is maintained.
:param dialect: Dialect instance in use.
:param coltype: A SQLAlchemy data type
"""
if self._has_result_processor:
process_value = self.process_result_value
impl_processor = self.impl_instance.result_processor(
dialect, coltype
)
if impl_processor:
fixed_process_value = process_value
fixed_impl_processor = impl_processor
def process(value: Any) -> Optional[_T]:
return fixed_process_value(
fixed_impl_processor(value), dialect
)
else:
fixed_process_value = process_value
def process(value: Any) -> Optional[_T]:
return fixed_process_value(value, dialect)
return process
else:
return self.impl_instance.result_processor(dialect, coltype)
| (self, dialect: 'Dialect', coltype: 'Any') -> 'Optional[_ResultProcessorType[_T]]' |
15,981 | sqlalchemy.sql.type_api | type_engine | Return a dialect-specific :class:`.TypeEngine` instance
for this :class:`.TypeDecorator`.
In most cases this returns a dialect-adapted form of
the :class:`.TypeEngine` type represented by ``self.impl``.
Makes usage of :meth:`dialect_impl`.
Behavior can be customized here by overriding
:meth:`load_dialect_impl`.
| def type_engine(self, dialect: Dialect) -> TypeEngine[Any]:
"""Return a dialect-specific :class:`.TypeEngine` instance
for this :class:`.TypeDecorator`.
In most cases this returns a dialect-adapted form of
the :class:`.TypeEngine` type represented by ``self.impl``.
Makes usage of :meth:`dialect_impl`.
Behavior can be customized here by overriding
:meth:`load_dialect_impl`.
"""
adapted = dialect.type_descriptor(self)
if not isinstance(adapted, type(self)):
return adapted
else:
return self.load_dialect_impl(dialect)
| (self, dialect: 'Dialect') -> 'TypeEngine[Any]' |
15,982 | sqlalchemy.sql.type_api | with_variant | Produce a copy of this type object that will utilize the given
type when applied to the dialect of the given name.
e.g.::
from sqlalchemy.types import String
from sqlalchemy.dialects import mysql
string_type = String()
string_type = string_type.with_variant(
mysql.VARCHAR(collation='foo'), 'mysql', 'mariadb'
)
The variant mapping indicates that when this type is
interpreted by a specific dialect, it will instead be
transmuted into the given type, rather than using the
primary type.
.. versionchanged:: 2.0 the :meth:`_types.TypeEngine.with_variant`
method now works with a :class:`_types.TypeEngine` object "in
place", returning a copy of the original type rather than returning
a wrapping object; the ``Variant`` class is no longer used.
:param type\_: a :class:`.TypeEngine` that will be selected
as a variant from the originating type, when a dialect
of the given name is in use.
:param \*dialect_names: one or more base names of the dialect which
uses this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)
.. versionchanged:: 2.0 multiple dialect names can be specified
for one variant.
.. seealso::
:ref:`types_with_variant` - illustrates the use of
:meth:`_types.TypeEngine.with_variant`.
| def with_variant(
self,
type_: _TypeEngineArgument[Any],
*dialect_names: str,
) -> Self:
r"""Produce a copy of this type object that will utilize the given
type when applied to the dialect of the given name.
e.g.::
from sqlalchemy.types import String
from sqlalchemy.dialects import mysql
string_type = String()
string_type = string_type.with_variant(
mysql.VARCHAR(collation='foo'), 'mysql', 'mariadb'
)
The variant mapping indicates that when this type is
interpreted by a specific dialect, it will instead be
transmuted into the given type, rather than using the
primary type.
.. versionchanged:: 2.0 the :meth:`_types.TypeEngine.with_variant`
method now works with a :class:`_types.TypeEngine` object "in
place", returning a copy of the original type rather than returning
a wrapping object; the ``Variant`` class is no longer used.
:param type\_: a :class:`.TypeEngine` that will be selected
as a variant from the originating type, when a dialect
of the given name is in use.
:param \*dialect_names: one or more base names of the dialect which
uses this type. (i.e. ``'postgresql'``, ``'mysql'``, etc.)
.. versionchanged:: 2.0 multiple dialect names can be specified
for one variant.
.. seealso::
:ref:`types_with_variant` - illustrates the use of
:meth:`_types.TypeEngine.with_variant`.
"""
if not dialect_names:
raise exc.ArgumentError("At least one dialect name is required")
for dialect_name in dialect_names:
if dialect_name in self._variant_mapping:
raise exc.ArgumentError(
f"Dialect {dialect_name!r} is already present in "
f"the mapping for this {self!r}"
)
new_type = self.copy()
type_ = to_instance(type_)
if type_._variant_mapping:
raise exc.ArgumentError(
"can't pass a type that already has variants as a "
"dialect-level type to with_variant()"
)
new_type._variant_mapping = self._variant_mapping.union(
{dialect_name: type_ for dialect_name in dialect_names}
)
return new_type
| (self, type_: '_TypeEngineArgument[Any]', *dialect_names: 'str') -> 'Self' |
15,986 | sqlalchemy_utc.now | utcnow | UTCNOW() expression for multiple dialects. | class utcnow(FunctionElement):
"""UTCNOW() expression for multiple dialects."""
type = UtcDateTime()
| (*clauses: '_ColumnExpressionOrLiteralArgument[Any]') |
15,987 | sqlalchemy.sql.operators | __add__ | Implement the ``+`` operator.
In a column context, produces the clause ``a + b``
if the parent object has non-string affinity.
If the parent object has a string affinity,
produces the concatenation operator, ``a || b`` -
see :meth:`.ColumnOperators.concat`.
| def __add__(self, other: Any) -> ColumnOperators:
"""Implement the ``+`` operator.
In a column context, produces the clause ``a + b``
if the parent object has non-string affinity.
If the parent object has a string affinity,
produces the concatenation operator, ``a || b`` -
see :meth:`.ColumnOperators.concat`.
"""
return self.operate(add, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
15,988 | sqlalchemy.sql.operators | __and__ | Implement the ``&`` operator.
When used with SQL expressions, results in an
AND operation, equivalent to
:func:`_expression.and_`, that is::
a & b
is equivalent to::
from sqlalchemy import and_
and_(a, b)
Care should be taken when using ``&`` regarding
operator precedence; the ``&`` operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions::
(a == 2) & (b == 4)
| def __and__(self, other: Any) -> Operators:
"""Implement the ``&`` operator.
When used with SQL expressions, results in an
AND operation, equivalent to
:func:`_expression.and_`, that is::
a & b
is equivalent to::
from sqlalchemy import and_
and_(a, b)
Care should be taken when using ``&`` regarding
operator precedence; the ``&`` operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions::
(a == 2) & (b == 4)
"""
return self.operate(and_, other)
| (self, other: Any) -> sqlalchemy.sql.operators.Operators |
15,989 | sqlalchemy.sql.elements | __bool__ | null | def __bool__(self):
raise TypeError("Boolean value of this clause is not defined")
| (self) |
15,990 | sqlalchemy.sql.operators | __contains__ | null | def __contains__(self, other: Any) -> ColumnOperators:
return self.operate(contains, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
15,991 | sqlalchemy.sql.operators | __eq__ | Implement the ``==`` operator.
In a column context, produces the clause ``a = b``.
If the target is ``None``, produces ``a IS NULL``.
| def __eq__(self, other: Any) -> ColumnOperators: # type: ignore[override]
"""Implement the ``==`` operator.
In a column context, produces the clause ``a = b``.
If the target is ``None``, produces ``a IS NULL``.
"""
return self.operate(eq, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
15,992 | sqlalchemy.sql.operators | __floordiv__ | Implement the ``//`` operator.
In a column context, produces the clause ``a / b``,
which is the same as "truediv", but considers the result
type to be integer.
.. versionadded:: 2.0
| def __floordiv__(self, other: Any) -> ColumnOperators:
"""Implement the ``//`` operator.
In a column context, produces the clause ``a / b``,
which is the same as "truediv", but considers the result
type to be integer.
.. versionadded:: 2.0
"""
return self.operate(floordiv, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
15,993 | sqlalchemy.sql.operators | __ge__ | Implement the ``>=`` operator.
In a column context, produces the clause ``a >= b``.
| def __ge__(self, other: Any) -> ColumnOperators:
"""Implement the ``>=`` operator.
In a column context, produces the clause ``a >= b``.
"""
return self.operate(ge, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
15,994 | sqlalchemy.sql.elements | __getattr__ | null | def __getattr__(self, key: str) -> Any:
try:
return getattr(self.comparator, key)
except AttributeError as err:
raise AttributeError(
"Neither %r object nor %r object has an attribute %r"
% (
type(self).__name__,
type(self.comparator).__name__,
key,
)
) from err
| (self, key: str) -> Any |
15,995 | sqlalchemy.sql.operators | __getitem__ | Implement the [] operator.
This can be used by some database-specific types
such as PostgreSQL ARRAY and HSTORE.
| def __getitem__(self, index: Any) -> ColumnOperators:
"""Implement the [] operator.
This can be used by some database-specific types
such as PostgreSQL ARRAY and HSTORE.
"""
return self.operate(getitem, index)
| (self, index: Any) -> sqlalchemy.sql.operators.ColumnOperators |
15,996 | sqlalchemy.sql.elements | __getstate__ | null | def __getstate__(self):
d = self.__dict__.copy()
d.pop("_is_clone_of", None)
d.pop("_generate_cache_key", None)
return d
| (self) |
15,997 | sqlalchemy.sql.operators | __gt__ | Implement the ``>`` operator.
In a column context, produces the clause ``a > b``.
| def __gt__(self, other: Any) -> ColumnOperators:
"""Implement the ``>`` operator.
In a column context, produces the clause ``a > b``.
"""
return self.operate(gt, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
15,998 | sqlalchemy.sql.functions | __init__ | Construct a :class:`.FunctionElement`.
:param \*clauses: list of column expressions that form the arguments
of the SQL function call.
:param \**kwargs: additional kwargs are typically consumed by
subclasses.
.. seealso::
:data:`.func`
:class:`.Function`
| def __init__(self, *clauses: _ColumnExpressionOrLiteralArgument[Any]):
r"""Construct a :class:`.FunctionElement`.
:param \*clauses: list of column expressions that form the arguments
of the SQL function call.
:param \**kwargs: additional kwargs are typically consumed by
subclasses.
.. seealso::
:data:`.func`
:class:`.Function`
"""
args: Sequence[_ColumnExpressionArgument[Any]] = [
coercions.expect(
roles.ExpressionElementRole,
c,
name=getattr(self, "name", None),
apply_propagate_attrs=self,
)
for c in clauses
]
self._has_args = self._has_args or bool(args)
self.clause_expr = Grouping(
ClauseList(operator=operators.comma_op, group_contents=True, *args)
)
| (self, *clauses: '_ColumnExpressionOrLiteralArgument[Any]') |
15,999 | sqlalchemy.sql.operators | __invert__ | Implement the ``~`` operator.
When used with SQL expressions, results in a
NOT operation, equivalent to
:func:`_expression.not_`, that is::
~a
is equivalent to::
from sqlalchemy import not_
not_(a)
| def __invert__(self) -> Operators:
"""Implement the ``~`` operator.
When used with SQL expressions, results in a
NOT operation, equivalent to
:func:`_expression.not_`, that is::
~a
is equivalent to::
from sqlalchemy import not_
not_(a)
"""
return self.operate(inv)
| (self) -> sqlalchemy.sql.operators.Operators |
16,000 | sqlalchemy.sql.operators | __le__ | Implement the ``<=`` operator.
In a column context, produces the clause ``a <= b``.
| def __le__(self, other: Any) -> ColumnOperators:
"""Implement the ``<=`` operator.
In a column context, produces the clause ``a <= b``.
"""
return self.operate(le, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,001 | sqlalchemy.sql.operators | __lshift__ | implement the << operator.
Not used by SQLAlchemy core, this is provided
for custom operator systems which want to use
<< as an extension point.
| def __lshift__(self, other: Any) -> ColumnOperators:
"""implement the << operator.
Not used by SQLAlchemy core, this is provided
for custom operator systems which want to use
<< as an extension point.
"""
return self.operate(lshift, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,002 | sqlalchemy.sql.operators | __lt__ | Implement the ``<`` operator.
In a column context, produces the clause ``a < b``.
| def __lt__(self, other: Any) -> ColumnOperators:
"""Implement the ``<`` operator.
In a column context, produces the clause ``a < b``.
"""
return self.operate(lt, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,003 | sqlalchemy.sql.operators | __mod__ | Implement the ``%`` operator.
In a column context, produces the clause ``a % b``.
| def __mod__(self, other: Any) -> ColumnOperators:
"""Implement the ``%`` operator.
In a column context, produces the clause ``a % b``.
"""
return self.operate(mod, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,004 | sqlalchemy.sql.operators | __mul__ | Implement the ``*`` operator.
In a column context, produces the clause ``a * b``.
| def __mul__(self, other: Any) -> ColumnOperators:
"""Implement the ``*`` operator.
In a column context, produces the clause ``a * b``.
"""
return self.operate(mul, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,005 | sqlalchemy.sql.operators | __ne__ | Implement the ``!=`` operator.
In a column context, produces the clause ``a != b``.
If the target is ``None``, produces ``a IS NOT NULL``.
| def __ne__(self, other: Any) -> ColumnOperators: # type: ignore[override]
"""Implement the ``!=`` operator.
In a column context, produces the clause ``a != b``.
If the target is ``None``, produces ``a IS NOT NULL``.
"""
return self.operate(ne, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,006 | sqlalchemy.sql.operators | __neg__ | Implement the ``-`` operator.
In a column context, produces the clause ``-a``.
| def __neg__(self) -> ColumnOperators:
"""Implement the ``-`` operator.
In a column context, produces the clause ``-a``.
"""
return self.operate(neg)
| (self) -> sqlalchemy.sql.operators.ColumnOperators |
16,007 | sqlalchemy.sql.operators | __or__ | Implement the ``|`` operator.
When used with SQL expressions, results in an
OR operation, equivalent to
:func:`_expression.or_`, that is::
a | b
is equivalent to::
from sqlalchemy import or_
or_(a, b)
Care should be taken when using ``|`` regarding
operator precedence; the ``|`` operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions::
(a == 2) | (b == 4)
| def __or__(self, other: Any) -> Operators:
"""Implement the ``|`` operator.
When used with SQL expressions, results in an
OR operation, equivalent to
:func:`_expression.or_`, that is::
a | b
is equivalent to::
from sqlalchemy import or_
or_(a, b)
Care should be taken when using ``|`` regarding
operator precedence; the ``|`` operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions::
(a == 2) | (b == 4)
"""
return self.operate(or_, other)
| (self, other: Any) -> sqlalchemy.sql.operators.Operators |
16,008 | sqlalchemy.sql.operators | __radd__ | Implement the ``+`` operator in reverse.
See :meth:`.ColumnOperators.__add__`.
| def __radd__(self, other: Any) -> ColumnOperators:
"""Implement the ``+`` operator in reverse.
See :meth:`.ColumnOperators.__add__`.
"""
return self.reverse_operate(add, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,009 | sqlalchemy.sql.elements | __repr__ | null | def __repr__(self):
friendly = self.description
if friendly is None:
return object.__repr__(self)
else:
return "<%s.%s at 0x%x; %s>" % (
self.__module__,
self.__class__.__name__,
id(self),
friendly,
)
| (self) |
16,010 | sqlalchemy.sql.operators | __rfloordiv__ | Implement the ``//`` operator in reverse.
See :meth:`.ColumnOperators.__floordiv__`.
| def __rfloordiv__(self, other: Any) -> ColumnOperators:
"""Implement the ``//`` operator in reverse.
See :meth:`.ColumnOperators.__floordiv__`.
"""
return self.reverse_operate(floordiv, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,011 | sqlalchemy.sql.operators | __rmod__ | Implement the ``%`` operator in reverse.
See :meth:`.ColumnOperators.__mod__`.
| def __rmod__(self, other: Any) -> ColumnOperators:
"""Implement the ``%`` operator in reverse.
See :meth:`.ColumnOperators.__mod__`.
"""
return self.reverse_operate(mod, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,012 | sqlalchemy.sql.operators | __rmul__ | Implement the ``*`` operator in reverse.
See :meth:`.ColumnOperators.__mul__`.
| def __rmul__(self, other: Any) -> ColumnOperators:
"""Implement the ``*`` operator in reverse.
See :meth:`.ColumnOperators.__mul__`.
"""
return self.reverse_operate(mul, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,013 | sqlalchemy.sql.operators | __rshift__ | implement the >> operator.
Not used by SQLAlchemy core, this is provided
for custom operator systems which want to use
>> as an extension point.
| def __rshift__(self, other: Any) -> ColumnOperators:
"""implement the >> operator.
Not used by SQLAlchemy core, this is provided
for custom operator systems which want to use
>> as an extension point.
"""
return self.operate(rshift, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,014 | sqlalchemy.sql.operators | __rsub__ | Implement the ``-`` operator in reverse.
See :meth:`.ColumnOperators.__sub__`.
| def __rsub__(self, other: Any) -> ColumnOperators:
"""Implement the ``-`` operator in reverse.
See :meth:`.ColumnOperators.__sub__`.
"""
return self.reverse_operate(sub, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,015 | sqlalchemy.sql.operators | __rtruediv__ | Implement the ``/`` operator in reverse.
See :meth:`.ColumnOperators.__truediv__`.
| def __rtruediv__(self, other: Any) -> ColumnOperators:
"""Implement the ``/`` operator in reverse.
See :meth:`.ColumnOperators.__truediv__`.
"""
return self.reverse_operate(truediv, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,016 | sqlalchemy.sql.operators | operate | Operate on an argument.
This is the lowest level of operation, raises
:class:`NotImplementedError` by default.
Overriding this on a subclass can allow common
behavior to be applied to all operations.
For example, overriding :class:`.ColumnOperators`
to apply ``func.lower()`` to the left and right
side::
class MyComparator(ColumnOperators):
def operate(self, op, other, **kwargs):
return op(func.lower(self), func.lower(other), **kwargs)
:param op: Operator callable.
:param \*other: the 'other' side of the operation. Will
be a single scalar for most operations.
:param \**kwargs: modifiers. These may be passed by special
operators such as :meth:`ColumnOperators.contains`.
| def operate(
self, op: OperatorType, *other: Any, **kwargs: Any
) -> Operators:
r"""Operate on an argument.
This is the lowest level of operation, raises
:class:`NotImplementedError` by default.
Overriding this on a subclass can allow common
behavior to be applied to all operations.
For example, overriding :class:`.ColumnOperators`
to apply ``func.lower()`` to the left and right
side::
class MyComparator(ColumnOperators):
def operate(self, op, other, **kwargs):
return op(func.lower(self), func.lower(other), **kwargs)
:param op: Operator callable.
:param \*other: the 'other' side of the operation. Will
be a single scalar for most operations.
:param \**kwargs: modifiers. These may be passed by special
operators such as :meth:`ColumnOperators.contains`.
"""
raise NotImplementedError(str(op))
| (self, op: sqlalchemy.sql.operators.OperatorType, *other: Any, **kwargs: Any) -> sqlalchemy.sql.operators.Operators |
16,017 | sqlalchemy.sql.elements | __setstate__ | null | def __setstate__(self, state):
self.__dict__.update(state)
| (self, state) |
16,019 | sqlalchemy.sql.operators | __sub__ | Implement the ``-`` operator.
In a column context, produces the clause ``a - b``.
| def __sub__(self, other: Any) -> ColumnOperators:
"""Implement the ``-`` operator.
In a column context, produces the clause ``a - b``.
"""
return self.operate(sub, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,020 | sqlalchemy.sql.operators | __truediv__ | Implement the ``/`` operator.
In a column context, produces the clause ``a / b``, and
considers the result type to be numeric.
.. versionchanged:: 2.0 The truediv operator against two integers
is now considered to return a numeric value. Behavior on specific
backends may vary.
| def __truediv__(self, other: Any) -> ColumnOperators:
"""Implement the ``/`` operator.
In a column context, produces the clause ``a / b``, and
considers the result type to be numeric.
.. versionchanged:: 2.0 The truediv operator against two integers
is now considered to return a numeric value. Behavior on specific
backends may vary.
"""
return self.operate(truediv, other)
| (self, other: Any) -> sqlalchemy.sql.operators.ColumnOperators |
16,021 | sqlalchemy.sql.base | _add_context_option | Add a context option to this statement.
These are callable functions that will
be given the CompileState object upon compilation.
A second argument cache_args is required, which will be combined with
the ``__code__`` identity of the function itself in order to produce a
cache key.
| # sql/base.py
# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
# mypy: allow-untyped-defs, allow-untyped-calls
"""Foundational utilities common to many sql modules.
"""
from __future__ import annotations
import collections
from enum import Enum
import itertools
from itertools import zip_longest
import operator
import re
from typing import Any
from typing import Callable
from typing import cast
from typing import Dict
from typing import FrozenSet
from typing import Generic
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import MutableMapping
from typing import NamedTuple
from typing import NoReturn
from typing import Optional
from typing import overload
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
from . import roles
from . import visitors
from .cache_key import HasCacheKey # noqa
from .cache_key import MemoizedHasCacheKey # noqa
from .traversals import HasCopyInternals # noqa
from .visitors import ClauseVisitor
from .visitors import ExtendedInternalTraversal
from .visitors import ExternallyTraversible
from .visitors import InternalTraversal
from .. import event
from .. import exc
from .. import util
from ..util import HasMemoized as HasMemoized
from ..util import hybridmethod
from ..util import typing as compat_typing
from ..util.typing import Protocol
from ..util.typing import Self
from ..util.typing import TypeGuard
if TYPE_CHECKING:
from . import coercions
from . import elements
from . import type_api
from ._orm_types import DMLStrategyArgument
from ._orm_types import SynchronizeSessionArgument
from ._typing import _CLE
from .elements import BindParameter
from .elements import ClauseList
from .elements import ColumnClause # noqa
from .elements import ColumnElement
from .elements import NamedColumn
from .elements import SQLCoreOperations
from .elements import TextClause
from .schema import Column
from .schema import DefaultGenerator
from .selectable import _JoinTargetElement
from .selectable import _SelectIterable
from .selectable import FromClause
from ..engine import Connection
from ..engine import CursorResult
from ..engine.interfaces import _CoreMultiExecuteParams
from ..engine.interfaces import _ExecuteOptions
from ..engine.interfaces import _ImmutableExecuteOptions
from ..engine.interfaces import CacheStats
from ..engine.interfaces import Compiled
from ..engine.interfaces import CompiledCacheType
from ..engine.interfaces import CoreExecuteOptionsParameter
from ..engine.interfaces import Dialect
from ..engine.interfaces import IsolationLevel
from ..engine.interfaces import SchemaTranslateMapType
from ..event import dispatcher
if not TYPE_CHECKING:
coercions = None # noqa
elements = None # noqa
type_api = None # noqa
class _NoArg(Enum):
NO_ARG = 0
def __repr__(self):
return f"_NoArg.{self.name}"
| (self, callable_: Callable[[sqlalchemy.sql.base.CompileState], NoneType], cache_args: Any) -> typing_extensions.Self |
16,022 | sqlalchemy.sql.annotation | _annotate | return a copy of this ClauseElement with annotations
updated by the given dictionary.
| def _annotate(self, values: _AnnotationDict) -> Self:
"""return a copy of this ClauseElement with annotations
updated by the given dictionary.
"""
return Annotated._as_annotated_instance(self, values) # type: ignore
| (self, values: Mapping[str, Any]) -> typing_extensions.Self |
16,023 | sqlalchemy.sql.elements | _anon_label | null | def _anon_label(
self, seed: Optional[str], add_hash: Optional[int] = None
) -> _anonymous_label:
while self._is_clone_of is not None:
self = self._is_clone_of
# as of 1.4 anonymous label for ColumnElement uses hash(), not id(),
# as the identifier, because a column and its annotated version are
# the same thing in a SQL statement
hash_value = hash(self)
if add_hash:
# this path is used for disambiguating anon labels that would
# otherwise be the same name for the same element repeated.
# an additional numeric value is factored in for each label.
# shift hash(self) (which is id(self), typically 8 byte integer)
# 16 bits leftward. fill extra add_hash on right
assert add_hash < (2 << 15)
assert seed
hash_value = (hash_value << 16) | add_hash
# extra underscore is added for labels with extra hash
# values, to isolate the "deduped anon" namespace from the
# regular namespace. eliminates chance of these
# manufactured hash values overlapping with regular ones for some
# undefined python interpreter
seed = seed + "_"
if isinstance(seed, _anonymous_label):
return _anonymous_label.safe_construct(
hash_value, "", enclosing_label=seed
)
return _anonymous_label.safe_construct(hash_value, seed or "anon")
| (self, seed: Optional[str], add_hash: Optional[int] = None) -> sqlalchemy.sql.elements._anonymous_label |
16,024 | sqlalchemy.sql.selectable | _anonymous_fromclause | null | def _anonymous_fromclause(
self, *, name: Optional[str] = None, flat: bool = False
) -> FromClause:
return self.alias(name=name)
| (self, *, name: Optional[str] = None, flat: bool = False) -> sqlalchemy.sql.selectable.FromClause |
16,025 | sqlalchemy.util.langhelpers | _assert_no_memoizations | null | def _assert_no_memoizations(self) -> None:
for elem in self._memoized_keys:
assert elem not in self.__dict__
| (self) -> NoneType |
16,026 | sqlalchemy.sql.functions | _bind_param | null | def _bind_param(
self,
operator: OperatorType,
obj: Any,
type_: Optional[TypeEngine[_T]] = None,
expanding: bool = False,
**kw: Any,
) -> BindParameter[_T]:
return BindParameter(
None,
obj,
_compared_to_operator=operator,
_compared_to_type=self.type,
unique=True,
type_=type_,
expanding=expanding,
**kw,
)
| (self, operator: 'OperatorType', obj: 'Any', type_: 'Optional[TypeEngine[_T]]' = None, expanding: 'bool' = False, **kw: 'Any') -> 'BindParameter[_T]' |
16,027 | sqlalchemy.sql.elements | _clone | Create a shallow copy of this ClauseElement.
This method may be used by a generative API. Its also used as
part of the "deep" copy afforded by a traversal that combines
the _copy_internals() method.
| def _clone(self, **kw: Any) -> Self:
"""Create a shallow copy of this ClauseElement.
This method may be used by a generative API. Its also used as
part of the "deep" copy afforded by a traversal that combines
the _copy_internals() method.
"""
skip = self._memoized_keys
c = self.__class__.__new__(self.__class__)
if skip:
# ensure this iteration remains atomic
c.__dict__ = {
k: v for k, v in self.__dict__.copy().items() if k not in skip
}
else:
c.__dict__ = self.__dict__.copy()
# this is a marker that helps to "equate" clauses to each other
# when a Select returns its list of FROM clauses. the cloning
# process leaves around a lot of remnants of the previous clause
# typically in the form of column expressions still attached to the
# old table.
cc = self._is_clone_of
c._is_clone_of = cc if cc is not None else self
return c
| (self, **kw: Any) -> typing_extensions.Self |
16,028 | sqlalchemy.sql.elements | _compare_name_for_result | Return True if the given column element compares to this one
when targeting within a result row. | def _compare_name_for_result(self, other: ColumnElement[Any]) -> bool:
"""Return True if the given column element compares to this one
when targeting within a result row."""
return (
hasattr(other, "name")
and hasattr(self, "name")
and other.name == self.name
)
| (self, other: sqlalchemy.sql.elements.ColumnElement[typing.Any]) -> bool |
16,029 | sqlalchemy.sql.elements | _compile_w_cache | null | def _compile_w_cache(
self,
dialect: Dialect,
*,
compiled_cache: Optional[CompiledCacheType],
column_keys: List[str],
for_executemany: bool = False,
schema_translate_map: Optional[SchemaTranslateMapType] = None,
**kw: Any,
) -> typing_Tuple[
Compiled, Optional[Sequence[BindParameter[Any]]], CacheStats
]:
elem_cache_key: Optional[CacheKey]
if compiled_cache is not None and dialect._supports_statement_cache:
elem_cache_key = self._generate_cache_key()
else:
elem_cache_key = None
if elem_cache_key is not None:
if TYPE_CHECKING:
assert compiled_cache is not None
cache_key, extracted_params = elem_cache_key
key = (
dialect,
cache_key,
tuple(column_keys),
bool(schema_translate_map),
for_executemany,
)
compiled_sql = compiled_cache.get(key)
if compiled_sql is None:
cache_hit = dialect.CACHE_MISS
compiled_sql = self._compiler(
dialect,
cache_key=elem_cache_key,
column_keys=column_keys,
for_executemany=for_executemany,
schema_translate_map=schema_translate_map,
**kw,
)
compiled_cache[key] = compiled_sql
else:
cache_hit = dialect.CACHE_HIT
else:
extracted_params = None
compiled_sql = self._compiler(
dialect,
cache_key=elem_cache_key,
column_keys=column_keys,
for_executemany=for_executemany,
schema_translate_map=schema_translate_map,
**kw,
)
if not dialect._supports_statement_cache:
cache_hit = dialect.NO_DIALECT_SUPPORT
elif compiled_cache is None:
cache_hit = dialect.CACHING_DISABLED
else:
cache_hit = dialect.NO_CACHE_KEY
return compiled_sql, extracted_params, cache_hit
| (self, dialect: 'Dialect', *, compiled_cache: 'Optional[CompiledCacheType]', column_keys: 'List[str]', for_executemany: 'bool' = False, schema_translate_map: 'Optional[SchemaTranslateMapType]' = None, **kw: 'Any') -> 'typing_Tuple[Compiled, Optional[Sequence[BindParameter[Any]]], CacheStats]' |
16,030 | sqlalchemy.sql.elements | _compiler | Return a compiler appropriate for this ClauseElement, given a
Dialect. | def _compiler(self, dialect: Dialect, **kw: Any) -> Compiled:
"""Return a compiler appropriate for this ClauseElement, given a
Dialect."""
if TYPE_CHECKING:
assert isinstance(self, ClauseElement)
return dialect.statement_compiler(dialect, self, **kw)
| (self, dialect: 'Dialect', **kw: 'Any') -> 'Compiled' |
16,031 | sqlalchemy.ext.compiler | <lambda> | null | def compiles(class_, *specs):
"""Register a function as a compiler for a
given :class:`_expression.ClauseElement` type."""
def decorate(fn):
# get an existing @compiles handler
existing = class_.__dict__.get("_compiler_dispatcher", None)
# get the original handler. All ClauseElement classes have one
# of these, but some TypeEngine classes will not.
existing_dispatch = getattr(class_, "_compiler_dispatch", None)
if not existing:
existing = _dispatcher()
if existing_dispatch:
def _wrap_existing_dispatch(element, compiler, **kw):
try:
return existing_dispatch(element, compiler, **kw)
except exc.UnsupportedCompilationError as uce:
raise exc.UnsupportedCompilationError(
compiler,
type(element),
message="%s construct has no default "
"compilation handler." % type(element),
) from uce
existing.specs["default"] = _wrap_existing_dispatch
# TODO: why is the lambda needed ?
setattr(
class_,
"_compiler_dispatch",
lambda *arg, **kw: existing(*arg, **kw),
)
setattr(class_, "_compiler_dispatcher", existing)
if specs:
for s in specs:
existing.specs[s] = fn
else:
existing.specs["default"] = fn
return fn
return decorate
| (*arg, **kw) |
16,032 | sqlalchemy.sql.traversals | _copy_internals | Reassign internal elements to be clones of themselves.
Called during a copy-and-traverse operation on newly
shallow-copied elements to create a deep copy.
The given clone function should be used, which may be applying
additional transformations to the element (i.e. replacement
traversal, cloned traversal, annotations).
| def _copy_internals(
self, *, omit_attrs: Iterable[str] = (), **kw: Any
) -> None:
"""Reassign internal elements to be clones of themselves.
Called during a copy-and-traverse operation on newly
shallow-copied elements to create a deep copy.
The given clone function should be used, which may be applying
additional transformations to the element (i.e. replacement
traversal, cloned traversal, annotations).
"""
try:
traverse_internals = self._traverse_internals
except AttributeError:
# user-defined classes may not have a _traverse_internals
return
for attrname, obj, meth in _copy_internals.run_generated_dispatch(
self, traverse_internals, "_generated_copy_internals_traversal"
):
if attrname in omit_attrs:
continue
if obj is not None:
result = meth(attrname, self, obj, **kw)
if result is not None:
setattr(self, attrname, result)
| (self, *, omit_attrs: Iterable[str] = (), **kw: Any) -> NoneType |
16,033 | sqlalchemy.sql.elements | _de_clone | null | def _de_clone(self):
while self._is_clone_of is not None:
self = self._is_clone_of
return self
| (self) |
16,034 | sqlalchemy.sql.annotation | _deannotate | return a copy of this :class:`_expression.ClauseElement`
with annotations
removed.
:param values: optional tuple of individual values
to remove.
| def _deannotate(
self,
values: Optional[Sequence[str]] = None,
clone: bool = False,
) -> SupportsAnnotations:
"""return a copy of this :class:`_expression.ClauseElement`
with annotations
removed.
:param values: optional tuple of individual values
to remove.
"""
if clone:
s = self._clone()
return s
else:
return self
| (self, values: Optional[Sequence[str]] = None, clone: bool = False) -> sqlalchemy.sql.annotation.SupportsAnnotations |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.