buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class TestMerge: # GH 24212 # pd.merge gets [0, 1, 2, -1, -1, -1] as left_indexer, ensure that # -1 is interpreted as a missing value instead of the last element df1 = pd.DataFrame({"a": [1, 2, 3], "key": [0, 2, 2]}, index=index) df2 = pd.DataFrame({"b": [1, 2, 3, 4, 5]}) ...
class TestMerge: # GH 24212 # pd.merge gets [0, 1, 2, -1, -1, -1] as left_indexer, ensure that # -1 is interpreted as a missing value instead of the last element df1 = pd.DataFrame({"a": [0, 1, 2], "key": [0, 1, 2]}, index=index) df2 = pd.DataFrame({"b": [0, 1, 2, 3, 4, 5]}) ...
class TestMerge: result = left.merge(right, left_on="key", right_index=True, how="right") tm.assert_frame_equal(result, expected) def test_merge_take_missing_values_from_index_of_other_dtype(self): # GH 24212 left = pd.DataFrame(
class TestMerge: result = left.merge(right, left_on="key", right_index=True, how="right") tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("how", ["left", "right"]) def test_merge_preserves_row_order(self, how): # GH 27453 left_df = pd.DataFrame({"animal": ["dog"...
def get_grouper( return False try: return gpr is obj[gpr.name] except (KeyError, IndexError): return False for i, (gpr, level) in enumerate(zip(keys, levels)):
def get_grouper( return False try: return gpr is obj[gpr.name] except (KeyError, IndexError, ValueError): # TODO: ValueError: Given date string not likely a datetime. # should be KeyError? return False for i, (gpr, level) in enumerate(zip(...
import numpy as np import pytest from pandas import DataFrame, Index, Series import pandas._testing as tm
import numpy as np import pytest from pandas import DataFrame, Index, PeriodIndex, Series import pandas._testing as tm
def test_size_groupby_all_null(): result = df.groupby("A").size() expected = Series(dtype="int64", index=Index([], name="A")) tm.assert_series_equal(result, expected)
def test_size_groupby_all_null(): result = df.groupby("A").size() expected = Series(dtype="int64", index=Index([], name="A")) tm.assert_series_equal(result, expected) def test_size_period_index(): # https://github.com/pandas-dev/pandas/issues/34010 ser = Series([1], index=PeriodIndex(["2000"], nam...
DEFAULT_LOG_PATH = get_config(p, DEFAULTS, 'log_path', 'ANSIB DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_FORCE_HANDLERS', False, boolean=True) DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".ori...
DEFAULT_LOG_PATH = get_config(p, DEFAULTS, 'log_path', 'ANSIB DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_FORCE_HANDLERS', False, boolean=True) DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".ori...
class Templar: loader=FileSystemLoader(self._basedir), ) self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string)) self.block_start = self.environment.block_start_string
class Templar: loader=FileSystemLoader(self._basedir), ) # the current rendering context under which the templar class is working self.cur_context = None self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_e...
class Templar: if instance is not None: wantlist = kwargs.pop('wantlist', False) from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False)
class Templar: if instance is not None: wantlist = kwargs.pop('wantlist', False) allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS) from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(term...
class Templar: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e)) ran = None if ran: from ansible.vars.unsafe_proxy import UnsafeProxy, wrap_var ...
class Templar: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e)) ran = None if ran and not allow_unsafe: from ansible.vars.unsafe_proxy import UnsafeProxy,...
class Templar: else: ran = wrap_var(ran) return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
class Templar: else: ran = wrap_var(ran) if self.cur_context: self.cur_context.unsafe = True return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
class Templar: jvars = AnsibleJ2Vars(self, t.globals) new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try:
class Templar: jvars = AnsibleJ2Vars(self, t.globals) self.cur_context = new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try:
class HTTPBearer(HTTPBase): else: return None if scheme.lower() != "bearer": raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Invalid authentication credentials", ) return HTTPAuthorizationCredentials(scheme=...
class HTTPBearer(HTTPBase): else: return None if scheme.lower() != "bearer": if self.auto_error: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Invalid authentication credentials", ) ...
def test_security_http_bearer_no_credentials(): def test_security_http_bearer_incorrect_scheme_credentials(): response = client.get("/users/me", headers={"Authorization": "Basic notreally"}) assert response.status_code == 403 assert response.json() == {"detail": "Invalid authentication credentials"}
def test_security_http_bearer_no_credentials(): def test_security_http_bearer_incorrect_scheme_credentials(): response = client.get("/users/me", headers={"Authorization": "Basic notreally"}) assert response.status_code == 200 assert response.json() == {"msg": "Create an account first"}
def should_series_dispatch(left, right, op): # numpy integer dtypes as timedelta64 dtypes in this scenario return True if is_datetime64_dtype(ldtype) and is_object_dtype(rdtype): # in particular case where right is an array of DateOffsets return True return False
def should_series_dispatch(left, right, op): # numpy integer dtypes as timedelta64 dtypes in this scenario return True if (is_datetime64_dtype(ldtype) and is_object_dtype(rdtype)) or ( is_datetime64_dtype(rdtype) and is_object_dtype(ldtype) ): # in particular case where one is a...
def id_func(x): # ------------------------------------------------------------------ @pytest.fixture(params=[1, np.array(1, dtype=np.int64)])
def id_func(x): # ------------------------------------------------------------------ @pytest.fixture( params=[ ("foo", None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ] ) def names(request): """ A 3-tuple of names, the first two for operands, the l...
class TestDatetime64DateOffsetArithmetic: tm.assert_equal(result, exp) tm.assert_equal(result2, exp) # TODO: __sub__, __rsub__ def test_dt64arr_add_mixed_offset_array(self, box_with_array): # GH#10699 # array of offsets s = DatetimeIndex([Timestamp("2000-1-1"), Timestamp...
class TestDatetime64DateOffsetArithmetic: tm.assert_equal(result, exp) tm.assert_equal(result2, exp) @pytest.mark.parametrize( "other", [ np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]), np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()])...
class TestTimestampSeriesArithmetic: # TODO: parametrize over box @pytest.mark.parametrize("op", ["__add__", "__radd__", "__sub__", "__rsub__"]) @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"]) def test_dt64_series_add_intlike(self, tz, op): # GH#19123 dti = pd.DatetimeIndex(["2016-...
class TestTimestampSeriesArithmetic: # TODO: parametrize over box @pytest.mark.parametrize("op", ["__add__", "__radd__", "__sub__", "__rsub__"]) def test_dt64_series_add_intlike(self, tz_naive_fixture, op): # GH#19123 tz = tz_naive_fixture dti = pd.DatetimeIndex(["2016-01-02", "2016...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result, exp) assert result.freq == exp.freq @pytest.mark.parametrize( "names", [("foo", None, None), ("baz", "bar", None), ("bar", "bar", "bar")] ) @pytest.mark.parametrize("tz", [None, "America/Chicago"]) def test...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result, exp) assert result.freq == exp.freq def test_dti_add_series(self, tz_naive_fixture, names): # GH#13905 tz = tz_naive_fixture index = DatetimeIndex( ["2016-06-28 05:30", "2016-06-28 05:31"], ...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result4, expected) @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub]) @pytest.mark.parametrize( "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")] ) def test_dti_addsub_offset_arra...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result4, expected) @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub]) def test_dti_addsub_offset_arraylike( self, tz_naive_fixture, names, op, index_or_series ):
class TestTimedeltaArraylikeAddSubOps: result = tdarr - tdi tm.assert_equal(result, expected) @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ], ) def test_t...
class TestTimedeltaArraylikeAddSubOps: result = tdarr - tdi tm.assert_equal(result, expected) def test_td64arr_add_sub_tdi(self, box, names): # GH#17250 make sure result dtype is correct # GH#19043 make sure names are propagated correctly if box is pd.DataFrame and names[1] ...
class TestTimedeltaArraylikeAddSubOps: # ------------------------------------------------------------------ # __add__/__sub__ with DateOffsets and arrays of DateOffsets @pytest.mark.parametrize( "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")] ) def test_td64arr_ad...
class TestTimedeltaArraylikeAddSubOps: # ------------------------------------------------------------------ # __add__/__sub__ with DateOffsets and arrays of DateOffsets def test_td64arr_add_offset_index(self, names, box): # GH#18849, GH#19744 if box is pd.DataFrame and names[1] != names[0]:...
class TestTimedeltaArraylikeMulDivOps: with pytest.raises(TypeError, match=pattern): vector.astype(object) / tdser @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ...
class TestTimedeltaArraylikeMulDivOps: with pytest.raises(TypeError, match=pattern): vector.astype(object) / tdser def test_td64arr_mul_int_series(self, box_df_fail, names): # GH#19042 test for correct name attachment box = box_df_fail # broadcasts along wrong axis, but doesn't...
class TestTimedeltaArraylikeMulDivOps: tm.assert_equal(result, expected) # TODO: Should we be parametrizing over types for `ser` too? @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701...
class TestTimedeltaArraylikeMulDivOps: tm.assert_equal(result, expected) # TODO: Should we be parametrizing over types for `ser` too? def test_float_series_rdiv_td64arr(self, box_with_array, names): # GH#19042 test for correct name attachment # TODO: the direct operation TimedeltaIndex ...
class WebSocketTest(WebSocketBaseTestCase): response = self.fetch('/echo') self.assertEqual(response.code, 400) def test_bad_websocket_version(self): response = self.fetch('/echo', headers={'Connection': 'Upgrade',
class WebSocketTest(WebSocketBaseTestCase): response = self.fetch('/echo') self.assertEqual(response.code, 400) def test_missing_websocket_key(self): response = self.fetch('/echo', headers={'Connection': 'Upgrade', 'Upgrad...
class WebSocketProtocol13(WebSocketProtocol): def accept_connection(self): try: self._handle_websocket_headers() self._accept_connection() except ValueError: gen_log.debug("Malformed WebSocket request received",
class WebSocketProtocol13(WebSocketProtocol): def accept_connection(self): try: self._handle_websocket_headers() except ValueError: self.handler.set_status(400) log_msg = "Missing/Invalid WebSocket headers" self.handler.finish(log_msg) gen_...
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) return self._save(name, content) # These methods are part of the public API, with default implementations.
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) name = self._save(name, content) # Ensure that the name returned from the storage system is still valid. validate_file_name(name, allow_relative_path=True) return...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise SuspiciousFileOperation("Detected path traversal ...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ name = str(name).replace('\\', '/') dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise Suspi...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(filename) if '..' in pathlib.PurePath(dirnam...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ filename = str(filename).replace('\\', '/') # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(...
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Store filenames with forward slashes, even on Windows. return str(name).replace('\\', '/')
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Ensure the saved path is always relative to the storage root. name = os.path.relpath(full_path, self.location) # Store filenames with forward slashe...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): file_name = '/tmp/../path' s = FileSystemStorage() msg = "Detected path traversal attempt in '/tmp/..'" with self.assertRaisesMessa...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): candidates = [ ('tmp/../path', 'tmp/..'), ('tmp\\..\\path', 'tmp/..'), ('/tmp/../path', '/tmp/..'), ('\\tmp...
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') @unittest.skipUnless(symlinks_supported(), 'Must be able to symlink to run this test.') def test_file_save_broken_symlink(self): """A new path is created on save when a broken symlink is supplied."""
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') def test_file_save_abs_path(self): test_name = 'path/to/test.file' f = ContentFile('file saved with path') f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f) self.assertEqual...
The `pillar_roots` wheel module is used to manage files under the pillar roots directories on the master server. """ # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os # Import salt libs import salt.utils.files import salt.utils.path # Import 3rd-party libs from ...
The `pillar_roots` wheel module is used to manage files under the pillar roots directories on the master server. """ from __future__ import absolute_import, print_function, unicode_literals import os import salt.utils.files import salt.utils.path import salt.utils.verify from salt.ext import six
def write(data, path, saltenv="base", index=0): return ( "The path passed in {0} is not relative to the environment " "{1}" ).format(path, saltenv) dest = os.path.join(__opts__["pillar_roots"][saltenv][index], path) dest_dir = os.path.dirname(dest) if not os.path.isdir(dest_dir):
def write(data, path, saltenv="base", index=0): return ( "The path passed in {0} is not relative to the environment " "{1}" ).format(path, saltenv) roots_dir = __opts__["pillar_roots"][saltenv][index] dest = os.path.join(roots_dir, path) if not salt.utils.verify.clean_path(roots_...
def __virtual__(): return __virtualname__ def _check_cb(cb_): ''' If the callback is None or is not callable, return a lambda that returns
def __virtual__(): return __virtualname__ def _log_cmd(cmd): if not isinstance(cmd, list): return cmd.split()[0].strip() return cmd[0].strip() def _check_cb(cb_): ''' If the callback is None or is not callable, return a lambda that returns
def _run(cmd, 'Setting value to an empty string', bad_env_key) env[bad_env_key] = '' def _get_stripped(cmd): # Return stripped command string copies to improve logging. if isinstance(cmd, list): return [x.strip() if isinstance(x, six.string_types) else x for x ...
def _run(cmd, 'Setting value to an empty string', bad_env_key) env[bad_env_key] = '' if output_loglevel is not None: # Always log the shell commands at INFO unless quiet logging is # requested. The command output is what will be controlled by the # 'loglevel' param...
def _run(cmd, if output_loglevel != 'quiet': log.error( 'Failed to decode stdout from command %s, non-decodable ' 'characters have been replaced', cmd ) try:
def _run(cmd, if output_loglevel != 'quiet': log.error( 'Failed to decode stdout from command %s, non-decodable ' 'characters have been replaced', _log_cmd(cmd) ) try:
def _run(cmd, if output_loglevel != 'quiet': log.error( 'Failed to decode stderr from command %s, non-decodable ' 'characters have been replaced', cmd ) if rstrip:
def _run(cmd, if output_loglevel != 'quiet': log.error( 'Failed to decode stderr from command %s, non-decodable ' 'characters have been replaced', _log_cmd(cmd) ) if rstrip:
def _run(cmd, output_loglevel = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( cmd, ret['retcode'] ) )
def _run(cmd, output_loglevel = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( _log_cmd(cmd), ret['retcode'] ) )
def run(cmd, lvl = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( cmd, ret['retcode'] ) )
def run(cmd, lvl = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( _log_cmd(cmd), ret['retcode'] ) )
class CMDMODTestCase(TestCase, LoaderModuleMockMixin): cmdmod.run_chroot('/mnt', 'cmd', binds=['/var']) self.assertEqual(mock_mount.call_count, 4) self.assertEqual(mock_umount.call_count, 4)
class CMDMODTestCase(TestCase, LoaderModuleMockMixin): cmdmod.run_chroot('/mnt', 'cmd', binds=['/var']) self.assertEqual(mock_mount.call_count, 4) self.assertEqual(mock_umount.call_count, 4) def test_cve_2021_25284(self): proc = MagicMock( return_...
def __dict__(self): with self.assertRaises(ZeroDivisionError): WorseStruct().__setstate__({}, b'foo') ################################################################ if __name__ == '__main__':
def __dict__(self): with self.assertRaises(ZeroDivisionError): WorseStruct().__setstate__({}, b'foo') def test_parameter_repr(self): from ctypes import ( c_bool, c_char, c_wchar, c_byte, c_ubyte, c_short, ...
class tqdm(Comparable): if disable is None and hasattr(file, "isatty") and not file.isatty(): disable = True if disable: self.iterable = iterable self.disable = disable self.pos = self._get_free_pos(self) self._instances.remove(self) ...
class tqdm(Comparable): if disable is None and hasattr(file, "isatty") and not file.isatty(): disable = True if total is None and iterable is not None: try: total = len(iterable) except (TypeError, AttributeError): total = None ...
class tqdm(Comparable): else TqdmKeyError("Unknown argument(s): " + str(kwargs))) # Preprocess the arguments if total is None and iterable is not None: try: total = len(iterable) except (TypeError, AttributeError): total = None ...
class tqdm(Comparable): else TqdmKeyError("Unknown argument(s): " + str(kwargs))) # Preprocess the arguments if ((ncols is None) and (file in (sys.stderr, sys.stdout))) or \ dynamic_ncols: # pragma: no cover if dynamic_ncols:
def test_threading(): # TODO: test interleaved output #445 @with_setup(pretest, posttest) def test_autonotebook(): """Test autonotebook fallback"""
def test_threading(): # TODO: test interleaved output #445 @with_setup(pretest, posttest) def test_bool(): """Test boolean cast""" def internal(our_file, disable): with tqdm(total=10, file=our_file, disable=disable) as t: assert t with tqdm(total=0, file=our_file, disable=disab...
from .engine import create_engine # noqa nosort from .engine import engine_from_config # noqa nosort __version__ = '1.3.0b3' def __go(lcls):
from .engine import create_engine # noqa nosort from .engine import engine_from_config # noqa nosort __version__ = "1.3.0b3" def __go(lcls):
except ImportError: _python_UUID = None AUTOCOMMIT_REGEXP = re.compile( r"\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|" "IMPORT FOREIGN SCHEMA|REFRESH MATERIALIZED VIEW|TRUNCATE)",
except ImportError: _python_UUID = None IDX_USING = re.compile(r"^(?:btree|hash|gist|gin|[\w_]+)$", re.I) AUTOCOMMIT_REGEXP = re.compile( r"\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|" "IMPORT FOREIGN SCHEMA|REFRESH MATERIALIZED VIEW|TRUNCATE)",
class PGDDLCompiler(compiler.DDLCompiler): using = index.dialect_options["postgresql"]["using"] if using: text += "USING %s " % preparer.quote(using) ops = index.dialect_options["postgresql"]["ops"] text += "(%s)" % (
class PGDDLCompiler(compiler.DDLCompiler): using = index.dialect_options["postgresql"]["using"] if using: text += ( "USING %s " % self.preparer.validate_sql_phrase(using, IDX_USING).lower() ) ops = index.dialect_options["postgresql"]["ops...
class PGDDLCompiler(compiler.DDLCompiler): "%s WITH %s" % (self.sql_compiler.process(expr, **kw), op) ) text += "EXCLUDE USING %s (%s)" % ( constraint.using, ", ".join(elements), ) if constraint.where is not None:
class PGDDLCompiler(compiler.DDLCompiler): "%s WITH %s" % (self.sql_compiler.process(expr, **kw), op) ) text += "EXCLUDE USING %s (%s)" % ( self.preparer.validate_sql_phrase( constraint.using, IDX_USING ).lower(), ", ".join(elements...
class ExcludeConstraint(ColumnCollectionConstraint): where = None def __init__(self, *elements, **kw): r""" Create an :class:`.ExcludeConstraint` object.
class ExcludeConstraint(ColumnCollectionConstraint): where = None @elements._document_text_coercion( "where", ":class:`.ExcludeConstraint`", ":paramref:`.ExcludeConstraint.where`", ) def __init__(self, *elements, **kw): r""" Create an :class:`.ExcludeConstraint`...
class ExcludeConstraint(ColumnCollectionConstraint): ) :param \*elements: A sequence of two tuples of the form ``(column, operator)`` where "column" is a SQL expression element or a raw SQL string, most typically a :class:`.Column` object, and "operator" is a...
class ExcludeConstraint(ColumnCollectionConstraint): ) :param \*elements: A sequence of two tuples of the form ``(column, operator)`` where "column" is a SQL expression element or a raw SQL string, most typically a :class:`.Column` object, and "operator" is a string ...
class ExcludeConstraint(ColumnCollectionConstraint): If set, emit WHERE <predicate> when issuing DDL for this constraint. .. note:: A plain string passed here is interpreted as an arbitrary SQL expression; when passing a plain string, any necessary quoting...
class ExcludeConstraint(ColumnCollectionConstraint): If set, emit WHERE <predicate> when issuing DDL for this constraint. """ columns = [] render_exprs = []
class ExcludeConstraint(ColumnCollectionConstraint): # backwards compat self.operators[name] = operator expr = expression._literal_as_text(expr) render_exprs.append((expr, name, operator)) self._render_exprs = render_exprs ColumnCollectionConstr...
class ExcludeConstraint(ColumnCollectionConstraint): # backwards compat self.operators[name] = operator expr = expression._literal_as_column(expr) render_exprs.append((expr, name, operator)) self._render_exprs = render_exprs ColumnCollectionCon...
class ExcludeConstraint(ColumnCollectionConstraint): self.using = kw.get("using", "gist") where = kw.get("where") if where is not None: self.where = expression._literal_as_text(where) def copy(self, **kw): elements = [(col, self.operators[col]) for col in self.columns.ke...
class ExcludeConstraint(ColumnCollectionConstraint): self.using = kw.get("using", "gist") where = kw.get("where") if where is not None: self.where = expression._literal_as_text( where, allow_coercion_to_text=True ) def copy(self, **kw): elemen...
class Session(_SessionClassMethods): in order to execute the statement. """ clause = expression._literal_as_text(clause) if bind is None: bind = self.get_bind(mapper, clause=clause, **kw)
class Session(_SessionClassMethods): in order to execute the statement. """ clause = expression._literal_as_text( clause, allow_coercion_to_text=True ) if bind is None: bind = self.get_bind(mapper, clause=clause, **kw)
RESERVED_WORDS = set( ) LEGAL_CHARACTERS = re.compile(r"^[A-Z0-9_$]+$", re.I) ILLEGAL_INITIAL_CHARACTERS = {str(x) for x in range(0, 10)}.union(["$"]) BIND_PARAMS = re.compile(r"(?<![:\w\$\x5c]):([\w\$]+)(?![:\w\$])", re.UNICODE) BIND_PARAMS_ESC = re.compile(r"\x5c(:[\w\$]*)(?![:\w\$])", re.UNICODE)
RESERVED_WORDS = set( ) LEGAL_CHARACTERS = re.compile(r"^[A-Z0-9_$]+$", re.I) LEGAL_CHARACTERS_PLUS_SPACE = re.compile(r"^[A-Z0-9_ $]+$", re.I) ILLEGAL_INITIAL_CHARACTERS = {str(x) for x in range(0, 10)}.union(["$"]) FK_ON_DELETE = re.compile( r"^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$", re.I ) FK_ON...
class SQLCompiler(Compiled): else: col = with_cols[element.element] except KeyError: # treat it like text() util.warn_limited( "Can't resolve label reference %r; converting to text()", util.ellipses_string(element.element), ...
class SQLCompiler(Compiled): else: col = with_cols[element.element] except KeyError: elements._no_text_coercion( element.element, exc.CompileError, "Can't resolve label reference for ORDER BY / GROUP BY.", ) ...
class SQLCompiler(Compiled): if func._has_args: name += "%(expr)s" else: name = func.name + "%(expr)s" return ".".join(list(func.packagenames) + [name]) % { "expr": self.function_argspec(func, **kwargs) } def vi...
class SQLCompiler(Compiled): if func._has_args: name += "%(expr)s" else: name = func.name name = ( self.preparer.quote(name) if self.preparer._requires_quotes_illegal_chars(name) e...
class DDLCompiler(Compiled): def define_constraint_cascades(self, constraint): text = "" if constraint.ondelete is not None: text += " ON DELETE %s" % constraint.ondelete if constraint.onupdate is not None: text += " ON UPDATE %s" % constraint.onupdate return ...
class DDLCompiler(Compiled): def define_constraint_cascades(self, constraint): text = "" if constraint.ondelete is not None: text += " ON DELETE %s" % self.preparer.validate_sql_phrase( constraint.ondelete, FK_ON_DELETE ) if constraint.onupdate is not ...
class DDLCompiler(Compiled): else: text += " NOT DEFERRABLE" if constraint.initially is not None: text += " INITIALLY %s" % constraint.initially return text def define_constraint_match(self, constraint):
class DDLCompiler(Compiled): else: text += " NOT DEFERRABLE" if constraint.initially is not None: text += " INITIALLY %s" % self.preparer.validate_sql_phrase( constraint.initially, FK_INITIALLY ) return text def define_constraint_m...
class IdentifierPreparer(object): return value.replace(self.escape_to_quote, self.escape_quote) def quote_identifier(self, value): """Quote an identifier.
class IdentifierPreparer(object): return value.replace(self.escape_to_quote, self.escape_quote) def validate_sql_phrase(self, element, reg): """keyword sequence filter. a filter for elements that are intended to represent keyword sequences, such as "INITIALLY", "INTIALLY DEFERRED"...
class IdentifierPreparer(object): or (lc_value != value) ) def quote_schema(self, schema, force=None): """Conditionally quote a schema name.
class IdentifierPreparer(object): or (lc_value != value) ) def _requires_quotes_illegal_chars(self, value): """Return True if the given identifier requires quoting, but not taking case convention into account.""" return not self.legal_characters.match(util.text_type(valu...
def _clone(element, **kw): return element._clone() def collate(expression, collation): """Return the clause ``expression COLLATE collation``.
def _clone(element, **kw): return element._clone() def _document_text_coercion(paramname, meth_rst, param_rst): return util.add_parameter_text( paramname, ( ".. warning:: " "The %s argument to %s can be passed as a Python string argument, " "which will be tr...
class TextClause(Executable, ClauseElement): "refer to the :meth:`.TextClause.columns` method.", ), ) def _create_text( self, text, bind=None, bindparams=None, typemap=None, autocommit=None ):
class TextClause(Executable, ClauseElement): "refer to the :meth:`.TextClause.columns` method.", ), ) @_document_text_coercion("text", ":func:`.text`", ":paramref:`.text.text`") def _create_text( self, text, bind=None, bindparams=None, typemap=None, autocommit=None ):
def _literal_and_labels_as_label_reference(element): def _expression_literal_as_text(element): return _literal_as_text(element, warn=True) def _literal_as_text(element, warn=False): if isinstance(element, Visitable): return element elif hasattr(element, "__clause_element__"): return elem...
def _literal_and_labels_as_label_reference(element): def _expression_literal_as_text(element): return _literal_as_text(element) def _literal_as(element, text_fallback): if isinstance(element, Visitable): return element elif hasattr(element, "__clause_element__"): return element.__clause_...
def _interpret_as_column_or_from(element): elif isinstance(element, (numbers.Number)): return ColumnClause(str(element), is_literal=True) else: element = str(element) # give into temptation, as this fact we are guessing about # is not one we've previously ever needed our users te...
def _interpret_as_column_or_from(element): elif isinstance(element, (numbers.Number)): return ColumnClause(str(element), is_literal=True) else: _no_column_coercion(element) return ColumnClause(element, is_literal=guess_is_literal)
from .elements import _expression_literal_as_text # noqa from .elements import _is_column # noqa from .elements import _labeled # noqa from .elements import _literal_as_binds # noqa from .elements import _literal_as_label_reference # noqa from .elements import _literal_as_text # noqa from .elements import _only_c...
from .elements import _expression_literal_as_text # noqa from .elements import _is_column # noqa from .elements import _labeled # noqa from .elements import _literal_as_binds # noqa from .elements import _literal_as_column # noqa from .elements import _literal_as_label_reference # noqa from .elements import _lite...
from .base import ColumnCollection from .base import DialectKWArgs from .base import SchemaEventTarget from .elements import _as_truncated from .elements import _literal_as_text from .elements import ClauseElement from .elements import ColumnClause
from .base import ColumnCollection from .base import DialectKWArgs from .base import SchemaEventTarget from .elements import _as_truncated from .elements import _document_text_coercion from .elements import _literal_as_text from .elements import ClauseElement from .elements import ColumnClause
class CheckConstraint(ColumnCollectionConstraint): _allow_multiple_tables = True def __init__( self, sqltext,
class CheckConstraint(ColumnCollectionConstraint): _allow_multiple_tables = True @_document_text_coercion( "sqltext", ":class:`.CheckConstraint`", ":paramref:`.CheckConstraint.sqltext`", ) def __init__( self, sqltext,
class CheckConstraint(ColumnCollectionConstraint): """ self.sqltext = _literal_as_text(sqltext, warn=False) columns = [] visitors.traverse(self.sqltext, {}, {"column": columns.append})
class CheckConstraint(ColumnCollectionConstraint): """ self.sqltext = _literal_as_text(sqltext, allow_coercion_to_text=True) columns = [] visitors.traverse(self.sqltext, {}, {"column": columns.append})
from .elements import _clause_element_as_expr from .elements import _clone from .elements import _cloned_difference from .elements import _cloned_intersection from .elements import _expand_cloned from .elements import _interpret_as_column_or_from from .elements import _literal_and_labels_as_label_reference from .elemen...
from .elements import _clause_element_as_expr from .elements import _clone from .elements import _cloned_difference from .elements import _cloned_intersection from .elements import _document_text_coercion from .elements import _expand_cloned from .elements import _interpret_as_column_or_from from .elements import _lite...
from .elements import ClauseElement from .elements import ClauseList from .elements import Grouping from .elements import literal_column from .elements import TextClause from .elements import True_ from .elements import UnaryExpression from .. import exc
from .elements import ClauseElement from .elements import ClauseList from .elements import Grouping from .elements import literal_column from .elements import True_ from .elements import UnaryExpression from .. import exc
def _interpret_as_from(element): insp = inspection.inspect(element, raiseerr=False) if insp is None: if isinstance(element, util.string_types): util.warn_limited( "Textual SQL FROM expression %(expr)r should be " "explicitly declared as text(%(expr)r), " ...
def _interpret_as_from(element): insp = inspection.inspect(element, raiseerr=False) if insp is None: if isinstance(element, util.string_types): _no_text_coercion(element) try: return insp.selectable except AttributeError:
class HasPrefixes(object): _prefixes = () @_generative def prefix_with(self, *expr, **kw): r"""Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.
class HasPrefixes(object): _prefixes = () @_generative @_document_text_coercion( "expr", ":meth:`.HasPrefixes.prefix_with`", ":paramref:`.HasPrefixes.prefix_with.*expr`", ) def prefix_with(self, *expr, **kw): r"""Add one or more expressions following the statement ke...
class HasPrefixes(object): def _setup_prefixes(self, prefixes, dialect=None): self._prefixes = self._prefixes + tuple( [(_literal_as_text(p, warn=False), dialect) for p in prefixes] )
class HasPrefixes(object): def _setup_prefixes(self, prefixes, dialect=None): self._prefixes = self._prefixes + tuple( [ (_literal_as_text(p, allow_coercion_to_text=True), dialect) for p in prefixes ] )
class HasSuffixes(object): _suffixes = () @_generative def suffix_with(self, *expr, **kw): r"""Add one or more expressions following the statement as a whole.
class HasSuffixes(object): _suffixes = () @_generative @_document_text_coercion( "expr", ":meth:`.HasSuffixes.suffix_with`", ":paramref:`.HasSuffixes.suffix_with.*expr`", ) def suffix_with(self, *expr, **kw): r"""Add one or more expressions following the statement as...
class HasSuffixes(object): def _setup_suffixes(self, suffixes, dialect=None): self._suffixes = self._suffixes + tuple( [(_literal_as_text(p, warn=False), dialect) for p in suffixes] )
class HasSuffixes(object): def _setup_suffixes(self, suffixes, dialect=None): self._suffixes = self._suffixes + tuple( [ (_literal_as_text(p, allow_coercion_to_text=True), dialect) for p in suffixes ] )
from .deprecations import inject_docstring_text # noqa from .deprecations import pending_deprecation # noqa from .deprecations import warn_deprecated # noqa from .deprecations import warn_pending_deprecation # noqa from .langhelpers import as_interface # noqa from .langhelpers import asbool # noqa from .langhelpe...
from .deprecations import inject_docstring_text # noqa from .deprecations import pending_deprecation # noqa from .deprecations import warn_deprecated # noqa from .deprecations import warn_pending_deprecation # noqa from .langhelpers import add_parameter_text # noqa from .langhelpers import as_interface # noqa fro...
functionality.""" import re import textwrap import warnings from . import compat from .langhelpers import decorator from .. import exc
functionality.""" import re import warnings from . import compat from .langhelpers import decorator from .langhelpers import inject_docstring_text from .langhelpers import inject_param_text from .. import exc
def _decorate_with_warning(func, wtype, message, docstring_header=None): decorated.__doc__ = doc decorated._sa_warn = lambda: warnings.warn(message, wtype, stacklevel=3) return decorated def _dedent_docstring(text): split_text = text.split("\n", 1) if len(split_text) == 1: return text ...
def _decorate_with_warning(func, wtype, message, docstring_header=None): decorated.__doc__ = doc decorated._sa_warn = lambda: warnings.warn(message, wtype, stacklevel=3) return decorated
import itertools import operator import re import sys import types import warnings
import itertools import operator import re import sys import textwrap import types import warnings
def quoted_token_parser(value): idx += 1 return ["".join(token) for token in result]
def quoted_token_parser(value): idx += 1 return ["".join(token) for token in result] def add_parameter_text(params, text): params = _collections.to_list(params) def decorate(fn): doc = fn.__doc__ is not None and fn.__doc__ or "" if doc: doc = inject_param_text(doc, {p...
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): Column( "id", Integer, ForeignKey("t1.id", deferrable=True, initially="XYZ"), primary_key=True, ), )
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): Column( "id", Integer, ForeignKey("t1.id", deferrable=True, initially="DEFERRED"), primary_key=True, ), )
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): schema.CreateTable(t2), "CREATE TABLE t2 (id INTEGER NOT NULL, " "PRIMARY KEY (id), FOREIGN KEY(id) REFERENCES t1 (id) " "DEFERRABLE INITIALLY XYZ)", ) def test_match_kw_raises(self):
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): schema.CreateTable(t2), "CREATE TABLE t2 (id INTEGER NOT NULL, " "PRIMARY KEY (id), FOREIGN KEY(id) REFERENCES t1 (id) " "DEFERRABLE INITIALLY DEFERRED)", ) def test_match_kw_raises(self):
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): "WITH (buffering = off)", ) def test_create_index_with_tablespace(self): m = MetaData() tbl = Table("testtbl", m, Column("data", String))
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): "WITH (buffering = off)", ) def test_create_index_with_using_unusual_conditions(self): m = MetaData() tbl = Table("testtbl", m, Column("data", String)) self.assert_compile( schema.CreateIndex( ...
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): "(room::TEXT WITH =)", ) def test_exclude_constraint_cast(self): m = MetaData() tbl = Table("testtbl", m, Column("room", String))
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): "(room::TEXT WITH =)", ) def test_exclude_constraint_colname_needs_quoting(self): m = MetaData() cons = ExcludeConstraint(("Some Column Name", "=")) Table("testtbl", m, Column("Some Column Name", String), cons) ...
from sqlalchemy.sql import operators from sqlalchemy.testing import assert_raises from sqlalchemy.testing import assert_raises_message from sqlalchemy.testing import eq_ from sqlalchemy.testing import expect_warnings from sqlalchemy.testing import fixtures from sqlalchemy.testing import in_ from sqlalchemy.testing impo...
from sqlalchemy.sql import operators from sqlalchemy.testing import assert_raises from sqlalchemy.testing import assert_raises_message from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing import in_ from sqlalchemy.testing import is_
class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): .order_by("email_address") ) with expect_warnings("Can't resolve label reference 'email_address'"): self.assert_compile( q, "SELECT users.id AS users_id, users.name AS users_name,...
class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): .order_by("email_address") ) assert_raises_message( sa.exc.CompileError, "Can't resolve label reference for ORDER BY / GROUP BY.", q.all, ) def test_deferred_fk_col(self): ...
from sqlalchemy.orm.util import join from sqlalchemy.orm.util import with_parent from sqlalchemy.sql import expression from sqlalchemy.sql import operators from sqlalchemy.testing import assert_warnings from sqlalchemy.testing import AssertsCompiledSQL from sqlalchemy.testing import fixtures from sqlalchemy.testing imp...
from sqlalchemy.orm.util import join from sqlalchemy.orm.util import with_parent from sqlalchemy.sql import expression from sqlalchemy.sql import operators from sqlalchemy.testing import AssertsCompiledSQL from sqlalchemy.testing import fixtures from sqlalchemy.testing import is_
class ColumnPropertyTest(_fixtures.FixtureTest, AssertsCompiledSQL): ua = aliased(User) q = s.query(ua).order_by("email_ad") def go(): self.assert_compile( q, "SELECT (SELECT max(addresses.email_address) AS max_1 " "FROM addresses WHER...
class ColumnPropertyTest(_fixtures.FixtureTest, AssertsCompiledSQL): ua = aliased(User) q = s.query(ua).order_by("email_ad") assert_raises_message( sa.exc.CompileError, "Can't resolve label reference for ORDER BY / GROUP BY", q.with_labels().statement.compile...
class TextTest(QueryTest, AssertsCompiledSQL): def test_fulltext(self): User = self.classes.User with expect_warnings("Textual SQL"): eq_( create_session() .query(User) .from_statement("select * from users order by id") .al...
class TextTest(QueryTest, AssertsCompiledSQL): def test_fulltext(self): User = self.classes.User assert_raises_message( sa_exc.ArgumentError, "Textual SQL expression", create_session().query(User).from_statement, "select * from users order by id", ...
class TextTest(QueryTest, AssertsCompiledSQL): def test_binds_coerce(self): User = self.classes.User with expect_warnings("Textual SQL expression"): eq_( create_session() .query(User) .filter("id in (:id1, :id2)") .params(i...
class TextTest(QueryTest, AssertsCompiledSQL): def test_binds_coerce(self): User = self.classes.User assert_raises_message( sa_exc.ArgumentError, r"Textual SQL expression 'id in \(:id1, :id2\)' " "should be explicitly declared", create_session().query...
class TextTest(QueryTest, AssertsCompiledSQL): # the queries here are again "invalid" from a SQL perspective, as the # "name" field isn't matched up to anything. # with expect_warnings("Can't resolve label reference 'name';"): self.assert_compile( s.query(User...
class TextTest(QueryTest, AssertsCompiledSQL): # the queries here are again "invalid" from a SQL perspective, as the # "name" field isn't matched up to anything. # q = ( s.query(User) .options(joinedload("addresses")) .order_by(desc("name")) ...
class TextTest(QueryTest, AssertsCompiledSQL): .limit(1) .offset(0) ) with expect_warnings( "Can't resolve label reference 'email_address desc'" ): eq_( [ ( User( ...
class TextTest(QueryTest, AssertsCompiledSQL): .limit(1) .offset(0) ) assert_raises_message( sa_exc.CompileError, "Can't resolve label reference for ORDER BY / GROUP BY", result.all, ) class TextErrorTest(QueryTest, AssertsCompiledSQ...
class TextWarningTest(QueryTest, AssertsCompiledSQL): arg, ) with expect_warnings("Textual "): stmt = fn(arg) self.assert_compile(stmt, expected) def test_filter(self): User = self.classes.User self._test( Session().query(User.id).fil...
class TextWarningTest(QueryTest, AssertsCompiledSQL): arg, ) def test_filter(self): User = self.classes.User self._test(Session().query(User.id).filter, "myid == 5", "myid == 5") def test_having(self): User = self.classes.User self._test(Session().query(User...
class TextWarningTest(QueryTest, AssertsCompiledSQL): Session().query(User.id).from_statement, "select id from user", "select id from user", "select id from user", )
class TextWarningTest(QueryTest, AssertsCompiledSQL): Session().query(User.id).from_statement, "select id from user", "select id from user", )
class DDLTest(fixtures.TestBase, AssertsCompiledSQL): schema_translate_map=schema_translate_map, ) class SchemaTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default"
class DDLTest(fixtures.TestBase, AssertsCompiledSQL): schema_translate_map=schema_translate_map, ) def test_fk_render(self): a = Table("a", MetaData(), Column("q", Integer)) b = Table("b", MetaData(), Column("p", Integer)) self.assert_compile( schema.AddCons...
class DefaultTest(fixtures.TestBase): ): assert_raises_message( sa.exc.ArgumentError, "SQL expression object or string expected, got object of type " "<.* 'list'> instead", t.select, [const],
class DefaultTest(fixtures.TestBase): ): assert_raises_message( sa.exc.ArgumentError, "SQL expression object expected, got object of type " "<.* 'list'> instead", t.select, [const],
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): def test_underscores(self): self.assert_compile(func.if_(), "if()") def test_generic_now(self): assert isinstance(func.now().type, sqltypes.DateTime)
class CompileTest(fixtures.TestBase, AssertsCompiledSQL): def test_underscores(self): self.assert_compile(func.if_(), "if()") def test_underscores_packages(self): self.assert_compile(func.foo_.bar_.if_(), "foo.bar.if()") def test_uppercase(self): # for now, we need to keep case ins...
from sqlalchemy.sql import column from sqlalchemy.sql import table from sqlalchemy.sql import util as sql_util from sqlalchemy.testing import assert_raises_message from sqlalchemy.testing import assert_warnings from sqlalchemy.testing import AssertsCompiledSQL from sqlalchemy.testing import eq_ from sqlalchemy.testing ...
from sqlalchemy.sql import column from sqlalchemy.sql import table from sqlalchemy.sql import util as sql_util from sqlalchemy.testing import assert_raises_message from sqlalchemy.testing import AssertsCompiledSQL from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.types import Nu...
class AsFromTest(fixtures.TestBase, AssertsCompiledSQL): eq_(set(t.element._bindparams), set(["bat", "foo", "bar"])) class TextWarningsTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def _test(self, fn, arg, offending_clause, expected): with expect_warnings("Textual "): ...
class AsFromTest(fixtures.TestBase, AssertsCompiledSQL): eq_(set(t.element._bindparams), set(["bat", "foo", "bar"])) class TextErrorsTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def _test(self, fn, arg, offending_clause): assert_raises_message( exc.Argument...