gurudesh/pytracebugs huggingface dataset:
# Buggy code
def copy(self, **kw):
    elements = [(col, self.operators[col]) for col in self.columns.keys()]
    c = self.__class__(
        *elements,
        name=self.name,
        deferrable=self.deferrable,
        initially=self.initially,
        where=self.where,
        using=self.using,
    )
    c.dispatch._update(self.dispatch)
    return c


# Traceback (KeyError)
=============================================== FAILURES ================================================
_________________________________ ToMetaDataExcludeConstraint.test_copy _________________________________
Traceback (most recent call last):
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/sql/test_metadata.py", line 5238, in test_copy
table_c = table.tometadata(meta2)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 1063, in tometadata
table.append_constraint(
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 867, in append_constraint
constraint._set_parent_with_dispatch(self)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/base.py", line 463, in _set_parent_with_dispatch
self._set_parent(parent)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3065, in _set_parent
ColumnCollectionMixin._set_parent(self, table)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3022, in _set_parent
for col in self._col_expressions(table):
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3016, in _col_expressions
return [
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3017, in <listcomp>
table.c[col] if isinstance(col, util.string_types) else col
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/util/_collections.py", line 194, in __getitem__
return self._data[key]
KeyError: "daterange(valid_from_date, valid_thru_date, '[]')"
======================================== short test summary info ========================================
FAILED test/sql/test_metadata.py::ToMetaDataExcludeConstraint::test_copy - KeyError: "daterange(valid_...

# Fixed code
def copy(self, target_table=None, **kw):
    elements = [
        (
            schema._copy_expression(expr, self.parent, target_table),
            self.operators[expr.name],
        )
        for expr in self.columns
    ]
    c = self.__class__(
        *elements,
        name=self.name,
        deferrable=self.deferrable,
        initially=self.initially,
        where=self.where,
        using=self.using,
    )
    c.dispatch._update(self.dispatch)
    return c
# Buggy code
def _copy_expression(expression, source_table, target_table):
    def replace(col):
        if (
            isinstance(col, Column)
            and col.table is source_table
            and col.key in source_table.c
        ):
            return target_table.c[col.key]
        else:
            return None

    return visitors.replacement_traverse(expression, {}, replace)


# Traceback (KeyError)
=============================================== FAILURES ================================================
_________________________________ ToMetaDataExcludeConstraint.test_copy _________________________________
Traceback (most recent call last):
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/sql/test_metadata.py", line 5238, in test_copy
table_c = table.tometadata(meta2)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 1063, in tometadata
table.append_constraint(
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 867, in append_constraint
constraint._set_parent_with_dispatch(self)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/base.py", line 463, in _set_parent_with_dispatch
self._set_parent(parent)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3065, in _set_parent
ColumnCollectionMixin._set_parent(self, table)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3022, in _set_parent
for col in self._col_expressions(table):
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3016, in _col_expressions
return [
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3017, in <listcomp>
table.c[col] if isinstance(col, util.string_types) else col
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/util/_collections.py", line 194, in __getitem__
return self._data[key]
KeyError: "daterange(valid_from_date, valid_thru_date, '[]')"
======================================== short test summary info ========================================
FAILED test/sql/test_metadata.py::ToMetaDataExcludeConstraint::test_copy - KeyError: "daterange(valid_...

# Fixed code
def _copy_expression(expression, source_table, target_table):
    if source_table is None or target_table is None:
        return expression

    def replace(col):
        if (
            isinstance(col, Column)
            and col.table is source_table
            and col.key in source_table.c
        ):
            return target_table.c[col.key]
        else:
            return None

    return visitors.replacement_traverse(expression, {}, replace)
# Buggy code
def copy(self, target_table=None, **kw):
    if target_table is not None:
        sqltext = _copy_expression(self.sqltext, self.table, target_table)
    else:
        sqltext = self.sqltext
    g = Computed(sqltext, persisted=self.persisted)

    return self._schema_item_copy(g)


# Traceback (KeyError)
=============================================== FAILURES ================================================
_________________________________ ToMetaDataExcludeConstraint.test_copy _________________________________
Traceback (most recent call last):
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/sql/test_metadata.py", line 5238, in test_copy
table_c = table.tometadata(meta2)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 1063, in tometadata
table.append_constraint(
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 867, in append_constraint
constraint._set_parent_with_dispatch(self)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/base.py", line 463, in _set_parent_with_dispatch
self._set_parent(parent)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3065, in _set_parent
ColumnCollectionMixin._set_parent(self, table)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3022, in _set_parent
for col in self._col_expressions(table):
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3016, in _col_expressions
return [
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3017, in <listcomp>
table.c[col] if isinstance(col, util.string_types) else col
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/util/_collections.py", line 194, in __getitem__
return self._data[key]
KeyError: "daterange(valid_from_date, valid_thru_date, '[]')"
======================================== short test summary info ========================================
FAILED test/sql/test_metadata.py::ToMetaDataExcludeConstraint::test_copy - KeyError: "daterange(valid_...

# Fixed code
def copy(self, target_table=None, **kw):
    sqltext = _copy_expression(
        self.sqltext,
        self.column.table if self.column is not None else None,
        target_table,
    )
    g = Computed(sqltext, persisted=self.persisted)

    return self._schema_item_copy(g)
# Buggy code
def copy(self, target_table=None, **kw):
    i = Identity(
        always=self.always,
        on_null=self.on_null,
        start=self.start,
        increment=self.increment,
        minvalue=self.minvalue,
        maxvalue=self.maxvalue,
        nominvalue=self.nominvalue,
        nomaxvalue=self.nomaxvalue,
        cycle=self.cycle,
        cache=self.cache,
        order=self.order,
    )

    return self._schema_item_copy(i)


# Traceback (KeyError)
=============================================== FAILURES ================================================
_________________________________ ToMetaDataExcludeConstraint.test_copy _________________________________
Traceback (most recent call last):
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/sql/test_metadata.py", line 5238, in test_copy
table_c = table.tometadata(meta2)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 1063, in tometadata
table.append_constraint(
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 867, in append_constraint
constraint._set_parent_with_dispatch(self)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/base.py", line 463, in _set_parent_with_dispatch
self._set_parent(parent)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3065, in _set_parent
ColumnCollectionMixin._set_parent(self, table)
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3022, in _set_parent
for col in self._col_expressions(table):
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3016, in _col_expressions
return [
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/sql/schema.py", line 3017, in <listcomp>
table.c[col] if isinstance(col, util.string_types) else col
File "/home/jeffh/workspace/vortex-workspace/vfinance/subrepos/SQLAlchemy-1.3.18/test/../lib/sqlalchemy/util/_collections.py", line 194, in __getitem__
return self._data[key]
KeyError: "daterange(valid_from_date, valid_thru_date, '[]')"
======================================== short test summary info ========================================
FAILED test/sql/test_metadata.py::ToMetaDataExcludeConstraint::test_copy - KeyError: "daterange(valid_...

# Fixed code
def copy(self, **kw):
    i = Identity(
        always=self.always,
        on_null=self.on_null,
        start=self.start,
        increment=self.increment,
        minvalue=self.minvalue,
        maxvalue=self.maxvalue,
        nominvalue=self.nominvalue,
        nomaxvalue=self.nomaxvalue,
        cycle=self.cycle,
        cache=self.cache,
        order=self.order,
    )

    return self._schema_item_copy(i)
# Buggy code
def fetchone(self, result, dbapi_cursor, hard_close=False):
    if not self._rowbuffer:
        self._buffer_rows(result, dbapi_cursor)
        if not self._rowbuffer:
            try:
                result._soft_close(hard=hard_close)
            except BaseException as e:
                self.handle_exception(result, e)
            return None
    return self._rowbuffer.popleft()


# Traceback (TypeError)
Traceback (most recent call last):
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/cursor.py", line 1093, in fetchmany
buf.extend(dbapi_cursor.fetchmany(size - lb))
KeyboardInterrupt

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
...
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/result.py", line 379, in iterrows
for row in self._fetchiter_impl():
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/orm/loading.py", line 105, in chunks
fetch = cursor.fetchmany(yield_per)
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/result.py", line 1011, in fetchmany
return self._manyrow_getter(self, size)
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/result.py", line 536, in manyrows
rows = self._fetchmany_impl(num)
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/cursor.py", line 1740, in _fetchmany_impl
return self.cursor_strategy.fetchmany(self, self.cursor, size)
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/cursor.py", line 1095, in fetchmany
self.handle_exception(result, e)
TypeError: handle_exception() missing 1 required positional argument: 'err'

# Fixed code
def fetchone(self, result, dbapi_cursor, hard_close=False):
    if not self._rowbuffer:
        self._buffer_rows(result, dbapi_cursor)
        if not self._rowbuffer:
            try:
                result._soft_close(hard=hard_close)
            except BaseException as e:
                self.handle_exception(result, dbapi_cursor, e)
            return None
    return self._rowbuffer.popleft()
# Buggy code
def fetchmany(self, result, dbapi_cursor, size=None):
    if size is None:
        return self.fetchall(result, dbapi_cursor)

    buf = list(self._rowbuffer)
    lb = len(buf)
    if size > lb:
        try:
            buf.extend(dbapi_cursor.fetchmany(size - lb))
        except BaseException as e:
            self.handle_exception(result, e)

    result = buf[0:size]
    self._rowbuffer = collections.deque(buf[size:])
    return result


# Traceback (TypeError)
Traceback (most recent call last):
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/cursor.py", line 1093, in fetchmany
buf.extend(dbapi_cursor.fetchmany(size - lb))
KeyboardInterrupt

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
...
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/result.py", line 379, in iterrows
for row in self._fetchiter_impl():
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/orm/loading.py", line 105, in chunks
fetch = cursor.fetchmany(yield_per)
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/result.py", line 1011, in fetchmany
return self._manyrow_getter(self, size)
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/result.py", line 536, in manyrows
rows = self._fetchmany_impl(num)
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/cursor.py", line 1740, in _fetchmany_impl
return self.cursor_strategy.fetchmany(self, self.cursor, size)
File "<private>/venv/lib/python3.8/site-packages/sqlalchemy/engine/cursor.py", line 1095, in fetchmany
self.handle_exception(result, e)
TypeError: handle_exception() missing 1 required positional argument: 'err'

# Fixed code
def fetchmany(self, result, dbapi_cursor, size=None):
    if size is None:
        return self.fetchall(result, dbapi_cursor)

    buf = list(self._rowbuffer)
    lb = len(buf)
    if size > lb:
        try:
            buf.extend(dbapi_cursor.fetchmany(size - lb))
        except BaseException as e:
            self.handle_exception(result, dbapi_cursor, e)

    result = buf[0:size]
    self._rowbuffer = collections.deque(buf[size:])
    return result
# Buggy code
def _sql_message(self, as_unicode):
    from sqlalchemy.sql import util

    details = [self._message(as_unicode=as_unicode)]
    if self.statement:
        if not as_unicode and not compat.py3k:
            stmt_detail = "[SQL: %s]" % compat.safe_bytestring(self.statement)
        else:
            stmt_detail = "[SQL: %s]" % self.statement
        details.append(stmt_detail)
        if self.params:
            if self.hide_parameters:
                details.append("[SQL parameters hidden due to hide_parameters=True]")
            else:
                params_repr = util._repr_params(self.params, 10, ismulti=self.ismulti)
                details.append("[parameters: %r]" % params_repr)
    code_str = self._code_str()
    if code_str:
        details.append(code_str)
    return "\n".join(["(%s)" % det for det in self.detail] + details)


# Traceback (sqlalchemy.exc.ProgrammingError)
Exception ignored in: <generator object it at 0x7f6aefc9a4a0>
Traceback (most recent call last):
File "run.py", line 36, in it
File ".../python3.8/site-packages/sqlalchemy/engine/base.py", line 1781, in __exit__
File ".../python3.8/site-packages/sqlalchemy/engine/base.py", line 1753, in rollback
File ".../python3.8/site-packages/sqlalchemy/engine/base.py", line 1791, in _do_rollback
File ".../python3.8/site-packages/sqlalchemy/engine/base.py", line 751, in _rollback_impl
File ".../python3.8/site-packages/sqlalchemy/engine/base.py", line 1510, in _handle_dbapi_exception
File ".../python3.8/site-packages/sqlalchemy/util/compat.py", line 182, in raise_
File ".../python3.8/site-packages/sqlalchemy/engine/base.py", line 749, in _rollback_impl
File ".../python3.8/site-packages/sqlalchemy/engine/default.py", line 543, in do_rollback
sqlalchemy.exc.ProgrammingError: <exception str() failed>

# Fixed code
def _sql_message(self, as_unicode):
    util = _preloaded.preloaded.sql_util

    details = [self._message(as_unicode=as_unicode)]
    if self.statement:
        if not as_unicode and not compat.py3k:
            stmt_detail = "[SQL: %s]" % compat.safe_bytestring(self.statement)
        else:
            stmt_detail = "[SQL: %s]" % self.statement
        details.append(stmt_detail)
        if self.params:
            if self.hide_parameters:
                details.append("[SQL parameters hidden due to hide_parameters=True]")
            else:
                params_repr = util._repr_params(self.params, 10, ismulti=self.ismulti)
                details.append("[parameters: %r]" % params_repr)
    code_str = self._code_str()
    if code_str:
        details.append(code_str)
    return "\n".join(["(%s)" % det for det in self.detail] + details)
# Buggy code
def _message(self, as_unicode=compat.py3k):
    # rules:
    #
    # 1. under py2k, for __str__ return single string arg as it was
    # given without converting to unicode.  for __unicode__
    # do a conversion but check that it's not unicode already just in
    # case
    #
    # 2. under py3k, single arg string will usually be a unicode
    # object, but since __str__() must return unicode, check for
    # bytestring just in case
    #
    # 3. for multiple self.args, this is not a case in current
    # SQLAlchemy though this is happening in at least one known external
    # library, call str() which does a repr().
    #
    if len(self.args) == 1:
        text = self.args[0]
        if as_unicode and isinstance(text, compat.binary_types):
            return compat.decode_backslashreplace(text, "utf-8")
        else:
            return self.args[0]
    else:
        # this is not a normal case within SQLAlchemy but is here for
        # compatibility with Exception.args - the str() comes out as
        # a repr() of the tuple
        return str(self.args)


# Traceback (TypeError)
from sqlalchemy.exc import SQLAlchemyError
class Foo(object):
...     pass
str(SQLAlchemyError(Foo()))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __str__ returned non-string (type Foo)

# Fixed code
def _message(self, as_unicode=compat.py3k):
    # rules:
    #
    # 1. under py2k, for __str__ return single string arg as it was
    # given without converting to unicode.  for __unicode__
    # do a conversion but check that it's not unicode already just in
    # case
    #
    # 2. under py3k, single arg string will usually be a unicode
    # object, but since __str__() must return unicode, check for
    # bytestring just in case
    #
    # 3. for multiple self.args, this is not a case in current
    # SQLAlchemy though this is happening in at least one known external
    # library, call str() which does a repr().
    #
    if len(self.args) == 1:
        text = self.args[0]

        if as_unicode and isinstance(text, compat.binary_types):
            text = compat.decode_backslashreplace(text, "utf-8")
        # This is for when the argument is not a string of any sort.
        # Otherwise, converting this exception to string would fail for
        # non-string arguments.
        elif compat.py3k or not as_unicode:
            text = str(text)
        else:
            text = compat.text_type(text)

        return text
    else:
        # this is not a normal case within SQLAlchemy but is here for
        # compatibility with Exception.args - the str() comes out as
        # a repr() of the tuple
        return str(self.args)
# Buggy code
def _merge_textual_cols_by_position(self, context, cursor_description, result_columns):
    num_ctx_cols = len(result_columns) if result_columns else None

    if num_ctx_cols > len(cursor_description):
        util.warn(
            "Number of columns in textual SQL (%d) is "
            "smaller than number of columns requested (%d)"
            % (num_ctx_cols, len(cursor_description))
        )
    seen = set()
    for (
        idx,
        colname,
        untranslated,
        coltype,
    ) in self._colnames_from_description(context, cursor_description):
        if idx < num_ctx_cols:
            ctx_rec = result_columns[idx]
            obj = ctx_rec[RM_OBJECTS]
            mapped_type = ctx_rec[RM_TYPE]
            if obj[0] in seen:
                raise exc.InvalidRequestError(
                    "Duplicate column expression requested in textual SQL: %r" % obj[0]
                )
            seen.add(obj[0])
        else:
            mapped_type = sqltypes.NULLTYPE
            obj = None
        yield idx, colname, mapped_type, coltype, obj, untranslated


# Traceback (sqlalchemy.exc.InvalidRequestError)
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine [generated in 0.00025s] {}
1
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine [cached since 0.001864s ago] {}
Traceback (most recent call last):
File "test_cache.py", line 28, in <module>
print(e.execute(build_query()).first()[users.c.id])
File "sqlalchemy/lib/sqlalchemy/engine/cursor.py", line 587, in _raise_for_ambiguous_column_name
raise exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'id' in result set column descriptions

# Fixed code
def _merge_textual_cols_by_position(self, context, cursor_description, result_columns):
    num_ctx_cols = len(result_columns) if result_columns else None

    if num_ctx_cols > len(cursor_description):
        util.warn(
            "Number of columns in textual SQL (%d) is "
            "smaller than number of columns requested (%d)"
            % (num_ctx_cols, len(cursor_description))
        )
    seen = set()
    for (
        idx,
        colname,
        untranslated,
        coltype,
    ) in self._colnames_from_description(context, cursor_description):
        if idx < num_ctx_cols:
            ctx_rec = result_columns[idx]
            obj = ctx_rec[RM_OBJECTS]
            ridx = idx
            mapped_type = ctx_rec[RM_TYPE]
            if obj[0] in seen:
                raise exc.InvalidRequestError(
                    "Duplicate column expression requested in textual SQL: %r" % obj[0]
                )
            seen.add(obj[0])
        else:
            mapped_type = sqltypes.NULLTYPE
            obj = None
            ridx = None
        yield idx, ridx, colname, mapped_type, coltype, obj, untranslated
# Buggy code
def _merge_cols_by_name(
    self,
    context,
    cursor_description,
    result_columns,
    loose_column_name_matching,
):
    dialect = context.dialect
    case_sensitive = dialect.case_sensitive
    match_map = self._create_description_match_map(
        result_columns, case_sensitive, loose_column_name_matching
    )

    for (
        idx,
        colname,
        untranslated,
        coltype,
    ) in self._colnames_from_description(context, cursor_description):
        try:
            ctx_rec = match_map[colname]
        except KeyError:
            mapped_type = sqltypes.NULLTYPE
            obj = None
        else:
            obj = ctx_rec[1]
            mapped_type = ctx_rec[2]
        yield idx, colname, mapped_type, coltype, obj, untranslated


# Traceback (sqlalchemy.exc.InvalidRequestError)
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine [generated in 0.00025s] {}
1
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine [cached since 0.001864s ago] {}
Traceback (most recent call last):
File "test_cache.py", line 28, in <module>
print(e.execute(build_query()).first()[users.c.id])
File "sqlalchemy/lib/sqlalchemy/engine/cursor.py", line 587, in _raise_for_ambiguous_column_name
raise exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'id' in result set column descriptions

# Fixed code
def _merge_cols_by_name(
    self,
    context,
    cursor_description,
    result_columns,
    loose_column_name_matching,
):
    dialect = context.dialect
    case_sensitive = dialect.case_sensitive
    match_map = self._create_description_match_map(
        result_columns, case_sensitive, loose_column_name_matching
    )
    for (
        idx,
        colname,
        untranslated,
        coltype,
    ) in self._colnames_from_description(context, cursor_description):
        try:
            ctx_rec = match_map[colname]
        except KeyError:
            mapped_type = sqltypes.NULLTYPE
            obj = None
            result_columns_idx = None
        else:
            obj = ctx_rec[1]
            mapped_type = ctx_rec[2]
            result_columns_idx = ctx_rec[3]
        yield (
            idx,
            result_columns_idx,
            colname,
            mapped_type,
            coltype,
            obj,
            untranslated,
        )
# Buggy code
def _merge_cols_by_none(self, context, cursor_description):
    for (
        idx,
        colname,
        untranslated,
        coltype,
    ) in self._colnames_from_description(context, cursor_description):
        yield idx, colname, sqltypes.NULLTYPE, coltype, None, untranslated


# Traceback (sqlalchemy.exc.InvalidRequestError)
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine [generated in 0.00025s] {}
1
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine [cached since 0.001864s ago] {}
Traceback (most recent call last):
File "test_cache.py", line 28, in <module>
print(e.execute(build_query()).first()[users.c.id])
File "sqlalchemy/lib/sqlalchemy/engine/cursor.py", line 587, in _raise_for_ambiguous_column_name
raise exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'id' in result set column descriptions

# Fixed code
def _merge_cols_by_none(self, context, cursor_description):
    for (
        idx,
        colname,
        untranslated,
        coltype,
    ) in self._colnames_from_description(context, cursor_description):
        yield (
            idx,
            None,
            colname,
            sqltypes.NULLTYPE,
            coltype,
            None,
            untranslated,
        )
# Buggy code
def __getstate__(self):
    return {
        "_keymap": {
            key: (rec[MD_INDEX], _UNPICKLED, key)
            for key, rec in self._keymap.items()
            if isinstance(key, util.string_types + util.int_types)
        },
        "_keys": self._keys,
        "case_sensitive": self.case_sensitive,
        "_translated_indexes": self._translated_indexes,
        "_tuplefilter": self._tuplefilter,
    }


# Traceback (sqlalchemy.exc.InvalidRequestError)
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine [generated in 0.00025s] {}
1
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine [cached since 0.001864s ago] {}
Traceback (most recent call last):
File "test_cache.py", line 28, in <module>
print(e.execute(build_query()).first()[users.c.id])
File "sqlalchemy/lib/sqlalchemy/engine/cursor.py", line 587, in _raise_for_ambiguous_column_name
raise exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'id' in result set column descriptions

# Fixed code
def __getstate__(self):
    return {
        "_keymap": {
            key: (rec[MD_INDEX], rec[MD_RESULT_MAP_INDEX], _UNPICKLED, key)
            for key, rec in self._keymap.items()
            if isinstance(key, util.string_types + util.int_types)
        },
        "_keys": self._keys,
        "case_sensitive": self.case_sensitive,
        "_translated_indexes": self._translated_indexes,
        "_tuplefilter": self._tuplefilter,
    }
# Buggy code
def __setstate__(self, state):
    self._processors = [None for _ in range(len(state["_keys"]))]
    self._keymap = state["_keymap"]

    self._keys = state["_keys"]
    self.case_sensitive = state["case_sensitive"]

    if state["_translated_indexes"]:
        self._translated_indexes = state["_translated_indexes"]
        self._tuplefilter = tuplegetter(*self._translated_indexes)
    else:
        self._translated_indexes = self._tuplefilter = None


# Traceback (sqlalchemy.exc.InvalidRequestError)
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,711 INFO sqlalchemy.engine.Engine [generated in 0.00025s] {}
1
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine SELECT users.id, teams.id
FROM users LEFT OUTER JOIN teams ON teams.id = users.team_id
2020-09-05 14:00:42,712 INFO sqlalchemy.engine.Engine [cached since 0.001864s ago] {}
Traceback (most recent call last):
File "test_cache.py", line 28, in <module>
print(e.execute(build_query()).first()[users.c.id])
File "sqlalchemy/lib/sqlalchemy/engine/cursor.py", line 587, in _raise_for_ambiguous_column_name
raise exc.InvalidRequestError(
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'id' in result set column descriptions

# Fixed code
def __setstate__(self, state):
    self._processors = [None for _ in range(len(state["_keys"]))]
    self._keymap = state["_keymap"]

    self._keymap_by_result_column_idx = {
        rec[MD_RESULT_MAP_INDEX]: rec for rec in self._keymap.values()
    }
    self._keys = state["_keys"]
    self.case_sensitive = state["case_sensitive"]

    if state["_translated_indexes"]:
        self._translated_indexes = state["_translated_indexes"]
        self._tuplefilter = tuplegetter(*self._translated_indexes)
    else:
        self._translated_indexes = self._tuplefilter = None
# Buggy code
def create_async_engine(*arg, **kw):
    """Create a new async engine instance.

    Arguments passed to :func:`_asyncio.create_async_engine` are mostly
    identical to those passed to the :func:`_sa.create_engine` function.
    The specified dialect must be an asyncio-compatible dialect
    such as :ref:`dialect-postgresql-asyncpg`.

    .. versionadded:: 1.4

    """

    if kw.get("server_side_cursors", False):
        raise exc.AsyncMethodRequired(
            "Can't set server_side_cursors for async engine globally; "
            "use the connection.stream() method for an async "
            "streaming result set"
        )
    kw["future"] = True
    sync_engine = _create_engine(*arg, **kw)
    return AsyncEngine(sync_engine)


# Traceback (AttributeError)
In [1]: from sqlalchemy.ext.asyncio import create_async_engine

In [2]: await create_async_engine(server_side_cursors=True)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-2bcff6ed9bdc> in <module>
----> 1 await create_async_engine(server_side_cursors=True)

lib/sqlalchemy/ext/asyncio/engine.py in create_async_engine(*arg, **kw)
32
33     if kw.get("server_side_cursors", False):
---> 34         raise exc.AsyncMethodRequired(
35             "Can't set server_side_cursors for async engine globally; "
36             "use the connection.stream() method for an async "

AttributeError: module 'sqlalchemy.exc' has no attribute 'AsyncMethodRequired'

# Fixed code
def create_async_engine(*arg, **kw):
    """Create a new async engine instance.

    Arguments passed to :func:`_asyncio.create_async_engine` are mostly
    identical to those passed to the :func:`_sa.create_engine` function.
    The specified dialect must be an asyncio-compatible dialect
    such as :ref:`dialect-postgresql-asyncpg`.

    .. versionadded:: 1.4

    """

    if kw.get("server_side_cursors", False):
        raise async_exc.AsyncMethodRequired(
            "Can't set server_side_cursors for async engine globally; "
            "use the connection.stream() method for an async "
            "streaming result set"
        )
    kw["future"] = True
    sync_engine = _create_engine(*arg, **kw)
    return AsyncEngine(sync_engine)
# Buggy code
def __init__(self, iterable=None):
    self._members = dict()
    if iterable:
        for o in iterable:
            self.add(o)


# Traceback (NotImplementedError)
Traceback (most recent call last):
File "sandbox/sqlalchemy_collections.py", line 29, in <module>
parent.children = [
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 271, in __set__
self.impl.set(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1335, in set
collections.bulk_replace(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/collections.py", line 790, in bulk_replace
constants = existing_idset.intersection(values or ())
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 615, in intersection
result._members.update(self._working_set(members).intersection(other))
File "sandbox/sqlalchemy_collections.py", line 23, in __hash__
raise NotImplementedError
NotImplementedError

# Fixed code
def __init__(self, iterable=None):
    self._members = dict()
    if iterable:
        self.update(iterable)
# Buggy code
def issubset(self, iterable):
    other = type(self)(iterable)

    if len(self) > len(other):
        return False
    for m in itertools_filterfalse(
        other._members.__contains__, iter(self._members.keys())
    ):
        return False
    return True


# Traceback (NotImplementedError)
Traceback (most recent call last):
File "sandbox/sqlalchemy_collections.py", line 29, in <module>
parent.children = [
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 271, in __set__
self.impl.set(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1335, in set
collections.bulk_replace(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/collections.py", line 790, in bulk_replace
constants = existing_idset.intersection(values or ())
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 615, in intersection
result._members.update(self._working_set(members).intersection(other))
File "sandbox/sqlalchemy_collections.py", line 23, in __hash__
raise NotImplementedError
NotImplementedError

# Fixed code
def issubset(self, iterable):
    other = self.__class__(iterable)

    if len(self) > len(other):
        return False
    for m in itertools_filterfalse(
        other._members.__contains__, iter(self._members.keys())
    ):
        return False
    return True
# Buggy code
def issuperset(self, iterable):
    other = type(self)(iterable)

    if len(self) < len(other):
        return False

    for m in itertools_filterfalse(
        self._members.__contains__, iter(other._members.keys())
    ):
        return False
    return True


# Traceback (NotImplementedError)
Traceback (most recent call last):
File "sandbox/sqlalchemy_collections.py", line 29, in <module>
parent.children = [
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 271, in __set__
self.impl.set(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1335, in set
collections.bulk_replace(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/collections.py", line 790, in bulk_replace
constants = existing_idset.intersection(values or ())
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 615, in intersection
result._members.update(self._working_set(members).intersection(other))
File "sandbox/sqlalchemy_collections.py", line 23, in __hash__
raise NotImplementedError
NotImplementedError

# Fixed code
def issuperset(self, iterable):
    other = self.__class__(iterable)

    if len(self) < len(other):
        return False

    for m in itertools_filterfalse(
        self._members.__contains__, iter(other._members.keys())
    ):
        return False
    return True
# Buggy code
def union(self, iterable):
    result = type(self)()
    # testlib.pragma exempt:__hash__
    members = self._member_id_tuples()
    other = _iter_id(iterable)
    result._members.update(self._working_set(members).union(other))
    return result


# Traceback (NotImplementedError)
Traceback (most recent call last):
File "sandbox/sqlalchemy_collections.py", line 29, in <module>
parent.children = [
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 271, in __set__
self.impl.set(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1335, in set
collections.bulk_replace(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/collections.py", line 790, in bulk_replace
constants = existing_idset.intersection(values or ())
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 615, in intersection
result._members.update(self._working_set(members).intersection(other))
File "sandbox/sqlalchemy_collections.py", line 23, in __hash__
raise NotImplementedError
NotImplementedError

# Fixed code
def union(self, iterable):
    result = self.__class__()
    members = self._members
    result._members.update(members)
    result._members.update((id(obj), obj) for obj in iterable)
    return result
# Buggy code
def update(self, iterable):
    self._members = self.union(iterable)._members


# Traceback (NotImplementedError)
Traceback (most recent call last):
File "sandbox/sqlalchemy_collections.py", line 29, in <module>
parent.children = [
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 271, in __set__
self.impl.set(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1335, in set
collections.bulk_replace(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/collections.py", line 790, in bulk_replace
constants = existing_idset.intersection(values or ())
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 615, in intersection
result._members.update(self._working_set(members).intersection(other))
File "sandbox/sqlalchemy_collections.py", line 23, in __hash__
raise NotImplementedError
NotImplementedError

# Fixed code
def update(self, iterable):
    self._members.update((id(obj), obj) for obj in iterable)
# Buggy code
def difference(self, iterable):
    result = type(self)()
    # testlib.pragma exempt:__hash__
    members = self._member_id_tuples()
    other = _iter_id(iterable)
    result._members.update(self._working_set(members).difference(other))
    return result


# Traceback (NotImplementedError)
Traceback (most recent call last):
File "sandbox/sqlalchemy_collections.py", line 29, in <module>
parent.children = [
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 271, in __set__
self.impl.set(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1335, in set
collections.bulk_replace(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/collections.py", line 790, in bulk_replace
constants = existing_idset.intersection(values or ())
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 615, in intersection
result._members.update(self._working_set(members).intersection(other))
File "sandbox/sqlalchemy_collections.py", line 23, in __hash__
raise NotImplementedError
NotImplementedError

# Fixed code
def difference(self, iterable):
    result = self.__class__()
    members = self._members
    other = {id(obj) for obj in iterable}
    result._members.update(((k, v) for k, v in members.items() if k not in other))
    return result
# Buggy code
def intersection(self, iterable):
    result = type(self)()
    # testlib.pragma exempt:__hash__
    members = self._member_id_tuples()
    other = _iter_id(iterable)
    result._members.update(self._working_set(members).intersection(other))
    return result


# Traceback (NotImplementedError)
Traceback (most recent call last):
File "sandbox/sqlalchemy_collections.py", line 29, in <module>
parent.children = [
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 271, in __set__
self.impl.set(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1335, in set
collections.bulk_replace(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/collections.py", line 790, in bulk_replace
constants = existing_idset.intersection(values or ())
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 615, in intersection
result._members.update(self._working_set(members).intersection(other))
File "sandbox/sqlalchemy_collections.py", line 23, in __hash__
raise NotImplementedError
NotImplementedError

# Fixed code
def intersection(self, iterable):
    result = self.__class__()
    members = self._members
    other = {id(obj) for obj in iterable}
    result._members.update((k, v) for k, v in members.items() if k in other)
    return result
# Buggy code
def symmetric_difference(self, iterable):
    result = type(self)()
    # testlib.pragma exempt:__hash__
    members = self._member_id_tuples()
    other = _iter_id(iterable)
    result._members.update(self._working_set(members).symmetric_difference(other))
    return result


# Traceback (NotImplementedError)
Traceback (most recent call last):
File "sandbox/sqlalchemy_collections.py", line 29, in <module>
parent.children = [
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 271, in __set__
self.impl.set(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/attributes.py", line 1335, in set
collections.bulk_replace(
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/orm/collections.py", line 790, in bulk_replace
constants = existing_idset.intersection(values or ())
File "/Users/james/Projects/new-realtimerail/.pyenv/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 615, in intersection
result._members.update(self._working_set(members).intersection(other))
File "sandbox/sqlalchemy_collections.py", line 23, in __hash__
raise NotImplementedError
NotImplementedError

# Fixed code
def symmetric_difference(self, iterable):
    result = self.__class__()
    members = self._members
    other = {id(obj): obj for obj in iterable}
    result._members.update(((k, v) for k, v in members.items() if k not in other))
    result._members.update(((k, v) for k, v in other.items() if k not in members))
    return result
# Buggy code
def entity_zero_or_selectable(self):
    if self.entity_zero is not None:
        return self.entity_zero
    elif self.actual_froms:
        return list(self.actual_froms)[0]
    else:
        return None


# Traceback (sqlalchemy.exc.InvalidRequestError)
Traceback (most recent call last):
File "/home/mahenzon/.PyCharm2019.2/config/scratches/scratch_32.py", line 283, in <module>
main()
File "/home/mahenzon/.PyCharm2019.2/config/scratches/scratch_32.py", line 279, in main
run_cte_query()
File "/home/mahenzon/.PyCharm2019.2/config/scratches/scratch_32.py", line 269, in run_cte_query
query = create_cte_query()
File "/home/mahenzon/.PyCharm2019.2/config/scratches/scratch_32.py", line 258, in create_cte_query
full=True,
File "/home/mahenzon/.local/share/virtualenvs/core-C3GrfXXb/src/sqlalchemy/lib/sqlalchemy/orm/query.py", line 2246, in join
from_joinpoint=from_joinpoint,
File "<string>", line 2, in _join
File "/home/mahenzon/.local/share/virtualenvs/core-C3GrfXXb/src/sqlalchemy/lib/sqlalchemy/orm/base.py", line 220, in generate
fn(self, *args[1:], **kw)
File "/home/mahenzon/.local/share/virtualenvs/core-C3GrfXXb/src/sqlalchemy/lib/sqlalchemy/orm/query.py", line 2425, in _join
left, right, onclause, prop, create_aliases, outerjoin, full
File "/home/mahenzon/.local/share/virtualenvs/core-C3GrfXXb/src/sqlalchemy/lib/sqlalchemy/orm/query.py", line 2448, in _join_left_to_right
) = self._join_determine_implicit_left_side(left, right, onclause)
File "/home/mahenzon/.local/share/virtualenvs/core-C3GrfXXb/src/sqlalchemy/lib/sqlalchemy/orm/query.py", line 2590, in _join_determine_implicit_left_side
"side of this join" % (right,)
sqlalchemy.exc.InvalidRequestError: Don't know how to join to ; please use an ON clause to more clearly establish the left side of this join

# Fixed code
def entity_zero_or_selectable(self):
    if self.entity_zero is not None:
        return self.entity_zero
    elif self.actual_froms:
        return self.actual_froms[0]
    else:
        return None