Загрузить файлы в «venv/Lib/site-packages/sqlalchemy/cyextension»

This commit is contained in:
2026-07-02 20:19:25 +00:00
parent ec93ff62bb
commit a5fa3f7a6f
5 changed files with 303 additions and 0 deletions

View File

@@ -0,0 +1,133 @@
# cyextension/immutabledict.pyx
# 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
from cpython.dict cimport PyDict_New, PyDict_Update, PyDict_Size
def _readonly_fn(obj):
raise TypeError(
"%s object is immutable and/or readonly" % obj.__class__.__name__)
def _immutable_fn(obj):
raise TypeError(
"%s object is immutable" % obj.__class__.__name__)
class ReadOnlyContainer:
__slots__ = ()
def _readonly(self, *a,**kw):
_readonly_fn(self)
__delitem__ = __setitem__ = __setattr__ = _readonly
class ImmutableDictBase(dict):
def _immutable(self, *a,**kw):
_immutable_fn(self)
@classmethod
def __class_getitem__(cls, key):
return cls
__delitem__ = __setitem__ = __setattr__ = _immutable
clear = pop = popitem = setdefault = update = _immutable
cdef class immutabledict(dict):
def __repr__(self):
return f"immutabledict({dict.__repr__(self)})"
@classmethod
def __class_getitem__(cls, key):
return cls
def union(self, *args, **kw):
cdef dict to_merge = None
cdef immutabledict result
cdef Py_ssize_t args_len = len(args)
if args_len > 1:
raise TypeError(
f'union expected at most 1 argument, got {args_len}'
)
if args_len == 1:
attribute = args[0]
if isinstance(attribute, dict):
to_merge = <dict> attribute
if to_merge is None:
to_merge = dict(*args, **kw)
if PyDict_Size(to_merge) == 0:
return self
# new + update is faster than immutabledict(self)
result = immutabledict()
PyDict_Update(result, self)
PyDict_Update(result, to_merge)
return result
def merge_with(self, *other):
cdef immutabledict result = None
cdef object d
cdef bint update = False
if not other:
return self
for d in other:
if d:
if update == False:
update = True
# new + update is faster than immutabledict(self)
result = immutabledict()
PyDict_Update(result, self)
PyDict_Update(
result, <dict>(d if isinstance(d, dict) else dict(d))
)
return self if update == False else result
def copy(self):
return self
def __reduce__(self):
return immutabledict, (dict(self), )
def __delitem__(self, k):
_immutable_fn(self)
def __setitem__(self, k, v):
_immutable_fn(self)
def __setattr__(self, k, v):
_immutable_fn(self)
def clear(self, *args, **kw):
_immutable_fn(self)
def pop(self, *args, **kw):
_immutable_fn(self)
def popitem(self, *args, **kw):
_immutable_fn(self)
def setdefault(self, *args, **kw):
_immutable_fn(self)
def update(self, *args, **kw):
_immutable_fn(self)
# PEP 584
def __ior__(self, other):
_immutable_fn(self)
def __or__(self, other):
return immutabledict(dict.__or__(self, other))
def __ror__(self, other):
# NOTE: this is used only in cython 3.x;
# version 0.x will call __or__ with args inversed
return immutabledict(dict.__ror__(self, other))

View File

@@ -0,0 +1,68 @@
# cyextension/processors.pyx
# 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
import datetime
from datetime import datetime as datetime_cls
from datetime import time as time_cls
from datetime import date as date_cls
import re
from cpython.object cimport PyObject_Str
from cpython.unicode cimport PyUnicode_AsASCIIString, PyUnicode_Check, PyUnicode_Decode
from libc.stdio cimport sscanf
def int_to_boolean(value):
if value is None:
return None
return True if value else False
def to_str(value):
return PyObject_Str(value) if value is not None else None
def to_float(value):
return float(value) if value is not None else None
cdef inline bytes to_bytes(object value, str type_name):
try:
return PyUnicode_AsASCIIString(value)
except Exception as e:
raise ValueError(
f"Couldn't parse {type_name} string '{value!r}' "
"- value is not a string."
) from e
def str_to_datetime(value):
if value is not None:
value = datetime_cls.fromisoformat(value)
return value
def str_to_time(value):
if value is not None:
value = time_cls.fromisoformat(value)
return value
def str_to_date(value):
if value is not None:
value = date_cls.fromisoformat(value)
return value
cdef class DecimalResultProcessor:
cdef object type_
cdef str format_
def __cinit__(self, type_, format_):
self.type_ = type_
self.format_ = format_
def process(self, object value):
if value is None:
return None
else:
return self.type_(self.format_ % value)

View File

@@ -0,0 +1,102 @@
# cyextension/resultproxy.pyx
# 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
import operator
cdef class BaseRow:
cdef readonly object _parent
cdef readonly dict _key_to_index
cdef readonly tuple _data
def __init__(self, object parent, object processors, dict key_to_index, object data):
"""Row objects are constructed by CursorResult objects."""
self._parent = parent
self._key_to_index = key_to_index
if processors:
self._data = _apply_processors(processors, data)
else:
self._data = tuple(data)
def __reduce__(self):
return (
rowproxy_reconstructor,
(self.__class__, self.__getstate__()),
)
def __getstate__(self):
return {"_parent": self._parent, "_data": self._data}
def __setstate__(self, dict state):
parent = state["_parent"]
self._parent = parent
self._data = state["_data"]
self._key_to_index = parent._key_to_index
def _values_impl(self):
return list(self)
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
def __hash__(self):
return hash(self._data)
def __getitem__(self, index):
return self._data[index]
def _get_by_key_impl_mapping(self, key):
return self._get_by_key_impl(key, 0)
cdef _get_by_key_impl(self, object key, int attr_err):
index = self._key_to_index.get(key)
if index is not None:
return self._data[<int>index]
self._parent._key_not_found(key, attr_err != 0)
def __getattr__(self, name):
return self._get_by_key_impl(name, 1)
def _to_tuple_instance(self):
return self._data
cdef tuple _apply_processors(proc, data):
res = []
for i in range(len(proc)):
p = proc[i]
if p is None:
res.append(data[i])
else:
res.append(p(data[i]))
return tuple(res)
def rowproxy_reconstructor(cls, state):
obj = cls.__new__(cls)
obj.__setstate__(state)
return obj
cdef int is_contiguous(tuple indexes):
cdef int i
for i in range(1, len(indexes)):
if indexes[i-1] != indexes[i] -1:
return 0
return 1
def tuplegetter(*indexes):
if len(indexes) == 1 or is_contiguous(indexes) != 0:
# slice form is faster but returns a list if input is list
return operator.itemgetter(slice(indexes[0], indexes[-1] + 1))
else:
return operator.itemgetter(*indexes)