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

Issue:
Order matters for functions in SDL
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: `1.0-alpha.4+dev.116.g83e9f530`

Steps to Reproduce:

```edgeql
ROLLBACK;
START TRANSACTION;
START MIGRATION TO {
    module default {
        function b() -> int64 {
            using EdgeQL $$
                SELECT a()
            $$
        }
        function a() -> int64 {
            using EdgeQL $$
                SELECT 1
            $$
        }
    }
};
```
Causes `ERROR: InvalidReferenceError: function 'a' does not exist`

This does not happen if you swap function positions.




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
@@ -42,6 +42,7 @@
 
 from edb.edgeql import ast as qlast
 from edb.edgeql import codegen as qlcodegen
+from edb.edgeql import parser as qlparser
 from edb.edgeql import tracer as qltracer
 
 from edb.schema import name as s_name
@@ -480,6 +481,11 @@ def trace_Function(node: qlast.CreateFunction, *, ctx: DepTraceContext):
 
     if node.nativecode is not None:
         deps.append((node.nativecode, params))
+    elif (node.code is not None
+            and node.code.language is qlast.Language.EdgeQL
+            and node.code.code):
+        # Need to parse the actual code string and use that as the dependency.
+        deps.append((qlparser.parse(node.code.code), params))
 
     # XXX: hard_dep_expr is used because it ultimately calls the
     # _get_hard_deps helper that extracts the proper dependency list


Test patch:
diff --git a/tests/test_schema.py b/tests/test_schema.py
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -1840,6 +1840,26 @@ def test_schema_get_migration_33(self):
 
         self._assert_migration_consistency(schema)
 
+    def test_schema_get_migration_34(self):
+        # Make sure that awkward order of function definitions doesn't
+        # affect the migraiton.
+        #
+        # Issue #1649.
+        schema = r'''
+        function b() -> int64 {
+            using EdgeQL $$
+                SELECT a()
+            $$
+        }
+        function a() -> int64 {
+            using EdgeQL $$
+                SELECT 1
+            $$
+        }
+        '''
+
+        self._assert_migration_consistency(schema)
+
     def test_schema_get_migration_multi_module_01(self):
         schema = r'''
             # The two declared types declared are from different
Repository: edgedb/edgedb

Issue:
ISE when LIMIT/OFFSET correlated with query
```
sully> SELECT Object LIMIT len(<str>.id);
ERROR: InternalServerError: argument of LIMIT must not contain variables
```

```
sully> SELECT Object OFFSET len(<str>.id);
ERROR: InternalServerError: argument of OFFSET must not contain variables
```

Rejecting these is correct but we want a real error.



Discussion:

Resolving patch:
diff --git a/edb/edgeql/compiler/clauses.py b/edb/edgeql/compiler/clauses.py
--- a/edb/edgeql/compiler/clauses.py
+++ b/edb/edgeql/compiler/clauses.py
@@ -125,6 +125,10 @@ def compile_limit_offset_clause(
         ir_set = None
     else:
         with ctx.newscope(fenced=True) as subctx:
+            # Clear out the partial_path_prefix, since we aren't in
+            # the scope of the select subject
+            subctx.partial_path_prefix = None
+
             ir_expr = dispatch.compile(expr, ctx=subctx)
             int_t = ctx.env.get_track_schema_type('std::int64')
             ir_set = setgen.scoped_set(


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
@@ -1253,6 +1253,30 @@ async def test_edgeql_select_limit_07(self):
                 OFFSET <int64>User.<owner[IS Issue].number;
             """)
 
+    async def test_edgeql_select_limit_08(self):
+        with self.assertRaisesRegex(
+                edgedb.QueryError,
+                r'could not resolve partial path'):
+
+            await self.con.query("""
+                WITH MODULE test
+                SELECT
+                    User { name }
+                LIMIT <int64>.<owner[IS Issue].number;
+            """)
+
+    async def test_edgeql_select_limit_09(self):
+        with self.assertRaisesRegex(
+                edgedb.QueryError,
+                r'could not resolve partial path'):
+
+            await self.con.query("""
+                WITH MODULE test
+                SELECT
+                    User { name }
+                OFFSET <int64>.<owner[IS Issue].number;
+            """)
+
     async def test_edgeql_select_polymorphic_01(self):
         await self.assert_query_result(
             r'''
Repository: edgedb/edgedb

Issue:
InternalServerError: cannot describe type default::User
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: Docker: `1.0a4-2020071615~buster`

Steps to Reproduce:

Run: ` SELECT <array<User>>{};`

