internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: edgedb/edgedb

Issue:
SDL with polymorphic functions is broken
Currently, if a polymorphic function is introduced via SDL the migration then produces only _one_ of the variants presented in SDL.

Example of problematic SDL:
```edgeql
function hello12(a: int64) -> str
    from edgeql $$
        SELECT 'hello' ++ <str>a
    $$;

function hello12(a: str) -> str
    from edgeql $$
        SELECT 'hello' ++ a
    $$;
```




Discussion:

Resolving patch:
diff --git a/edb/edgeql/declarative.py b/edb/edgeql/declarative.py
--- a/edb/edgeql/declarative.py
+++ b/edb/edgeql/declarative.py
@@ -337,6 +337,18 @@ def trace_View(
     _register_item(node, hard_dep_exprs=hard_dep_exprs, ctx=ctx)
 
 
+@trace_dependencies.register
+def trace_Function(node: qlast.CreateFunction, *, ctx: DepTraceContext):
+    # Functions are defined by their name + call signature, so we need
+    # to add that to the "extra_name".
+    params = f'({qlcodegen.generate_source(node.params)})'
+    m = hashlib.sha1()
+    m.update(params.encode())
+    extra_name = m.hexdigest()
+
+    _register_item(node, ctx=ctx, extra_name=extra_name)
+
+
 @trace_dependencies.register
 def trace_default(node: qlast.CreateObject, *, ctx: DepTraceContext):
     # Generic DDL catchall


Test patch:
diff --git a/tests/test_edgeql_data_migration.py b/tests/test_edgeql_data_migration.py
--- a/tests/test_edgeql_data_migration.py
+++ b/tests/test_edgeql_data_migration.py
@@ -2624,12 +2624,6 @@ async def test_edgeql_migration_function_11(self):
                 r"""SELECT hello11(1);"""
             )
 
-    @test.xfail('''
-        edgedb.errors.QueryError: could not find a function variant hello12
-
-        After the migration only one version of the function exists,
-        instead of two.
-    ''')
     async def test_edgeql_migration_function_12(self):
         await self.con.execute("""
             SET MODULE test;
@@ -2670,12 +2664,6 @@ async def test_edgeql_migration_function_12(self):
             ['hello1'],
         )
 
-    @test.xfail('''
-        edgedb.errors.QueryError: could not find a function variant hello13
-
-        The first migration ostensibly succeeds, but there's only one
-        version of the function instead of two.
-    ''')
     async def test_edgeql_migration_function_13(self):
         # this is the inverse of test_edgeql_migration_function_12
         await self.con.execute("""
@@ -2721,7 +2709,7 @@ async def test_edgeql_migration_function_13(self):
                 edgedb.QueryError,
                 r'could not find a function variant hello13'):
             await self.con.execute(
-                r"""SELECT hello11(' world');"""
+                r"""SELECT hello13(' world');"""
             )
 
     async def test_edgeql_migration_linkprops_01(self):
Repository: edgedb/edgedb

Issue:
No need to use sha1 in edb/edgeql/declarative.py
No need to use sha1 on rendered parameters, just use the rendered string as `extra_name`.


Discussion:
I copied this practice from `trace_ConcreteConstraint` handling of `extra_name` to be honest. Should I also remove the sha1 from there? Is there some deeper reason behind it @elprans?
No deeper reason, just drop it.

Resolving patch:
diff --git a/edb/edgeql/declarative.py b/edb/edgeql/declarative.py
--- a/edb/edgeql/declarative.py
+++ b/edb/edgeql/declarative.py
@@ -31,7 +31,6 @@
 from __future__ import annotations
 
 import copy
-import hashlib
 import functools
 
 from edb import errors
