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

Issue:
InvalidReferenceError: object type '__derived__::(default:X | default:Y)' does not exist
- EdgeDB Version: 2.0-dev.6375+75976cc

Subquery on link where target is union type fails with `InvalidReferenceError` if link is aliased in 'with' block:
```
select Z {
  xy := (
    select .xy { a }
  )
}
# This works 

select Z {
  xy := (
    with _scope := .xy
    select _scope { a }
  )
}
# InvalidReferenceError: object type '__derived__::(default:X | default:Y)' does not exist
```

Schema:
```
type X {
  property a -> str;
}
type Y {
  property a -> str;
}
type Z {
  link xy -> X | Y;
}
```



Discussion:
Simpler query that returns same error:
```
with _scope := Z.xy
select _scope
```

Resolving patch:
diff --git a/edb/schema/types.py b/edb/schema/types.py
--- a/edb/schema/types.py
+++ b/edb/schema/types.py
@@ -431,7 +431,10 @@ def as_shell(
     ) -> TypeShell[TypeT]:
         name = typing.cast(s_name.QualName, self.get_name(schema))
 
-        if union_of := self.get_union_of(schema):
+        if (
+            (union_of := self.get_union_of(schema))
+            and not self.is_view(schema)
+        ):
             assert isinstance(self, so.QualifiedObject)
             return UnionTypeShell(
                 components=[
@@ -441,7 +444,10 @@ def as_shell(
                 opaque=self.get_is_opaque_union(schema),
                 schemaclass=type(self),
             )
-        elif intersection_of := self.get_intersection_of(schema):
+        elif (
+            (intersection_of := self.get_intersection_of(schema))
+            and not self.is_view(schema)
+        ):
             assert isinstance(self, so.QualifiedObject)
             return IntersectionTypeShell(
                 components=[


Test patch:
diff --git a/tests/test_edgeql_advtypes.py b/tests/test_edgeql_advtypes.py
--- a/tests/test_edgeql_advtypes.py
+++ b/tests/test_edgeql_advtypes.py
@@ -315,3 +315,17 @@ async def test_edgeql_advtypes_intersection_with_comp(self):
             """,
             ['aaa'],
         )
+
+    async def test_edgeql_advtypes_intersection_alias(self):
+        await self.con.execute("""
+            INSERT S { name := 'aaa', s := '' };
+            INSERT Z { name := 'lol', stw0 := S };
+        """)
+
+        await self.assert_query_result(
+            """
+            WITH X := Z.stw0
+            SELECT X { name }
+            """,
+            [{'name': 'aaa'}],
+        )
Repository: edgedb/edgedb

Issue:
ISE if index expression has a cast
```
edgedb> create type Artist { create property oid -> bigint; create index on (<str>.oid) };
Error: InternalServerError: syntax error at or near "::"
```

This is because the underlying `CREATE INDEX` is generated as follows:

```
CREATE INDEX "b6GKl3sIRH/PYIKyIki7qQ:11ec-9ea6-4df84086378a_index" ON edgedbpub."9790a99b-cb25-11ec-9c22-c31f3cc13b16" (("97935a4f-cb25-11ec-9573-010d1def5538")::text NULLS FIRST);
ERROR:  syntax error at or near "::"
```

This is fixed by adding a set of paretheses around the index expression.


Discussion:

Resolving patch:
diff --git a/edb/pgsql/dbops/indexes.py b/edb/pgsql/dbops/indexes.py
--- a/edb/pgsql/dbops/indexes.py
+++ b/edb/pgsql/dbops/indexes.py
@@ -93,7 +93,7 @@ def creation_code(self, block: base.PLBlock) -> str:
             exprs = [qi(c) for c in self.columns]
 
         # TODO: Make NULLs behavior configurable
-        expr = ', '.join(f'{e} NULLS FIRST' for e in exprs)
+        expr = ', '.join(f'({e}) NULLS FIRST' for e in exprs)
 
         code = '''
             CREATE {unique} INDEX {name}


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
@@ -11014,6 +11014,14 @@ async def test_edgeql_ddl_index_04(self):
                 };
             """)
 
+    async def test_edgeql_ddl_index_05(self):
+        await self.con.execute(r"""
+            create type Artist {
+                create property oid -> bigint;
+                create index on (<str>.oid)
+            };
+        """)
+
     async def test_edgeql_ddl_errors_01(self):
         await self.con.execute('''
             CREATE TYPE Err1 {
Repository: edgedb/edgedb

Issue:
ISE when casting a "null" JSON value to `std::bigint`.
```
select <bigint>to_json('null');
```

```
edgedb error: InternalServerError: RAISE statement option cannot be null
  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:
      edb.errors.InternalServerError: RAISE statement option cannot be null
```


Discussion:

Resolving patch:
diff --git a/edb/buildmeta.py b/edb/buildmeta.py
--- a/edb/buildmeta.py
+++ b/edb/buildmeta.py
@@ -44,7 +44,7 @@
 
 
 # Increment this whenever the database layout or stdlib changes.
-EDGEDB_CATALOG_VERSION = 2022_05_03_00_00
+EDGEDB_CATALOG_VERSION = 2022_05_05_00_00
 EDGEDB_MAJOR_VERSION = 2
 
 
diff --git a/edb/pgsql/metaschema.py b/edb/pgsql/metaschema.py
--- a/edb/pgsql/metaschema.py
+++ b/edb/pgsql/metaschema.py
@@ -526,6 +526,7 @@ def __init__(self) -> None:
             returns=('edgedb', 'bigint_t'),
             # Stable because it's raising exceptions.
             volatility='stable',
+            strict=True,
             text=self.text)
 
 
@@ -559,6 +560,7 @@ def __init__(self) -> None:
             returns=('numeric',),
             # Stable because it's raising exceptions.
             volatility='stable',
+            strict=True,
             text=self.text,
         )
 


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
@@ -2371,6 +2371,34 @@ async def test_edgeql_casts_json_13(self):
             [],
         )
 
+        await self.assert_query_result(
+            r'''
+                select <bigint>to_json('null')
+            ''',
+            [],
+        )
+
+        await self.assert_query_result(
+            r'''
+                select <decimal>to_json('null')
+            ''',
+            [],
+        )
+
+        await self.assert_query_result(
+            r'''
+                select <bigint><str>to_json('null')
+            ''',
+            [],
+        )
+
+        await self.assert_query_result(
+            r'''
+                select <decimal><str>to_json('null')
+            ''',
+            [],
+        )
+
     async def test_edgeql_casts_assignment_01(self):
         async with self._run_and_rollback():
             await self.con.execute(r"""
Repository: edgedb/edgedb

Issue:
Casts from json can produce empty values but card inference doesn't understand
For example:
```
edgedb> select { required z := <str>to_json('null') };
[{"z": null}]
```

(Prompted by https://github.com/edgedb/edgedb/issues/3793)


Discussion:

Resolving patch:
diff --git a/edb/edgeql/compiler/inference/cardinality.py b/edb/edgeql/compiler/inference/cardinality.py
--- a/edb/edgeql/compiler/inference/cardinality.py
+++ b/edb/edgeql/compiler/inference/cardinality.py
@@ -840,9 +840,17 @@ def __infer_typecast(
     scope_tree: irast.ScopeTreeNode,
     ctx: inference_context.InfCtx,
 ) -> qltypes.Cardinality:
-    return infer_cardinality(
+    card = infer_cardinality(
         ir.expr, scope_tree=scope_tree, ctx=ctx,
     )
+    # json values can be 'null', which produces an empty set, which we
+    # need to reflect in the cardinality.
+    if (
+        typeutils.is_json(ir.from_type)
+        and not ir.cardinality_mod == qlast.CardinalityModifier.Required
+    ):
+        card = _bounds_to_card(CB_ZERO, _card_to_bounds(card).upper)
+    return card
 
 
 def _is_ptr_or_self_ref(
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
@@ -537,12 +537,21 @@ def can_omit_optional_wrapper(
     # Our base json casts should all preserve nullity (instead of
     # turning it into an empty set), so allow passing through those
     # cases. This is mainly an optimization for passing globals to
-    # functions, where we need to convert a bunch of optoinal params
-    # to json.
+    # functions, where we need to convert a bunch of optional params
+    # to json, and for casting out of json there and in schema updates.
+    #
+    # (FIXME: This also works around an obscure INSERT bug in which
+    # inserting values into `id` that need optional wrappers break.
+    # Since user code can't specify `id` at all, this is low prio.)
     if (
         isinstance(ir_set.expr, irast.TypeCast)
-        and irtyputils.is_scalar(ir_set.expr.expr.typeref)
-        and irtyputils.is_json(ir_set.expr.to_type)
+        and ((
+            irtyputils.is_scalar(ir_set.expr.expr.typeref)
+            and irtyputils.is_json(ir_set.expr.to_type)
+        ) or (
+            irtyputils.is_json(ir_set.expr.expr.typeref)
+            and irtyputils.is_scalar(ir_set.expr.to_type)
+        ))
     ):
         return can_omit_optional_wrapper(
             ir_set.expr.expr,


Test patch:
diff --git a/tests/test_edgeql_ir_card_inference.py b/tests/test_edgeql_ir_card_inference.py
--- a/tests/test_edgeql_ir_card_inference.py
+++ b/tests/test_edgeql_ir_card_inference.py
@@ -984,3 +984,10 @@ def test_edgeql_ir_card_inference_111(self):
 % OK %
         MANY
         """
+
+    def test_edgeql_ir_card_inference_112(self):
+        """
+        select <str>to_json('null')
+% OK %
+        AT_MOST_ONE
+        """
Repository: edgedb/edgedb

Issue:
ISE when selecting generated alias type
- EdgeDB Version: 2.0-dev.6578+local

Steps to Reproduce:

`select`ing any type that EdgeDB generates from an alias (the alias type itself is fine) causes an ISE with no message:
```
select default::__AwardAlias2__winner;

InternalServerError:
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
```

Schema: https://github.com/edgedb/edgedb/blob/master/tests/schemas/cards.esdl



Discussion:

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
@@ -298,6 +298,13 @@ def compile_path(expr: qlast.Path, *, ctx: context.ContextLevel) -> irast.Set:
 
                 if (stype.get_expr_type(ctx.env.schema) is not None and
                         stype.get_name(ctx.env.schema) not in ctx.view_nodes):
+                    if not stype.get_expr(ctx.env.schema):
+                        raise errors.InvalidReferenceError(
+                            f"cannot refer to alias link helper type "
+                            f"'{stype.get_name(ctx.env.schema)}'",
+                            context=step.context,
+                        )
+
                     # This is a schema-level view, as opposed to
                     # a WITH-block or inline alias view.
                     stype = stmtctx.declare_view_from_schema(stype, ctx=ctx)


Test patch:
diff --git a/tests/test_edgeql_expr_aliases.py b/tests/test_edgeql_expr_aliases.py
--- a/tests/test_edgeql_expr_aliases.py
+++ b/tests/test_edgeql_expr_aliases.py
@@ -1096,3 +1096,13 @@ async def test_edgeql_aliases_backlinks_02(self):
             await self.con.execute("""
                 SELECT User.<owners;
             """)
+
+    async def test_edgeql_aliases_helper_01(self):
+        async with self.assertRaisesRegexTx(
+            edgedb.InvalidReferenceError,
+            "cannot refer to alias link helper type "
+            "'default::__AwardAlias2__winner'",
+        ):
+            await self.con.execute("""
+                SELECT __AwardAlias2__winner
+            """)
Repository: edgedb/edgedb

Issue:
`assert_exists` fails to trigger on single properties
```
edgedb> create type Foo { create property a -> str };
OK: CREATE TYPE
edgedb> insert Foo;
{default::Foo {id: 03be41f4-d891-11ec-aa0a-07e61661297e}}
edgedb> select Foo { a := assert_exists(.a) };
{default::Foo {a: {}}}
```



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
@@ -2271,14 +2271,16 @@ def process_set_as_existence_assertion(
             force=True,
             env=newctx.env,
         )
-        if ir_set.path_id.is_objtype_path():
-            pathctx.put_path_identity_var(
-                newctx.rel,
-                ir_arg_set.path_id,
-                set_expr,
-                force=True,
-                env=newctx.env,
-            )
+        other_aspect = (
+            'identity' if ir_set.path_id.is_objtype_path() else 'serialized')
+        pathctx.put_path_var(
+            newctx.rel,
+            ir_arg_set.path_id,
+            set_expr,
+            force=True,
+            aspect=other_aspect,
+            env=newctx.env,
+        )
 
     # It is important that we do not provide source, which could allow
     # fields on the object to be accessed without triggering the


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
@@ -5147,6 +5147,19 @@ async def test_edgeql_assert_exists_01(self):
                 ).name;
             """)
 
+    async def test_edgeql_assert_exists_02(self):
+        await self.con.execute('''
+            insert BooleanTest { name := "" }
+        ''')
+
+        async with self.assertRaisesRegexTx(
+            edgedb.CardinalityViolationError,
+            "assert_exists violation",
+        ):
+            await self.con.query_json("""
+                select BooleanTest { name, val := assert_exists(.val) }
+            """)
+
     async def test_edgeql_assert_exists_no_op(self):
         await self.con.query("""
             SELECT assert_exists(1)
Repository: edgedb/edgedb

Issue:
Missing source context in index cardinality check error
Original report: https://discord.com/channels/841451783728529451/849377751370432573/963429739505258568


Discussion:

Resolving patch:
diff --git a/edb/schema/indexes.py b/edb/schema/indexes.py
--- a/edb/schema/indexes.py
+++ b/edb/schema/indexes.py
@@ -310,7 +310,9 @@ def compile_expr_field(
                 raise errors.ResultCardinalityMismatchError(
                     f'possibly more than one element returned by '
                     f'the index expression where only singletons '
-                    f'are allowed')
+                    f'are allowed',
+                    context=value.qlast.context,
+                )
 
             if expr.irast.volatility != qltypes.Volatility.Immutable:
                 raise errors.SchemaDefinitionError(


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
@@ -11225,7 +11225,8 @@ async def test_edgeql_ddl_prop_alias(self):
     async def test_edgeql_ddl_index_01(self):
         with self.assertRaisesRegex(
             edgedb.ResultCardinalityMismatchError,
-            r"possibly more than one element returned by the index expression"
+            r"possibly more than one element returned by the index expression",
+            _line=4, _col=34
         ):
             await self.con.execute(r"""
                 CREATE TYPE Foo {
@@ -11237,7 +11238,8 @@ async def test_edgeql_ddl_index_01(self):
     async def test_edgeql_ddl_index_02(self):
         with self.assertRaisesRegex(
             edgedb.ResultCardinalityMismatchError,
-            r"possibly more than one element returned by the index expression"
+            r"possibly more than one element returned by the index expression",
+            _line=5, _col=34
         ):
             await self.con.execute(r"""
                 CREATE TYPE Foo {
@@ -11250,7 +11252,8 @@ async def test_edgeql_ddl_index_02(self):
     async def test_edgeql_ddl_index_03(self):
         with self.assertRaisesRegex(
             edgedb.ResultCardinalityMismatchError,
-            r"possibly more than one element returned by the index expression"
+            r"possibly more than one element returned by the index expression",
+            _line=5, _col=34
         ):
             await self.con.execute(r"""
                 CREATE TYPE Foo {
Repository: edgedb/edgedb

Issue:
Disallow globals with both computed and default expressions
Currently it is allowed to define a computed global with a default value. Since the default value will never be used, this should be disallowed to avoid confusion. 
```
create global test {
  using ('abc');
  set default := 'def';
}
```


Discussion:

Resolving patch:
diff --git a/edb/schema/globals.py b/edb/schema/globals.py
--- a/edb/schema/globals.py
+++ b/edb/schema/globals.py
@@ -228,6 +228,13 @@ def validate_object(
             default_type = default_expr.irast.stype
 
             source_context = self.get_attribute_source_context('default')
+
+            if is_computable:
+                raise errors.SchemaDefinitionError(
+                    f'computed globals may not have default values',
+                    context=source_context,
+                )
+
             if not default_type.assignment_castable_to(target, schema):
                 raise errors.SchemaDefinitionError(
                     f'default expression is of invalid type: '


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
@@ -6039,6 +6039,17 @@ async def test_edgeql_ddl_global_02(self):
                 create global foo -> float64 { set default := random(); };
             """)
 
+        async with self.assertRaisesRegexTx(
+            edgedb.SchemaDefinitionError,
+            "computed globals may not have default values",
+        ):
+            await self.con.execute("""
+                create global test {
+                    using ('abc');
+                    set default := 'def';
+                }
+            """)
+
     async def test_edgeql_ddl_global_03(self):
         await self.con.execute("""
             create global foo -> str;
Repository: edgedb/edgedb

Issue:
InvalidReferenceError when creating an alias
<!-- Please search existing issues to avoid creating duplicates. -->
- EdgeDB Version: rc4 (current master)
- OS Version: linux

Steps to Reproduce:

```
edgedb> create type Foo;
OK: CREATE TYPE
edgedb> create type Bar;
OK: CREATE TYPE
edgedb> alter type Foo create link bar := Bar{val := 42};
error: InvalidReferenceError: object type 'default::Bar' does not exist
  ┌─ query:1:35
  │
1 │ alter type Foo create link bar := Bar{val := 42};
  │                                   ^^^^^^^^^^^^^^ error
```

Notice that this is achieved in DDL, so it doesn't look like a typical case of SDL ordering that prevents visibility.


Discussion:

Resolving patch:
diff --git a/edb/schema/pointers.py b/edb/schema/pointers.py
--- a/edb/schema/pointers.py
+++ b/edb/schema/pointers.py
@@ -1211,6 +1211,17 @@ def _parse_computable(
                     context=srcctx,
                 )
 
+        if (
+            not isinstance(source, Pointer)
+            and not source.is_view(schema)  # type: ignore
+            and target.is_view(expression.irast.schema)
+        ):
+            raise errors.UnsupportedFeatureError(
+                f'including a shape on schema-defined computed links '
+                f'is not yet supported',
+                context=self.source_context,
+            )
+
         spec_target: Optional[
             Union[
                 s_types.TypeShell[s_types.Type],


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
@@ -6517,6 +6517,22 @@ async def test_edgeql_ddl_link_computable_01(self):
             }],
         )
 
+    async def test_edgeql_ddl_link_computable_02(self):
+        await self.con.execute('''
+            CREATE TYPE LinkTarget;
+        ''')
+
+        # TODO We want to actually support this, but until then we should
+        # have a decent error.
+        async with self.assertRaisesRegexTx(
+            edgedb.UnsupportedFeatureError,
+            r"including a shape on schema-defined computed links "
+            r"is not yet supported"
+        ):
+            await self.con.execute("""
+                CREATE TYPE X { CREATE LINK x := LinkTarget { z := 1 } };
+            """)
+
     async def test_edgeql_ddl_link_computable_circular_01(self):
         await self.con.execute('''\
             CREATE TYPE CompLinkCircular {
Repository: edgedb/edgedb

Issue:
Incorrect shape keys returned in JSON output
- EdgeDB Version: 2.0-dev.6695+local

Steps to Reproduce:

```
edgedb> select schema::Type {is_abstract} limit 10;
{
  schema::ObjectType {is_abstract: true},
  schema::ObjectType {is_abstract: true},
  schema::ObjectType {is_abstract: false},
  schema::ObjectType {is_abstract: true},
  schema::ObjectType {is_abstract: true},
  schema::ObjectType {is_abstract: true},
  schema::ObjectType {is_abstract: false},
  schema::ObjectType {is_abstract: false},
  schema::ObjectType {is_abstract: true},
  schema::ObjectType {is_abstract: true},
}
edgedb> \set output-format json
edgedb> select schema::Type {is_abstract} limit 10;
[
  {"abstract": true},
  {"abstract": true},
  {"abstract": false},
  {"abstract": true},
  {"abstract": true},
  {"abstract": true},
  {"abstract": false},
  {"abstract": false},
  {"abstract": true},
  {"abstract": true}
]
```

Seems this happens with any computed that's just an alias of another property:
```
edgedb> create type Test {
.......   create property val -> str;
.......   create property some_val := .val;
.......   create property other_val := str_upper(.val);
....... };
OK: CREATE TYPE
edgedb> insert Test {val := 'abc'};
[{"id": "67ec103c-fc79-11ec-ad40-63b51ba51ad6"}]
edgedb> select Test {some_val, other_val};
[{"other_val": "ABC", "val": "abc"}]
edgedb> \set output-format default
edgedb> select Test {some_val, other_val};
{default::Test {some_val: 'abc', other_val: 'ABC'}}
```


Discussion:
Looks like this a regression introduced by #3982

Resolving patch:
diff --git a/edb/schema/pointers.py b/edb/schema/pointers.py
--- a/edb/schema/pointers.py
+++ b/edb/schema/pointers.py
@@ -566,6 +566,9 @@ def get_nearest_defined(self, schema: s_schema.Schema) -> Pointer:
         while (
             ptrcls.get_is_derived(schema)
             and not ptrcls.get_defined_here(schema)
+            # schema defined computeds don't have the ephemeral defined_here
+            # set, but they do have expr set, so we check that also.
+            and not ptrcls.get_expr(schema)
             and (bases := ptrcls.get_bases(schema).objects(schema))
             and len(bases) == 1
             and bases[0].get_source(schema)


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
@@ -7301,3 +7301,12 @@ async def test_edgeql_select_card_blowup_01(self):
           })),
         };
         ''')
+
+    async def test_edgeql_shape_computed_alias_01(self):
+        # Issue #4023 had this producing an incorrect key name in JSON mode
+        await self.assert_query_result(
+            r'''
+            select schema::Type {is_abstract} filter .name = 'std::Object';
+            ''',
+            [{"is_abstract": True}]
+        )