<!-- If the issue is about a query error, please also provide your schema -->
Schema:
```esdl
type User {
            required property nickname -> str;
            required property email -> str;
            required property email_verified -> bool {
                default := false;
            };
            required property password -> bytes;
            required property created_at -> datetime {
                default := datetime_current();
            };
        };
```


Discussion:

Resolving patch:
diff --git a/edb/server/compiler/sertypes.py b/edb/server/compiler/sertypes.py
--- a/edb/server/compiler/sertypes.py
+++ b/edb/server/compiler/sertypes.py
@@ -33,6 +33,7 @@
 
 from edb.schema import links as s_links
 from edb.schema import objects as s_obj
+from edb.schema import objtypes as s_objtypes
 from edb.schema import scalars as s_scalars
 from edb.schema import types as s_types
 
@@ -205,7 +206,7 @@ def _describe_type(self, t, view_shapes, view_shapes_metadata,
         elif isinstance(t, s_types.Collection):
             raise errors.SchemaError(f'unsupported collection type {t!r}')
 
-        elif view_shapes.get(t):
+        elif isinstance(t, s_objtypes.ObjectType):
             # This is a view
             self.schema, mt = t.material_type(self.schema)
             base_type_id = mt.id
@@ -218,7 +219,7 @@ def _describe_type(self, t, view_shapes, view_shapes_metadata,
             metadata = view_shapes_metadata.get(t)
             implicit_id = metadata is not None and metadata.has_implicit_id
 
-            for ptr in view_shapes[t]:
+            for ptr in view_shapes.get(t, ()):
                 if ptr.singular(self.schema):
                     if isinstance(ptr, s_links.Link) and not follow_links:
                         subtype_id = self._describe_type(


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
@@ -2464,3 +2464,11 @@ async def test_edgeql_casts_prohibit_tuple_query_params_02(self):
                 r"SELECT <array<tuple<int64, str>>>$0;",
                 [(0, 'zero'), (1, 'one')],
             )
+
+    async def test_edgeql_cast_empty_set_to_array_01(self):
+        await self.assert_query_result(
+            r'''
+                SELECT <array<Object>>{};
+            ''',
+            [],
+        )
Repository: edgedb/edgedb

Issue:
ISE when doing `SET` on an invalid proprety
`CREATE TYPE Lol { SET ha := "crash"; };`
produces
```
ERROR: InternalServerError: schema class 'ObjectType' has no field 'ha'
  Hint: This is most likely a bug in EdgeDB. Please consider opening an issue ticket at https://github.com/edgedb/edgedb/issues/new?template=bug_report.md
```
Same story with migrations;

The error does, tbh, make it pretty clear what the problem is, but we ought to produce a real error.


Discussion:
`errors.InvalidDefinitionError` should be good enough

Resolving patch:
diff --git a/edb/schema/delta.py b/edb/schema/delta.py
--- a/edb/schema/delta.py
+++ b/edb/schema/delta.py
@@ -3524,7 +3524,12 @@ def regular_cmd_from_ast(
         ):
             return Nop()
         else:
-            field = parent_cls.get_field(propname)
+            try:
+                field = parent_cls.get_field(propname)
+            except LookupError:
+                raise errors.SchemaDefinitionError(
+                    f'{propname!r} is not a valid field',
+                    context=astnode.context)
 
         if not (
             astnode.special_syntax


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
@@ -9009,6 +9009,28 @@ async def test_edgeql_ddl_drop_field_03(self):
                 INSERT Foo;
             """)
 
+    async def test_edgeql_ddl_bad_field_01(self):
+        async with self.assertRaisesRegexTx(
+            edgedb.SchemaDefinitionError,
+            "'ha' is not a valid field",
+        ):
+            await self.con.execute(r"""
+                CREATE TYPE test::Lol {SET ha := "crash"};
+            """)
+
+    async def test_edgeql_ddl_bad_field_02(self):
+        async with self.assertRaisesRegexTx(
+            edgedb.SchemaDefinitionError,
+            "'ha' is not a valid field",
+        ):
+            await self.con.execute(r"""
+                START MIGRATION TO {
+                    type test::Lol {
+                        ha := "crash"
+                    }
+                }
+            """)
+
     async def test_edgeql_ddl_adjust_computed_01(self):
         await self.con.execute(r"""
             SET MODULE test;
Repository: edgedb/edgedb

Issue:
Better syntax errors for substitution tokens
Currently as of 1.0-alpha.8+dev.5341.g66ec73494 it fails with InternalServerError:
```
edgedb> SELECT \(x);
ERROR: InternalServerError: (<class 'edb.edgeql.parser.grammar.tokens.TokenMeta'>, 'SUBSTITUTION')
  Hint: This is most likely a bug in EdgeDB. Please consider opening an issue ticket at https://github.com/edgedb/edgedb/issues/new?template=bug_report.md
  Server traceback:
      Traceback (most recent call last):
        File "/work/edb/server/procpool/worker.py", line 75, in worker
          res = await meth(*args)
        File "/work/edb/server/compiler/compiler.py", line 1935, in compile
          return self._compile(ctx=ctx, source=source)
        File "/work/edb/server/compiler/compiler.py", line 1487, in _compile
          return self._try_compile(ctx=ctx, source=source)
        File "/work/edb/server/compiler/compiler.py", line 1519, in _try_compile
          statements = edgeql.parse_block(source)
        File "/work/edb/edgeql/parser/__init__.py", line 69, in parse_block
          return parser.parse(source)
        File "/work/edb/common/parsing.py", line 401, in parse
          token = self.process_lex_token(mod, tok)
        File "/work/edb/common/parsing.py", line 390, in process_lex_token
          return mod.TokenMeta.for_lex_token(tok.kind())(
        File "/work/edb/common/parsing.py", line 100, in for_lex_token
          return mcls.token_map[mcls, token]
      KeyError: (<class 'edb.edgeql.parser.grammar.tokens.TokenMeta'>, 'SUBSTITUTION')
```
This bug appeared after #2131 


Discussion:
Yeah, you need to add a matching declaration to edgeql/parser/grammar/tokens.py

Resolving patch:
diff --git a/edb/edgeql/parser/grammar/tokens.py b/edb/edgeql/parser/grammar/tokens.py
--- a/edb/edgeql/parser/grammar/tokens.py
+++ b/edb/edgeql/parser/grammar/tokens.py
@@ -219,6 +219,10 @@ class T_OP(Token):
     pass
 
 
+class T_SUBSTITUTION(Token):
+    pass
+
+
 class T_EOF(Token):
     pass
 


Test patch:
Repository: edgedb/edgedb

Issue:
Migrations don't work with multiple indexes
When running this:
```
start migration to {                                                      
module default {                                                          
type Message {                                                            
    required property text -> str;                                        
    required property ts -> datetime;                                     
    index on (.ts);                                                       
    index on (.text);                                                     
};                                                                        
                                                                          
}                                                                         
};                                                                        
POPULATE MIGRATION; DESCRIBE CURRENT MIGRATION; COMMIT MIGRATION;
```

We get back:
```
CREATE TYPE default::Message {
    CREATE REQUIRED PROPERTY text -> std::str;
    CREATE INDEX ON (.text);
    CREATE REQUIRED PROPERTY ts -> std::datetime;
};
```
which is missing one of the indexes!


Discussion:
Oh, no, and what is worse, if I go manually add the index with DDL, and run the migration again, it tries to delete 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
@@ -181,6 +181,11 @@ def get_fq_name(
 
             extra_name = '|'.join(qlcodegen.generate_source(e) for e in exprs)
 
+        elif isinstance(decl, qlast.CreateIndex):
+            # Indexes are defined by what they are an index over, so we need
+            # to add that to the "extra_name".
+            extra_name = f'({qlcodegen.generate_source(decl.expr)})'
+
         if extra_name:
             fq_name = s_name.QualName(
                 module=fq_name.module,


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
@@ -4707,6 +4707,31 @@ async def test_edgeql_migration_eq_43(self):
         """)
         await self.migrate(r"")
 
+    async def test_edgeql_migration_index_01(self):
+        await self.migrate('''
+            type Message {
+                required property text -> str;
+                index on (.text);
+            };
+        ''')
+
+        await self.migrate('''
+            type Message {
+                required property text -> str;
+                required property ts -> datetime;
+                index on (.text);
+                index on (.ts);
+            };
+        ''')
+
+        await self.assert_query_result(
+            r"""
+                SELECT count((SELECT schema::ObjectType
+                              FILTER .name = 'test::Message').indexes)
+            """,
+            [2],
+        )
+
     async def test_edgeql_migration_eq_function_01(self):
         await self.migrate(r"""
             function hello01(a: int64) -> str
Repository: edgedb/edgedb

Issue:
ISE on empty set within set literal
- EdgeDB Version: `1.0-alpha.8+dev.5351.g93a3c34c4.d20210126`

Repro:

```
SELECT {False, <bool>{}};
```




Discussion:

Resolving patch:
diff --git a/edb/ir/staeval.py b/edb/ir/staeval.py
--- a/edb/ir/staeval.py
+++ b/edb/ir/staeval.py
@@ -166,20 +166,32 @@ def evaluate_OperatorCall(
 
 def _evaluate_union(
         opcall: irast.OperatorCall,
-        schema: s_schema.Schema) -> irast.ConstantSet:
+        schema: s_schema.Schema) -> irast.ConstExpr:
 
-    elements: List[irast.ConstExpr] = []
+    elements: List[irast.BaseConstant] = []
     for arg in opcall.args:
         val = evaluate(arg.expr, schema=schema)
         if isinstance(val, irast.ConstantSet):
             elements.extend(val.elements)
-        else:
+        elif isinstance(val, irast.EmptySet):
+            empty_set = val
+        elif isinstance(val, irast.BaseConstant):
             elements.append(val)
+        else:
+            raise UnsupportedExpressionError(
+                f'{val!r} not supported in UNION',
+                context=opcall.context)
 
-    return irast.ConstantSet(
-        elements=tuple(elements),
-        typeref=next(iter(elements)).typeref,
-    )
+    if elements:
+        return irast.ConstantSet(
+            elements=tuple(elements),
+            typeref=next(iter(elements)).typeref,
+        )
+    else:
+        # We get an empty set if the UNION was exclusivly empty set
+        # literals. If that happens, grab one of the empty sets
+        # that we saw and return it.
+        return empty_set
 
 
 @functools.singledispatch


Test patch:
diff --git a/tests/test_edgeql_expressions.py b/tests/test_edgeql_expressions.py
--- a/tests/test_edgeql_expressions.py
+++ b/tests/test_edgeql_expressions.py
@@ -257,6 +257,27 @@ async def test_edgeql_expr_emptyset_04(self):
             [2],
         )
 
+    async def test_edgeql_expr_emptyset_05(self):
+        await self.assert_query_result(
+            r'''SELECT {False, <bool>{}};''',
+            [False],
+        )
+
+        await self.assert_query_result(
+            r'''SELECT {False, {False, <bool>{}}};''',
+            [False, False],
+        )
+
+        await self.assert_query_result(
+            r'''SELECT {<bool>{}, <bool>{}};''',
+            [],
+        )
+
+        await self.assert_query_result(
+            r'''SELECT {False, {<bool>{}, <bool>{}}};''',
+            [False],
+        )
+
     async def test_edgeql_expr_idempotent_01(self):
         await self.assert_query_result(
             r"""
Repository: edgedb/edgedb

Issue:
Inconsistent handling of `{}` by the `IF` operator
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: 1.0-beta.2+dev.5580.ge5414991c 
- OS Version: Linux

Steps to Reproduce:

```
db> CREATE TYPE Foo { CREATE PROPERTY opt -> int64; CREATE REQUIRED PROPERTY val -> str; };
OK: CREATE TYPE
db> INSERT Foo {val := 'a'};
{default::Foo {id: da4de6e0-9ede-11eb-bbd8-f7d69321c5d6}}
db> INSERT Foo {val := 'b', opt := 111};
{default::Foo {id: e1d0fef2-9ede-11eb-bbd8-1fcfa95ddf34}}
db> SELECT Foo.val;
{'a', 'b'}
db> SELECT Foo.opt;
{111}
db> WITH 
...   a := (SELECT Foo FILTER .val = 'a'),
...   b := (SELECT Foo FILTER .val = 'b'),
... SELECT a.opt < b.opt;
{}
db> WITH 
...   a := (SELECT Foo FILTER .val = 'a'),
...   b := (SELECT Foo FILTER .val = 'b'),
... SELECT a.val IF a.opt < b.opt ELSE b.val;
{'b'}
db> WITH 
...   a := (SELECT Foo FILTER .val = 'a'),
...   b := (SELECT Foo FILTER .val = 'b'),
... SELECT a.val IF <int64>{} < 111 ELSE b.val;
{}
db> WITH 
...   a := (SELECT Foo FILTER .val = 'a'),
...   b := (SELECT Foo FILTER .val = 'b'),
...   c := <int64>{},
...   d := 111,
... SELECT a.val IF c < d ELSE b.val;
{}
```
The problem is that the query `SELECT a.val IF a.opt < b.opt ELSE b.val;` should be returning `{}` by our rules, but does not, while very similar expressions (involving the same values) correctly return `{}`.




Discussion:

Resolving patch:
diff --git a/edb/pgsql/compiler/relgen.py b/edb/pgsql/compiler/relgen.py
--- a/edb/pgsql/compiler/relgen.py
+++ b/edb/pgsql/compiler/relgen.py
@@ -1424,12 +1424,14 @@ def process_set_as_ifelse(
 
         rvar = pathctx.get_path_value_var(
             stmt, path_id=ir_set.path_id, env=ctx.env)
-        stmt.where_clause = astutils.extend_binop(
-            stmt.where_clause,
-            pgast.NullTest(
-                arg=rvar, negated=True
+        # We need to NULL filter both the result and the input condition
+        for var in [rvar, condref]:
+            stmt.where_clause = astutils.extend_binop(
+                stmt.where_clause,
+                pgast.NullTest(
+                    arg=var, negated=True
+                )
             )
-        )
 
     else:
         with ctx.subrel() as _, _.newscope() as subctx:


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
@@ -5370,6 +5370,17 @@ async def test_edgeql_select_if_else_06(self):
             [{'number': '1'}, {'number': '3'}, {'number': '4'}],
         )
 
+    async def test_edgeql_select_if_else_07(self):
+        await self.assert_query_result(
+            r'''
+            WITH MODULE test,
+                 a := (SELECT Issue FILTER .number = '2'),
+                 b := (SELECT Issue FILTER .number = '1'),
+            SELECT a.number IF a.time_estimate < b.time_estimate ELSE b.number;
+            ''',
+            [],
+        )
+
     async def test_edgeql_partial_01(self):
         await self.assert_query_result(
             '''
Repository: edgedb/edgedb

Issue:
Computable property fails in polymorphic query with `WITH` block
- EdgeDB Version: 1.0-beta.3+dev5706.d2021070612.gbeb025efc.cv202107020000

Steps to Reproduce:

```
edgedb> select HasImage {
.......   avg_rating := [is Movie].avg_rating
....... };
{}

edgedb> with rows := (select HasImage)
....... select rows {
.......   avg_rating := [is Movie].avg_rating
....... };
error: 'default::Movie & default::HasImage.<movie' does not resolve to any known path
```

Schema:
```
module default {
  abstract type HasImage {
    required property image -> str;
  };

  type Movie extending HasImage {
    property avg_rating := (math::mean(.<movie[is Review].rating));
  };

  type Review {
    required link movie -> Movie;
    required property rating -> int64;
  }
}
```



Discussion:
```
select (select HasImage { lol := 1 }) {                                   
    avg_rating := [is Movie].avg_rating                                   
};
```
also fails

Resolving patch:
diff --git a/edb/schema/objtypes.py b/edb/schema/objtypes.py
--- a/edb/schema/objtypes.py
+++ b/edb/schema/objtypes.py
@@ -171,6 +171,9 @@ def getrptrs(
                 )
             )
 
+        for intersection in self.get_intersection_of(schema).objects(schema):
+            ptrs.update(intersection.getrptrs(schema, name, sources=sources))
+
         unions = schema.get_referrers(
             self, scls_type=ObjectType, field_name='union_of')
 


Test patch:
diff --git a/tests/test_edgeql_scope.py b/tests/test_edgeql_scope.py
--- a/tests/test_edgeql_scope.py
+++ b/tests/test_edgeql_scope.py
@@ -2357,6 +2357,34 @@ async def test_edgeql_scope_computables_11c(self):
             ],
         )
 
+    async def test_edgeql_scope_computables_12(self):
+        await self.assert_query_result(
+            r"""
+                WITH rows := Named,
+                SELECT rows {
+                    name, owner_count := count([IS Card].owners)
+                } FILTER .name IN {'1st', 'Alice', 'Dwarf'} ORDER BY .name;
+            """,
+            [
+                {"name": "1st", "owner_count": 0},
+                {"name": "Alice", "owner_count": 0},
+                {"name": "Dwarf", "owner_count": 2}
+            ]
+        )
+
+        await self.assert_query_result(
+            r"""
+                SELECT (Named { name }) {
+                    name, owner_count := count([IS Card].owners)
+                } FILTER .name IN {'1st', 'Alice', 'Dwarf'} ORDER BY .name;
+            """,
+            [
+                {"name": "1st", "owner_count": 0},
+                {"name": "Alice", "owner_count": 0},
+                {"name": "Dwarf", "owner_count": 2}
+            ]
+        )
+
     async def test_edgeql_scope_with_01(self):
         # Test that same symbol can be re-used in WITH block.
         await self.assert_query_result(