@@ -292,10 +291,7 @@ def trace_ConcreteConstraint(
         loop_control = None
 
     if exprs:
-        texts = [qlcodegen.generate_source(e) for e in exprs]
-        m = hashlib.sha1()
-        m.update('|'.join(texts).encode())
-        extra_name = m.hexdigest()
+        extra_name = '|'.join(qlcodegen.generate_source(e) for e in exprs)
     else:
         extra_name = None
 
@@ -341,11 +337,7 @@ def trace_View(
 def trace_Function(node: qlast.CreateFunction, *, ctx: DepTraceContext):
     # Functions are defined by their name + call signature, so we need
     # to add that to the "extra_name".
-    params = f'({qlcodegen.generate_source(node.params)})'
-    m = hashlib.sha1()
-    m.update(params.encode())
-    extra_name = m.hexdigest()
-
+    extra_name = f'({qlcodegen.generate_source(node.params)})'
     _register_item(node, ctx=ctx, extra_name=extra_name)
 
 


Test patch:
Repository: edgedb/edgedb

Issue:
Terminal detection is weird
While working on #857 I noticed that "script mode" is activated in a weird way:
```
> echo rollback | edgedb --admin
{}
> {sleep 1; echo rollback;} | edgedb --admin
Warning: Input is not to a terminal (fd=0).
EdgeDB 1.0-alpha.2+dev.261.g655230a2
Type "\?" for help.

edgedb> rollback 
.......                     
```
The code is basically:
```
        if select.select([sys.stdin], [], [], 0.0)[0]:
            # script mode
        else:
            # interactive mode
```

Usually, it's detected by `isatty` function? Are there any problems with it? Assuming that data is already in stdin isn't a good idea, as I've demonstrated above.

Also, I think that doing `sys.stdin.read()` (read until eof) in non-interactive mode isn't good, as pipelining should be supported too.

But at the end of the day is it worth fixing?


Discussion:
@elprans I think you had an explanation for why we want to use `select()` there.
Evidently this was added by me https://github.com/edgedb/edgedb/commit/7b1792857d124429b93cc2c3d9e2b08f73c0bfd2. :)

And also evidently postgres is using `isatty`.

So let's try to use `isatty` too. Paul, please submit a PR.

Resolving patch:
diff --git a/edb/repl/__init__.py b/edb/repl/__init__.py
--- a/edb/repl/__init__.py
+++ b/edb/repl/__init__.py
@@ -20,9 +20,7 @@
 from __future__ import annotations
 
 import functools
-import io
 import os
-import select
 import subprocess
 import sys
 
@@ -640,19 +638,6 @@ def execute_script(conn_args, data):
         con.close()
 
 
-def _data_in_stdin() -> str:
-    try:
-        if select.select([sys.stdin], [], [], 0.0)[0]:
-            data = sys.stdin.read()
-        else:
-            data = ''
-    except io.UnsupportedOperation:
-        # Mock stdin cannot be selected, just read it
-        data = sys.stdin.read()
-
-    return data
-
-
 def main(*, host, port, user, database, password, password_prompt, admin):
     connect_kwargs = {
         'user': user,
@@ -665,8 +650,13 @@ def main(*, host, port, user, database, password, password_prompt, admin):
         'timeout': 60,
     }
 
-    stdin_data = _data_in_stdin()
-    if stdin_data:
-        return execute_script(connect_kwargs, stdin_data)
-    else:
+    try:
+        interactive = sys.stdin.isatty()
+    except AttributeError:
+        # mock streams are always non-interactive
+        interactive = False
+
+    if interactive:
         return Cli(connect_kwargs).run()
+    else:
+        return execute_script(connect_kwargs, sys.stdin.read())


Test patch:
diff --git a/tests/test_type_coverage.py b/tests/test_type_coverage.py
--- a/tests/test_type_coverage.py
+++ b/tests/test_type_coverage.py
@@ -242,7 +242,7 @@ def test_cqa_type_coverage_pgsql_dbops(self) -> None:
         self.assertFunctionCoverage(EDB_DIR / "pgsql" / "dbops", 34.40)
 
     def test_cqa_type_coverage_repl(self) -> None:
-        self.assertFunctionCoverage(EDB_DIR / "repl", 22.08)
+        self.assertFunctionCoverage(EDB_DIR / "repl", 21.05)
 
     def test_cqa_type_coverage_schema(self) -> None:
         self.assertFunctionCoverage(EDB_DIR / "schema", 35.36)
Repository: edgedb/edgedb

Issue:
Profiler tests leak output in terse test mode
![Screenshot_20191125_183705](https://user-images.githubusercontent.com/347119/69587123-aed4d300-0fb2-11ea-9ac9-d24cdf9857de.png)



Discussion:

Resolving patch:
diff --git a/edb/tools/profiling.py b/edb/tools/profiling.py
--- a/edb/tools/profiling.py
+++ b/edb/tools/profiling.py
@@ -149,6 +149,7 @@ def aggregate(
         sort_by: str = "",
         width: int = 1920,
         threshold: float = 0.0001,  # 1.0 is 100%
+        quiet: bool = False,
     ) -> Tuple[int, int]:
         """Read all pstats in `self.dir` and write a summary to `out_path`.
 
@@ -163,6 +164,9 @@ def aggregate(
         Returns a tuple with number of successfully and unsucessfully
         aggregated files.
         """
+        if quiet:
+            print = lambda *args, **kwargs: None
+
         if not self.dir:
             with tempfile.NamedTemporaryFile() as tmp:
                 directory = pathlib.Path(tmp.name).parent


Test patch:
diff --git a/tests/test_profiling.py b/tests/test_profiling.py
--- a/tests/test_profiling.py
+++ b/tests/test_profiling.py
@@ -74,7 +74,9 @@ def profiled_function(arg):
 
         # aggregate the results
         out_file = ptest_files[0].with_suffix(".pstats")
-        success, failure = profiler.aggregate(out_file, sort_by="cumulative")
+        success, failure = profiler.aggregate(
+            out_file, sort_by="cumulative", quiet=True
+        )
 
         self.assertEqual(success, 1)
         self.assertEqual(failure, 0)
Repository: edgedb/edgedb

Issue:
Limit dollar $$ quoting syntax $$ to ascii idents



Discussion:

Resolving patch:
diff --git a/edb/edgeql/parser/grammar/lexer.py b/edb/edgeql/parser/grammar/lexer.py
--- a/edb/edgeql/parser/grammar/lexer.py
+++ b/edb/edgeql/parser/grammar/lexer.py
@@ -33,7 +33,7 @@
 STATE_BASE = 1
 
 
-re_dquote = r'\$([A-Za-z\200-\377_][0-9]*)*\$'
+re_dquote = r'\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$'
 
 Rule = lexer.Rule
 
diff --git a/edb/edgeql/pygments/__init__.py b/edb/edgeql/pygments/__init__.py
--- a/edb/edgeql/pygments/__init__.py
+++ b/edb/edgeql/pygments/__init__.py
@@ -113,7 +113,7 @@ class EdgeQLLexer(RegexLexer):
                 (?P<Q>
                     # capture the opening quote in group Q
                     (
-                        \$([A-Za-z\200-\377_][0-9]*)*\$
+                        \$(?:[A-Za-z_][A-Za-z_0-9]*)?\$
                     )
                 )
                 (?:


Test patch:
Repository: edgedb/edgedb

Issue:
Bad pretty printing of datetime
Here is what I get:
```
edgedb> SELECT <datetime>'2020-01-08T17:03:06.026178+00:00';
{<local_date>'2020-01-08T17:03:06.026178+00:00'}
```
Well the `datetime` in python is a subclass of `date` but `singledispatch` is supposed to handle that well. Do we have a patched singledispatch now?


Discussion:
UPDATE: Nevermind, I did it the wrong way round.
<details>
```
>>> issubclass(datetime.date, datetime.datetime)
False
```
</details>

I'm looking.

Resolving patch:
diff --git a/edb/repl/render_binary.py b/edb/repl/render_binary.py
--- a/edb/repl/render_binary.py
+++ b/edb/repl/render_binary.py
@@ -275,6 +275,7 @@ def _empty(
     buf.write('{}', style.bracket)
 
 
+@walk.register
 def _datetime(
     o: datetime.datetime,
     repl_ctx: context.ReplContext,


Test patch:
Repository: edgedb/edgedb

Issue:
Prohibit tuples as query arguments
Postgres does not support anonymous rowtypes as input, and there is no way to specify the tuple descriptor on the fly, so we have no choice but to inherit this limitation.


Discussion:
@elprans, how about I do this to kick the tires on EdgeQL?
@ambv Yes, this is a perfect type of an issue to start.
@ambv Are you still interested in working on this? If not, it would be a great introduction for me to learn about how query arguments are parsed. This would also be my first EdgeQL contribution.

Resolving patch:
diff --git a/edb/edgeql/compiler/expr.py b/edb/edgeql/compiler/expr.py
--- a/edb/edgeql/compiler/expr.py
+++ b/edb/edgeql/compiler/expr.py
@@ -412,6 +412,23 @@ def compile_TypeCast(
 
     elif isinstance(expr.expr, qlast.Parameter):
         pt = typegen.ql_typeexpr_to_type(expr.type, ctx=ctx)
+
+        if pt.is_tuple() or pt.is_anytuple():
+            raise errors.QueryError(
+                'cannot pass tuples as query parameters',
+                context=expr.expr.context,
+            )
+
+        if (
+            isinstance(pt, s_types.Collection)
+            and pt.contains_array_of_tuples(ctx.env.schema)
+        ):
+            raise errors.QueryError(
+                'cannot pass collections with tuple elements'
+                ' as query parameters',
+                context=expr.expr.context,
+            )
+
         param_name = expr.expr.name
         if param_name not in ctx.env.query_parameters:
             if ctx.env.query_parameters:


Test patch:
diff --git a/tests/test_edgeql_casts.py b/tests/test_edgeql_casts.py
--- a/tests/test_edgeql_casts.py
+++ b/tests/test_edgeql_casts.py
@@ -2237,3 +2237,31 @@ async def test_edgeql_casts_custom_scalar_01(self):
                 'invalid custom_str_t'):
             await self.con.fetchall(
                 "SELECT <test::custom_str_t>'123'")
+
+    async def test_edgeql_casts_prohibit_tuple_query_params_01(self):
+        with self.assertRaisesRegex(
+            edgedb.QueryError,
+            r'cannot pass tuples as query parameters',
+        ):
+            await self.con.fetchall(
+                r'''
+                WITH MODULE test
+                SELECT Test {
+                    id,
+                    num := (<tuple<int64, float64, str, bytes>>$tup).0,
+                    st := (<tuple<int64, float64, str, bytes>>$tup).2,
+                };
+                ''',
+                tup=(0, 1.0, "str", b"bytes"),
+            )
+
+    async def test_edgeql_casts_prohibit_tuple_query_params_02(self):
+        with self.assertRaisesRegex(
+            edgedb.QueryError,
+            r'cannot pass collections with tuple elements'
+            r' as query parameters',
+        ):
+            await self.con.fetchall(
+                r"SELECT <array<tuple<int64, str>>>$0;",
+                [(0, 'zero'), (1, 'one')],
+            )
Repository: edgedb/edgedb

Issue:
InternalServerError: 'NoneType' object has no attribute 'ptrref'
- EdgeDB Version: 1.0-alpha.3+dev.247.g04b74247

Steps to Reproduce:
Error occurs when a computed property has a link property path on a subquery, eg.

```
WITH MODULE schema
SELECT ObjectType {
  name,

  # error occurs with this line:
  annotationValues := (SELECT .annotations)@value

  # these are ok:
  # annotationValues := .annotations@value
  # annotationNames := (SELECT .annotations).name
  # annotationNames := .annotations.name
  
} FILTER EXISTS .annotations
```


Discussion:
`(SELECT .annotations)@value` should be a `ReferenceError`.  The only valid form of link property reference is `.link@prop`.

Resolving patch:
diff --git a/edb/edgeql/compiler/setgen.py b/edb/edgeql/compiler/setgen.py
--- a/edb/edgeql/compiler/setgen.py
+++ b/edb/edgeql/compiler/setgen.py
@@ -264,6 +264,13 @@ def compile_path(expr: qlast.Path, *, ctx: context.ContextLevel) -> irast.Set:
             if ptr_expr.type == 'property':
                 # Link property reference; the source is the
                 # link immediately preceding this step in the path.
+                if path_tip.rptr is None:
+                    raise errors.EdgeQLSyntaxError(
+                        f"unexpected reference to link property {ptr_name!r} "
+                        "outside of a path expression",
+                        context=ptr_expr.ptr.context,
+                    )
+
                 if isinstance(path_tip.rptr.ptrref,
                               irast.TypeIntersectionPointerRef):
                     ind_prefix, ptrs = typegen.collapse_type_intersection_rptr(


Test patch:
diff --git a/tests/test_edgeql_select.py b/tests/test_edgeql_select.py
--- a/tests/test_edgeql_select.py
+++ b/tests/test_edgeql_select.py
@@ -4884,6 +4884,34 @@ async def test_edgeql_select_linkproperty_03(self):
             }],
         )
 
+    async def test_edgeql_select_linkproperty_04(self):
+        with self.assertRaisesRegex(
+            edgedb.EdgeQLSyntaxError,
+            "unexpected reference to link property 'since' "
+            "outside of a path expression",
+        ):
+            await self.con.execute(
+                r'''
+                WITH MODULE test
+                SELECT
+                    Issue { since := (SELECT .owner)@since }
+                ''',
+            )
+
+    async def test_edgeql_select_linkproperty_05(self):
+        with self.assertRaisesRegex(
+            edgedb.EdgeQLSyntaxError,
+            "unexpected reference to link property 'since' "
+            "outside of a path expression",
+        ):
+            await self.con.execute(
+                r'''
+                WITH MODULE test
+                SELECT
+                    Issue { since := [.owner]@since }
+                ''',
+            )
+
     async def test_edgeql_select_if_else_01(self):
         await self.assert_query_result(
             r"""
Repository: edgedb/edgedb

Issue:
DDL results in SQL syntax error
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: EdgeDB 1.0-alpha.4+dev.130.g9e96c03f
- OS Version: LInux

Steps to Reproduce:

Try this in REPL:
```
CREATE TYPE Foo {CREATE LINK left -> Foo};
```

I get an error:
```
  Server traceback:
      edb.errors.InternalServerError: syntax error at or near "left"
```

Note that this also happens for `rgiht`. It appears that the identifier `left` is not quoted and clashes with a SQL keyword.


Discussion:
`needs_quoting` in `pgsql/common.py` needs to be updated to always quote all keywords except `UNRESERVED_KEYWORD`.

Resolving patch:
diff --git a/edb/pgsql/common.py b/edb/pgsql/common.py
--- a/edb/pgsql/common.py
+++ b/edb/pgsql/common.py
@@ -81,7 +81,10 @@ def needs_quoting(string):
                string.replace('_', 'a').isalnum())
     return (
         not isalnum or
-        string.lower() in pg_keywords.by_type[pg_keywords.RESERVED_KEYWORD] or
+        string.lower() in pg_keywords.by_type[
+            pg_keywords.RESERVED_KEYWORD] or
+        string.lower() in pg_keywords.by_type[
+            pg_keywords.TYPE_FUNC_NAME_KEYWORD] or
         string.lower() != string
     )
 


Test patch:
diff --git a/tests/test_edgeql_ddl.py b/tests/test_edgeql_ddl.py
--- a/tests/test_edgeql_ddl.py
+++ b/tests/test_edgeql_ddl.py
@@ -879,6 +879,21 @@ async def test_edgeql_ddl_26(self):
                 ALTER TYPE Child ALTER LINK target DROP OWNED;
             """)
 
+    async def test_edgeql_ddl_27(self):
+        # Test that identifiers that are SQL keywords get quoted.
+        # Issue 1667
+        await self.con.execute("""
+            CREATE TYPE test::Foo {
+                CREATE PROPERTY left -> str;
+                CREATE PROPERTY smallint -> str;
+                CREATE PROPERTY natural -> str;
+                CREATE PROPERTY null -> str;
+                CREATE PROPERTY `like` -> str;
+                CREATE PROPERTY `create` -> str;
+                CREATE PROPERTY `link` -> str;
+            };
+        """)
+
     async def test_edgeql_ddl_default_01(self):
         with self.assertRaisesRegex(
                 edgedb.SchemaDefinitionError,
Repository: edgedb/edgedb

Issue:
Incorrect code generated for nested inserts from a default
Per @vpetrovykh:

```
EdgeDB 1.0-alpha.6+dev.5035.g8a51fcae
Type "\?" for help.
victor> create module test;
OK: CREATE
victor>             CREATE TYPE test::TestDefaultInsert03;
....... 
.......             CREATE TYPE test::TestDefault03 {
.......                 CREATE LINK def03 -> test::TestDefaultInsert03 {
.......                     SET default := (INSERT test::TestDefaultInsert03);
.......                 };
.......             };
OK: CREATE
OK: CREATE
victor> INSERT test::TestDefault03;
{Object {id: 978c6de2-e951-11ea-92ce-77bf9238bc18, def03: Object {id: 978c7242-e951-11ea-92ce-e7bd34764008}}}
victor> SELECT test::TestDefaultInsert03;
{Object {id: 978c19f0-e951-11ea-92ce-cfa17b564165}, Object {id: 978c7242-e951-11ea-92ce-e7bd34764008}}
```


Note: this only happens when `output_format` is not `SCRIPT` (i.e. in `query()`, not `execute()`).


Discussion:
Relevant tests added in #1719

Resolving patch:
diff --git a/edb/edgeql/compiler/context.py b/edb/edgeql/compiler/context.py
--- a/edb/edgeql/compiler/context.py
+++ b/edb/edgeql/compiler/context.py
@@ -381,6 +381,7 @@ class ContextLevel(compiler.ContextLevel):
     shape_type_cache: Dict[
         Tuple[
             s_objtypes.ObjectType,
+            bool, bool, bool,
             Tuple[qlast.ShapeElement, ...],
         ],
         s_objtypes.ObjectType,
diff --git a/edb/edgeql/compiler/viewgen.py b/edb/edgeql/compiler/viewgen.py
--- a/edb/edgeql/compiler/viewgen.py
+++ b/edb/edgeql/compiler/viewgen.py
@@ -70,7 +70,7 @@ def process_view(
     ctx: context.ContextLevel,
 ) -> s_objtypes.ObjectType:
 
-    cache_key = (stype, tuple(elements))
+    cache_key = (stype, is_insert, is_update, is_delete, tuple(elements))
     view_scls = ctx.shape_type_cache.get(cache_key)
     if view_scls is not None:
         return view_scls


Test patch:
diff --git a/tests/test_edgeql_ddl.py b/tests/test_edgeql_ddl.py
--- a/tests/test_edgeql_ddl.py
+++ b/tests/test_edgeql_ddl.py
@@ -1059,11 +1059,6 @@ async def test_edgeql_ddl_default_02(self):
                 };
             """)
 
-    @test.xfail('''
-        Issue #1721
-
-        Two TestDefaultInsert03 objects are created instead of one.
-    ''')
     async def test_edgeql_ddl_default_03(self):
         # Test INSERT as default link expression
         await self.con.execute(r"""
diff --git a/tests/test_edgeql_insert.py b/tests/test_edgeql_insert.py
--- a/tests/test_edgeql_insert.py
+++ b/tests/test_edgeql_insert.py
@@ -1336,6 +1336,15 @@ async def test_edgeql_insert_default_05(self):
             {1, 2, 3}
         )
 
+    async def test_edgeql_insert_default_06(self):
+        res = await self.con.query(r'''
+            INSERT test::DefaultTest1;
+        ''')
+        assert len(res) == 1
+        obj = res[0]
+        # The result should not include the default param
+        assert not hasattr(obj, 'num')
+
     async def test_edgeql_insert_as_expr_01(self):
         await self.con.execute(r'''
             # insert several objects, then annotate one of the inserted batch