Repository: geldata/gel
Pull request: Make sys:: and cfg:: fit propertly into the object model
Objects in `sys` and `cfg` are implemented using custom views.  These
views live in the `edgedbss` module and do not get correctly
incorporated into inheritence views for BaseObject (and even for other
abstract objects in the cfg hierarchy).

Move all of those views into `edgedbstd` with the names they ought to
have. Since we run all the schema DDL before running metaschema
scripts, we need to create dummy views in our DDL, which we do by
doing a `select *` from a dummy table that has the DDL run on it.
Then, when running metaschema, we replace those views with our real
ones.

Doing this means we need to take care to preserve the order of
columns, which is annoying but not hard.

Fixes #4491.

Problem statement:
Objects in `cfg` and `sys` are in a somewhat busted state
Most of types in `cfg` and `sys` are represented in the database as views that live in the `edgedbss` schema, and which are created in `metaschema.py`.

However the knowledge that they should live in `edgedbss` is somewhat inconsistent.
Duplicates of each of those types exist in `edgedbstd`, and those are used by `BaseObject`s views.
Some of the abstract types in `cfg`/`sys` have views created explicitly in `metaschema`, but some don't.

`cfg` and `sys` special cased in relctx to point at `edgedbss`.

This should all get rationalized, so that one version of each of these tables exists and is routed to in one place (pgsql/common.py, ideally).

What is the reason why these views are in `edgedbss` instead of just `edgedbstd`? Is this important?

Here are some of the bugs that result from this state:
```
edgedb> select cfg::ConfigObject;
edgedb error: InternalServerError: relation "edgedbss.734bd415-4670-11ed-88a5-6d9ebab1a5f7_t" does not exist
```

```
edgedb> select count(BaseObject[is cfg::AbstractConfig]);
[0]
edgedb> select count(cfg::AbstractConfig);
[3]
```

Hints from issue discussion:
> What is the reason why these views are in `edgedbss` instead of just `edgedbstd`? Is this important?

Mostly historical.  Ideally we should teach system DDL to special-case these and create in `edgedbstd` properly.

Commit message: Make sys:: and cfg:: fit propertly into the object model

Objects in `sys` and `cfg` are implemented using custom views.  These
views live in the `edgedbss` module and do not get correctly
incorporated into inheritence views for BaseObject (and even for other
abstract objects in the cfg hierarchy).

Move all of those views into `edgedbstd` with the names they ought to
have. Since we run all the schema DDL before running metaschema
scripts, we need to create dummy views in our DDL, which we do by
doing a `select *` from a dummy table that has the DDL run on it.
Then, when running metaschema, we replace those views with our real
ones.

Doing this means we need to take care to preserve the order of
columns, which is annoying but not hard.

Fixes #4491.

Currently objects in sys:: and cfg::, which

Patch to review:
diff --git a/edb/buildmeta.py b/edb/buildmeta.py
index f3b6e169da7..7785162873f 100644
--- a/edb/buildmeta.py
+++ b/edb/buildmeta.py
@@ -44,7 +44,7 @@
 
 
 # Increment this whenever the database layout or stdlib changes.
-EDGEDB_CATALOG_VERSION = 2023_02_23_00_00
+EDGEDB_CATALOG_VERSION = 2023_03_06_00_00
 EDGEDB_MAJOR_VERSION = 3
 
 
diff --git a/edb/pgsql/common.py b/edb/pgsql/common.py
index 23219204fcf..5f08354e500 100644
--- a/edb/pgsql/common.py
+++ b/edb/pgsql/common.py
@@ -255,7 +255,7 @@ def get_objtype_backend_name(
 ):
     if aspect is None:
         aspect = 'table'
-    if aspect not in {'table', 'inhview'} and not re.match(
+    if aspect not in {'table', 'inhview', 'dummy'} and not re.match(
             r'(source|target)-del-(def|imm)-(inl|otl)-(f|t)', aspect):
         raise ValueError(
             f'unexpected aspect for object type backend name: {aspect!r}')
@@ -270,7 +270,7 @@ def get_pointer_backend_name(id, module_name, *, catenate=False, aspect=None):
     if aspect is None:
         aspect = 'table'
 
-    if aspect not in ('table', 'index', 'inhview'):
+    if aspect not in ('table', 'index', 'inhview', 'dummy'):
         raise ValueError(
             f'unexpected aspect for pointer backend name: {aspect!r}')
 
diff --git a/edb/pgsql/compiler/dml.py b/edb/pgsql/compiler/dml.py
index 8606c13a012..53e8083926c 100644
--- a/edb/pgsql/compiler/dml.py
+++ b/edb/pgsql/compiler/dml.py
@@ -129,6 +129,11 @@ def init_dml_stmt(
     for typeref in typerefs:
         if typeref.union:
             continue
+        if (
+            isinstance(typeref.name_hint, sn.QualName)
+            and typeref.name_hint.module in ('sys', 'cfg')
+        ):
+            continue
         dml_cte, dml_rvar = gen_dml_cte(
             ir_stmt,
             range_rvar=range_rvar,
diff --git a/edb/pgsql/compiler/relctx.py b/edb/pgsql/compiler/relctx.py
index 31ddf17dc08..d63abdec4e1 100644
--- a/edb/pgsql/compiler/relctx.py
+++ b/edb/pgsql/compiler/relctx.py
@@ -1496,10 +1496,6 @@ def range_for_material_objtype(
             catenate=False,
         )
 
-        if typeref.name_hint.module in {'cfg', 'sys'} and include_descendants:
-            # Redirect all queries to schema tables to edgedbss
-            table_schema_name = 'edgedbss'
-
         relation = pgast.Relation(
             schemaname=table_schema_name,
             name=table_name,
@@ -1790,10 +1786,6 @@ def table_from_ptrref(
         ptr_info.table_name, aspect
     )
 
-    if ptrref.name.module in {'cfg', 'sys'}:
-        # Redirect all queries to schema tables to edgedbss
-        table_schema_name = 'edgedbss'
-
     typeref = ptrref.out_source if ptrref else None
     relation = pgast.Relation(
         schemaname=table_schema_name,
diff --git a/edb/pgsql/delta.py b/edb/pgsql/delta.py
index 979801aef65..39892d31c21 100644
--- a/edb/pgsql/delta.py
+++ b/edb/pgsql/delta.py
@@ -92,6 +92,11 @@
     from edb.schema import schema as s_schema
 
 
+# Modules where all the "types" in them are really just custom views
+# provided by metaschema.
+VIEW_MODULES = ('sys', 'cfg')
+
+
 def has_table(obj, schema):
     if isinstance(obj, s_objtypes.ObjectType):
         return not (
@@ -120,6 +125,16 @@ def has_table(obj, schema):
         )
 
 
+def is_cfg_view(
+    obj: so.Object,
+    schema: s_schema.Schema,
+) -> bool:
+    return (
+        isinstance(obj, (s_objtypes.ObjectType, s_pointers.Pointer))
+        and obj.get_name(schema).module in VIEW_MODULES
+    )
+
+
 def get_index_code(index_name: sn.Name) -> str:
     # HACK: currently this helper just hardcodes the SQL code necessary for
     # specific PG indexes, but this should be based on index definition.
@@ -264,7 +279,14 @@ def schedule_inhview_source_update(
             raise AssertionError(f"there is no {ctxcls} in context stack")
         assert isinstance(ctx.op, CompositeMetaCommand)
 
-        ctx.op.inhview_updates.add((ptr.get_source(schema), True))
+        src = ptr.get_source(schema)
+        if src and is_cfg_view(src, schema):
+            assert isinstance(src, s_sources.Source)
+            self.pgops.add(
+                CompositeMetaCommand._refresh_fake_cfg_view_cmd(
+                    src, schema, context))
+
+        ctx.op.inhview_updates.add((src, True))
         for anc in ptr.get_ancestors(schema).objects(schema):
             if src := anc.get_source(schema):
                 ctx.op.inhview_updates.add((src, False))
@@ -1982,6 +2004,9 @@ def constraint_is_effective(cls, schema, constraint):
         ):
             return False
 
+        elif is_cfg_view(subject, schema):
+            return False
+
         elif isinstance(subject, s_pointers.Pointer):
             if subject.generic(schema):
                 return True
@@ -2907,6 +2932,57 @@ def get_alter_table(
     def attach_alter_table(self, context):
         self._attach_multicommand(context, dbops.AlterTable)
 
+    @staticmethod
+    def _get_table_name(obj, schema) -> tuple[str, str]:
+        is_internal_view = is_cfg_view(obj, schema)
+        aspect = 'dummy' if is_internal_view else None
+        return common.get_backend_name(
+            schema, obj, catenate=False, aspect=aspect)
+
+    @classmethod
+    def _refresh_fake_cfg_view_cmd(
+        cls,
+        obj: CompositeObject,
+        schema: s_schema.Schema,
+        context: sd.CommandContext,
+    ) -> dbops.Command:
+        if not has_table(obj, schema):
+            return dbops.CommandGroup()
+        # Objects in sys and cfg are actually implemented by views
+        # that are defined in metaschema. The metaschema scripts run
+        # *after* the schema is instantiated, though, and we need to
+        # populate something *now* that can go into inhviews.
+        #
+        # The way we do this is by creating an actual concrete table
+        # with the suffix "_dummy" and then creating a view with the
+        # expected table name that simply `select *`s from the dummy
+        # table. Pointer creation on the type gets routed to the dummy
+        # table, so it has the right columns. Since the view `select
+        # *`s from the table, it also has the right columns, and can
+        # go into all of the inheritance views without any trouble.
+        #
+        # We refresh the fake config view before creating/updating
+        # inhviews associated with the object, since that corresponds
+        # with when it actually needs to happen by.
+        #
+        # Then, when we run the metaschema script, it simply swaps out
+        # this hacky view for the real one and everything works out fine.
+        orig_name = common.get_backend_name(schema, obj, catenate=False)
+        dummy_name = cls._get_table_name(obj, schema)
+        query = f'''
+            SELECT * FROM {q(*dummy_name)}
+        '''
+        view = dbops.View(name=orig_name, query=query)
+        return dbops.CreateView(view, or_replace=True)
+
+    def _refresh_fake_cfg_view(
+        self,
+        obj: CompositeObject,
+        schema: s_schema.Schema,
+        context: sd.CommandContext,
+    ) -> None:
+        self.pgops.add(self._refresh_fake_cfg_view_cmd(obj, schema, context))
+
     @classmethod
     def get_source_and_pointer_ctx(cls, schema, context):
         if context:
@@ -2936,15 +3012,11 @@ def _get_select_from(
 
         cols = []
 
-        if pg_schema not in ('edgedbss',):
-            cols.extend([
-                ('tableoid', 'tableoid', True),
-                ('xmin', 'xmin', True),
-                ('cmin', 'cmin', True),
-                ('xmax', 'xmax', True),
-                ('cmax', 'cmax', True),
-                ('ctid', 'ctid', True),
-            ])
+        special_cols = ['tableoid', 'xmin', 'cmin', 'xmax', 'cmax', 'ctid']
+        if not is_cfg_view(obj, schema):
+            cols.extend([(col, col, True) for col in special_cols])
+        else:
+            cols.extend([('NULL', col, False) for col in special_cols])
 
         if isinstance(obj, s_sources.Source):
             ptrs = dict(obj.get_pointers(schema).items(schema))
@@ -3094,6 +3166,9 @@ def update_base_inhviews_on_rebase(
         context: sd.CommandContext,
         obj: CompositeObject,
     ) -> None:
+        if is_cfg_view(obj, schema):
+            self._refresh_fake_cfg_view(obj, schema, context)
+
         bases = set(obj.get_bases(schema).objects(schema))
         orig_bases = set(obj.get_bases(orig_schema).objects(orig_schema))
 
@@ -3164,6 +3239,10 @@ def create_inhview(
         alter_ancestors: bool = True,
     ) -> None:
         assert has_table(obj, schema)
+
+        if is_cfg_view(obj, schema):
+            self._refresh_fake_cfg_view(obj, schema, context)
+
         inhview = self.get_inhview(schema, obj, exclude_ptrs=exclude_ptrs)
         self.pgops.add(dbops.CreateView(view=inhview))
         self.pgops.add(dbops.Comment(
@@ -3187,6 +3266,9 @@ def alter_inhview(
     ) -> None:
         assert has_table(obj, schema)
 
+        if is_cfg_view(obj, schema):
+            self._refresh_fake_cfg_view(obj, schema, context)
+
         inhview = self.get_inhview(
             schema,
             obj,
@@ -3507,8 +3589,9 @@ def _create_begin(
         objtype = self.scls
         if objtype.is_compound_type(schema) or objtype.get_is_derived(schema):
             return schema
-        new_table_name = common.get_backend_name(
-            schema, self.scls, catenate=False)
+
+        new_table_name = self._get_table_name(self.scls, schema)
+
         self.table_name = new_table_name
         columns: list[str] = []
 
@@ -3553,6 +3636,16 @@ def _alter_innards(
 
 class AlterObjectType(ObjectTypeMetaCommand,
                       adapts=s_objtypes.AlterObjectType):
+    def _alter_begin(
+        self,
+        schema: s_schema.Schema,
+        context: sd.CommandContext,
+    ) -> s_schema.Schema:
+        schema = super()._alter_begin(schema, context)
+        # We want to set this name up early, so children operations see it
+        self.table_name = self._get_table_name(self.scls, schema)
+        return schema
+
     def apply(
         self,
         schema: s_schema.Schema,
@@ -3564,9 +3657,6 @@ def apply(
 
         self.apply_scheduled_inhview_updates(schema, context)
 
-        self.table_name = common.get_backend_name(
-            schema, objtype, catenate=False)
-
         self._maybe_do_abstract_test(orig_schema, schema, context)
 
         if has_table(objtype, schema):
@@ -4627,7 +4717,7 @@ class LinkMetaCommand(PointerMetaCommand[s_links.Link]):
     def _create_table(
             cls, link, schema, context, conditional=False, create_bases=True,
             create_children=True):
-        new_table_name = common.get_backend_name(schema, link, catenate=False)
+        new_table_name = cls._get_table_name(link, schema)
 
         create_c = dbops.CommandGroup()
 
@@ -4757,8 +4847,7 @@ def _create_link(
             if ptr_stor_info.table_type == 'ObjectType':
                 cols = self.get_columns(
                     link, schema, None, sets_required)
-                table_name = common.get_backend_name(
-                    schema, objtype.scls, catenate=False)
+                table_name = objtype.op.table_name  # type: ignore
                 assert isinstance(objtype.op, CompositeMetaCommand)
                 objtype_alter_table = objtype.op.get_alter_table(
                     schema, context, manual=True)
@@ -4895,7 +4984,7 @@ def _create_begin(
         schema = super()._create_begin(schema, context)
 
         link = self.scls
-        self.table_name = common.get_backend_name(schema, link, catenate=False)
+        self.table_name = self._get_table_name(self.scls, schema)
 
         self._create_link(link, schema, orig_schema, context)
 
@@ -5015,6 +5104,16 @@ class AlterLinkOwned(LinkMetaCommand, adapts=s_links.AlterLinkOwned):
 
 
 class AlterLink(LinkMetaCommand, adapts=s_links.AlterLink):
+    def _alter_begin(
+        self,
+        schema: s_schema.Schema,
+        context: sd.CommandContext,
+    ) -> s_schema.Schema:
+        schema = super()._alter_begin(schema, context)
+        # We want to set this name up early, so children operations see it
+        self.table_name = self._get_table_name(self.scls, schema)
+        return schema
+
     def _alter_innards(
         self,
         schema: s_schema.Schema,
@@ -5096,7 +5195,7 @@ class PropertyMetaCommand(PointerMetaCommand[s_props.Property]):
     def _create_table(
             cls, prop, schema, context, conditional=False, create_bases=True,
             create_children=True):
-        new_table_name = common.get_backend_name(schema, prop, catenate=False)
+        new_table_name = cls._get_table_name(prop, schema)
 
         create_c = dbops.CommandGroup()
 
@@ -5257,6 +5356,7 @@ def _create_property(
                 (default := prop.get_default(schema))
                 and not prop.is_pure_computable(schema)
                 and not fills_required
+                and not is_cfg_view(src.scls, schema)  # sigh
                 # link properties use SQL defaults and shouldn't need
                 # us to do it explicitly (which is good, since
                 # _alter_pointer_optionality doesn't currently work on
@@ -5361,6 +5461,8 @@ def _create_begin(
 
         src = context.get(s_sources.SourceCommandContext)
 
+        self.table_name = self._get_table_name(prop, schema)
+
         self._create_property(prop, src, schema, orig_schema, context)
 
         return schema
@@ -5625,7 +5727,10 @@ def get_target_objs(self, link, schema):
             objs = {tgt}
         objs |= {
             x for obj in objs for x in obj.descendants(schema)}
-        return {obj for obj in objs if not obj.is_view(schema)}
+        return {
+            obj for obj in objs
+            if not obj.is_view(schema) and not is_cfg_view(obj, schema)
+        }
 
     def get_orphan_link_ancestors(self, link, schema):
         val = s_links.LinkSourceDeleteAction.DeleteTargetIfOrphan
@@ -6177,7 +6282,10 @@ def apply(
             source = link.get_source(eff_schema)
             target = link.get_target(eff_schema)
 
-            if not isinstance(source, s_objtypes.ObjectType):
+            if (
+                not isinstance(source, s_objtypes.ObjectType)
+                or is_cfg_view(source, eff_schema)
+            ):
                 continue
 
             if not isinstance(link_op, (CreateProperty, CreateLink)):
@@ -6263,6 +6371,9 @@ def apply(
                         all_affected_targets.add(descendant)
 
         for target in all_affected_targets:
+            if is_cfg_view(target, schema):
+                continue
+
             deferred_links = []
             deferred_inline_links = []
             links = []
@@ -6298,7 +6409,10 @@ def apply(
                     continue
 
                 source = link.get_source(schema)
-                if not source.is_material_object_type(schema):
+                if (
+                    not source.is_material_object_type(schema)
+                    or is_cfg_view(source, schema)
+                ):
                     continue
                 ptr_stor_info = types.get_pointer_storage_info(
                     link, schema=schema)
diff --git a/edb/pgsql/metaschema.py b/edb/pgsql/metaschema.py
index aa5296c007e..a1b1f15093a 100644
--- a/edb/pgsql/metaschema.py
+++ b/edb/pgsql/metaschema.py
@@ -62,7 +62,6 @@
 from . import common
 from . import compiler
 from . import dbops
-from . import delta
 from . import types
 from . import params
 
@@ -78,7 +77,13 @@
 
 DATABASE_ID_NAMESPACE = uuidgen.UUID('0e6fed66-204b-11e9-8666-cffd58a5240b')
 CONFIG_ID_NAMESPACE = uuidgen.UUID('a48b38fa-349b-11e9-a6be-4f337f82f5ad')
-CONFIG_ID = uuidgen.UUID('172097a4-39f4-11e9-b189-9321eb2f4b97')
+CONFIG_ID = {
+    None: uuidgen.UUID('172097a4-39f4-11e9-b189-9321eb2f4b97'),
+    qltypes.ConfigScope.INSTANCE: uuidgen.UUID(
+        '172097a4-39f4-11e9-b189-9321eb2f4b98'),
+    qltypes.ConfigScope.DATABASE: uuidgen.UUID(
+        '172097a4-39f4-11e9-b189-9321eb2f4b99'),
+}
 
 
 class DBConfigTable(dbops.Table):
@@ -4363,7 +4368,6 @@ async def bootstrap(
 ) -> None:
     cmds = [
         dbops.CreateSchema(name='edgedb'),
-        dbops.CreateSchema(name='edgedbss'),
         dbops.CreateSchema(name='edgedbpub'),
         dbops.CreateSchema(name='edgedbstd'),
         dbops.CreateSchema(name='edgedbsql'),
@@ -4507,9 +4511,11 @@ async def create_pg_extensions(conn: pgcon.PGConnection) -> None:
 }
 
 
-def tabname(schema: s_schema.Schema, obj: s_obj.Object) -> Tuple[str, str]:
+def tabname(
+    schema: s_schema.Schema, obj: s_obj.QualifiedObject
+) -> Tuple[str, str]:
     return (
-        'edgedbss',
+        'edgedbstd',
         common.get_backend_name(
             schema,
             obj,
@@ -4519,9 +4525,11 @@ def tabname(schema: s_schema.Schema, obj: s_obj.Object) -> Tuple[str, str]:
     )
 
 
-def inhviewname(schema: s_schema.Schema, obj: s_obj.Object) -> Tuple[str, str]:
+def inhviewname(
+    schema: s_schema.Schema, obj: s_obj.QualifiedObject
+) -> Tuple[str, str]:
     return (
-        'edgedbss',
+        'edgedbstd',
         common.get_backend_name(
             schema,
             obj,
@@ -4541,6 +4549,33 @@ def ptr_col_name(
     return psi.column_name  # type: ignore[no-any-return]
 
 
+def format_fields(
+    schema: s_schema.Schema,
+    obj: s_sources.Source,
+    fields: dict[str, str],
+) -> str:
+    """Format a dictionary of column mappings for database views
+
+    The reason we do it this way is because, since these views are
+    overwriting existing temporary views, we need to put all the
+    columns in the same order as the original view.
+    """
+    ptrs = [obj.getptr(schema, s_name.UnqualName(s)) for s in fields]
+    # Sort by UUID timestamp, except that source goes before target always
+    # so force that to sort first.
+    ptrs.sort(key=(
+        lambda p: (not p.is_link_source_property(schema), p.id.time)))
+
+    cols = []
+    for ptr in ptrs:
+        name = ptr.get_shortname(schema).name
+        val = fields[name]
+        sname = qi(ptr_col_name(schema, obj, name))
+        cols.append(f'            {val} AS {sname}')
+
+    return ',\n'.join(cols)
+
+
 def _generate_database_views(schema: s_schema.Schema) -> List[dbops.View]:
     Database = schema.get('sys::Database', type=s_objtypes.ObjectType)
     annos = Database.getptr(
@@ -4548,14 +4583,9 @@ def _generate_database_views(schema: s_schema.Schema) -> List[dbops.View]:
     int_annos = Database.getptr(
         schema, s_name.UnqualName('annotations__internal'), type=s_links.Link)
 
-    view_query = f'''
-        SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, Database, 'id'))},
-            (SELECT id FROM edgedb."_SchemaObjectType"
-                 WHERE name = 'sys::Database')
-                AS {qi(ptr_col_name(schema, Database, '__type__'))},
-            (CASE WHEN
+    view_fields = {
+        'id': "((d.description)->>'id')::uuid",
+        'internal': f"""(CASE WHEN
                 (edgedb.get_backend_capabilities()
                  & {int(params.BackendCapabilities.CREATE_DATABASE)}) != 0
              THEN
@@ -4566,16 +4596,16 @@ def _generate_database_views(schema: s_schema.Schema) -> List[dbops.View]:
                         {ql(defines.EDGEDB_SYSTEM_DB)})
                 )
              ELSE False END
-            )
-                AS {qi(ptr_col_name(schema, Database, 'internal'))},
-            (d.description)->>'name'
-                AS {qi(ptr_col_name(schema, Database, 'name'))},
-            (d.description)->>'name'
-                AS {qi(ptr_col_name(schema, Database, 'name__internal'))},
-            ARRAY[]::text[]
-                AS {qi(ptr_col_name(schema, Database, 'computed_fields'))},
-            ((d.description)->>'builtin')::bool
-                AS {qi(ptr_col_name(schema, Database, 'builtin'))}
+        )""",
+        'name': "(d.description)->>'name'",
+        'name__internal': "(d.description)->>'name'",
+        'computed_fields': 'ARRAY[]::text[]',
+        'builtin': "((d.description)->>'builtin')::bool",
+    }
+
+    view_query = f'''
+        SELECT
+            {format_fields(schema, Database, view_fields)}
         FROM
             pg_database dat
             CROSS JOIN LATERAL (
@@ -4588,16 +4618,16 @@ def _generate_database_views(schema: s_schema.Schema) -> List[dbops.View]:
             AND (d.description)->>'tenant_id' = edgedb.get_backend_tenant_id()
     '''
 
+    annos_link_fields = {
+        'source': "((d.description)->>'id')::uuid",
+        'target': "(annotations->>'id')::uuid",
+        'value': "(annotations->>'value')::text",
+        'owned': "(annotations->>'owned')::bool",
+    }
+
     annos_link_query = f'''
         SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, annos, 'source'))},
-            (annotations->>'id')::uuid
-                AS {qi(ptr_col_name(schema, annos, 'target'))},
-            (annotations->>'value')::text
-                AS {qi(ptr_col_name(schema, annos, 'value'))},
-            (annotations->>'owned')::bool
-                AS {qi(ptr_col_name(schema, annos, 'owned'))}
+            {format_fields(schema, annos, annos_link_fields)}
         FROM
             pg_database dat
             CROSS JOIN LATERAL (
@@ -4611,14 +4641,15 @@ def _generate_database_views(schema: s_schema.Schema) -> List[dbops.View]:
                 ) AS annotations
     '''
 
+    int_annos_link_fields = {
+        'source': "((d.description)->>'id')::uuid",
+        'target': "(annotations->>'id')::uuid",
+        'owned': "(annotations->>'owned')::bool",
+    }
+
     int_annos_link_query = f'''
         SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, int_annos, 'source'))},
-            (annotations->>'id')::uuid
-                AS {qi(ptr_col_name(schema, int_annos, 'target'))},
-            (annotations->>'owned')::bool
-                AS {qi(ptr_col_name(schema, int_annos, 'owned'))}
+            {format_fields(schema, int_annos, int_annos_link_fields)}
         FROM
             pg_database dat
             CROSS JOIN LATERAL (
@@ -4643,9 +4674,7 @@ def _generate_database_views(schema: s_schema.Schema) -> List[dbops.View]:
     views = []
     for obj, query in objects.items():
         tabview = dbops.View(name=tabname(schema, obj), query=query)
-        inhview = dbops.View(name=inhviewname(schema, obj), query=query)
         views.append(tabview)
-        views.append(inhview)
 
     return views
 
@@ -4664,17 +4693,15 @@ def _generate_extension_views(schema: s_schema.Schema) -> List[dbops.View]:
         catenate=False,
     )
 
-    view_query = f'''
-        SELECT
-            (e.value->>'id')::uuid
-                AS {qi(ptr_col_name(schema, ExtPkg, 'id'))},
-            (SELECT id FROM edgedb."_SchemaObjectType"
-                 WHERE name = 'sys::ExtensionPackage')
-                AS {qi(ptr_col_name(schema, ExtPkg, '__type__'))},
-            (e.value->>'name')
-                AS {qi(ptr_col_name(schema, ExtPkg, 'name'))},
-            (e.value->>'name__internal')
-                AS {qi(ptr_col_name(schema, ExtPkg, 'name__internal'))},
+    view_query_fields = {
+        'id': "(e.value->>'id')::uuid",
+        'name': "(e.value->>'name')",
+        'name__internal': "(e.value->>'name__internal')",
+        'script': "(e.value->>'script')",
+        'computed_fields': 'ARRAY[]::text[]',
+        'builtin': "(e.value->>'builtin')::bool",
+        'internal': "(e.value->>'internal')::bool",
+        'version': f'''
             (
                 (e.value->'version'->>'major')::int,
                 (e.value->'version'->>'minor')::int,
@@ -4688,15 +4715,12 @@ def _generate_extension_views(schema: s_schema.Schema) -> List[dbops.View]:
                     ARRAY[]::text[]
                 )
             )::{qt(ver_t)}
-                AS {qi(ptr_col_name(schema, ExtPkg, 'version'))},
-            (e.value->>'script')
-                AS {qi(ptr_col_name(schema, ExtPkg, 'script'))},
-            ARRAY[]::text[]
-                AS {qi(ptr_col_name(schema, ExtPkg, 'computed_fields'))},
-            (e.value->>'builtin')::bool
-                AS {qi(ptr_col_name(schema, ExtPkg, 'builtin'))},
-            (e.value->>'internal')::bool
-                AS {qi(ptr_col_name(schema, ExtPkg, 'internal'))}
+        ''',
+    }
+
+    view_query = f'''
+        SELECT
+            {format_fields(schema, ExtPkg, view_query_fields)}
         FROM
             jsonb_each(
                 edgedb.get_database_metadata(
@@ -4705,16 +4729,22 @@ def _generate_extension_views(schema: s_schema.Schema) -> List[dbops.View]:
             ) AS e
     '''
 
+    annos_link_fields = {
+        'source': "(e.value->>'id')::uuid",
+        'target': "(annotations->>'id')::uuid",
+        'value': "(annotations->>'value')::text",
+        'owned': "(annotations->>'owned')::bool",
+    }
+
+    int_annos_link_fields = {
+        'source': "(e.value->>'id')::uuid",
+        'target': "(annotations->>'id')::uuid",
+        'owned': "(annotations->>'owned')::bool",
+    }
+
     annos_link_query = f'''
         SELECT
-            (e.value->>'id')::uuid
-                AS {qi(ptr_col_name(schema, annos, 'source'))},
-            (annotations->>'id')::uuid
-                AS {qi(ptr_col_name(schema, annos, 'target'))},
-            (annotations->>'value')::text
-                AS {qi(ptr_col_name(schema, annos, 'value'))},
-            (annotations->>'is_owned')::bool
-                AS {qi(ptr_col_name(schema, annos, 'owned'))}
+            {format_fields(schema, annos, annos_link_fields)}
         FROM
             jsonb_each(
                 edgedb.get_database_metadata(
@@ -4729,12 +4759,7 @@ def _generate_extension_views(schema: s_schema.Schema) -> List[dbops.View]:
 
     int_annos_link_query = f'''
         SELECT
-            (e.value->>'id')::uuid
-                AS {qi(ptr_col_name(schema, int_annos, 'source'))},
-            (annotations->>'id')::uuid
-                AS {qi(ptr_col_name(schema, int_annos, 'target'))},
-            (annotations->>'is_owned')::bool
-                AS {qi(ptr_col_name(schema, int_annos, 'owned'))}
+            {format_fields(schema, int_annos, int_annos_link_fields)}
         FROM
             jsonb_each(
                 edgedb.get_database_metadata(
@@ -4756,9 +4781,7 @@ def _generate_extension_views(schema: s_schema.Schema) -> List[dbops.View]:
     views = []
     for obj, query in objects.items():
         tabview = dbops.View(name=tabname(schema, obj), query=query)
-        inhview = dbops.View(name=inhviewname(schema, obj), query=query)
         views.append(tabview)
-        views.append(inhview)
 
     return views
 
@@ -4791,33 +4814,23 @@ def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]:
         )
     '''
 
+    view_query_fields = {
+        'id': "((d.description)->>'id')::uuid",
+        'name': "(d.description)->>'name'",
+        'name__internal': "(d.description)->>'name'",
+        'superuser': f'{superuser}',
+        'abstract': 'False',
+        'is_derived': 'False',
+        'inherited_fields': 'ARRAY[]::text[]',
+        'computed_fields': 'ARRAY[]::text[]',
+        'builtin': "((d.description)->>'builtin')::bool",
+        'internal': 'False',
+        'password': "(d.description)->>'password_hash'",
+    }
+
     view_query = f'''
         SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, Role, 'id'))},
-            (SELECT id FROM edgedb."_SchemaObjectType"
-                 WHERE name = 'sys::Role')
-                AS {qi(ptr_col_name(schema, Role, '__type__'))},
-            (d.description)->>'name'
-                AS {qi(ptr_col_name(schema, Role, 'name'))},
-            (d.description)->>'name'
-                AS {qi(ptr_col_name(schema, Role, 'name__internal'))},
-            {superuser}
-                AS {qi(ptr_col_name(schema, Role, 'superuser'))},
-            False
-                AS {qi(ptr_col_name(schema, Role, 'abstract'))},
-            False
-                AS {qi(ptr_col_name(schema, Role, 'is_derived'))},
-            ARRAY[]::text[]
-                AS {qi(ptr_col_name(schema, Role, 'inherited_fields'))},
-            ARRAY[]::text[]
-                AS {qi(ptr_col_name(schema, Role, 'computed_fields'))},
-            ((d.description)->>'builtin')::bool
-                AS {qi(ptr_col_name(schema, Role, 'builtin'))},
-            False
-                AS {qi(ptr_col_name(schema, Role, 'internal'))},
-            (d.description)->>'password_hash'
-                AS {qi(ptr_col_name(schema, Role, 'password'))}
+            {format_fields(schema, Role, view_query_fields)}
         FROM
             pg_catalog.pg_roles AS a
             CROSS JOIN LATERAL (
@@ -4830,12 +4843,14 @@ def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]:
             AND (d.description)->>'tenant_id' = edgedb.get_backend_tenant_id()
     '''
 
+    member_of_link_query_fields = {
+        'source': "((d.description)->>'id')::uuid",
+        'target': "((md.description)->>'id')::uuid",
+    }
+
     member_of_link_query = f'''
         SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, member_of, 'source'))},
-            ((md.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, member_of, 'target'))}
+            {format_fields(schema, member_of, member_of_link_query_fields)}
         FROM
             pg_catalog.pg_roles AS a
             CROSS JOIN LATERAL (
@@ -4851,14 +4866,15 @@ def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]:
             ) AS md
     '''
 
+    bases_link_query_fields = {
+        'source': "((d.description)->>'id')::uuid",
+        'target': "((md.description)->>'id')::uuid",
+        'index': 'row_number() OVER (PARTITION BY a.oid ORDER BY m.roleid)',
+    }
+
     bases_link_query = f'''
         SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, bases, 'source'))},
-            ((md.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, bases, 'target'))},
-            row_number() OVER (PARTITION BY a.oid ORDER BY m.roleid)
-                AS {qi(ptr_col_name(schema, bases, 'index'))}
+            {format_fields(schema, bases, bases_link_query_fields)}
         FROM
             pg_catalog.pg_roles AS a
             CROSS JOIN LATERAL (
@@ -4876,12 +4892,7 @@ def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]:
 
     ancestors_link_query = f'''
         SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, ancestors, 'source'))},
-            ((md.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, ancestors, 'target'))},
-            row_number() OVER (PARTITION BY a.oid ORDER BY m.roleid)
-                AS {qi(ptr_col_name(schema, ancestors, 'index'))}
+            {format_fields(schema, ancestors, bases_link_query_fields)}
         FROM
             pg_catalog.pg_roles AS a
             CROSS JOIN LATERAL (
@@ -4897,16 +4908,16 @@ def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]:
             ) AS md
     '''
 
+    annos_link_fields = {
+        'source': "((d.description)->>'id')::uuid",
+        'target': "(annotations->>'id')::uuid",
+        'value': "(annotations->>'value')::text",
+        'owned': "(annotations->>'owned')::bool",
+    }
+
     annos_link_query = f'''
         SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, annos, 'source'))},
-            (annotations->>'id')::uuid
-                AS {qi(ptr_col_name(schema, annos, 'target'))},
-            (annotations->>'value')::text
-                AS {qi(ptr_col_name(schema, annos, 'value'))},
-            (annotations->>'owned')::bool
-                AS {qi(ptr_col_name(schema, annos, 'owned'))}
+            {format_fields(schema, annos, annos_link_fields)}
         FROM
             pg_catalog.pg_roles AS a
             CROSS JOIN LATERAL (
@@ -4922,14 +4933,15 @@ def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]:
                 ) AS annotations
     '''
 
+    int_annos_link_fields = {
+        'source': "((d.description)->>'id')::uuid",
+        'target': "(annotations->>'id')::uuid",
+        'owned': "(annotations->>'owned')::bool",
+    }
+
     int_annos_link_query = f'''
         SELECT
-            ((d.description)->>'id')::uuid
-                AS {qi(ptr_col_name(schema, int_annos, 'source'))},
-            (annotations->>'id')::uuid
-                AS {qi(ptr_col_name(schema, int_annos, 'target'))},
-            (annotations->>'owned')::bool
-                AS {qi(ptr_col_name(schema, int_annos, 'owned'))}
+            {format_fields(schema, int_annos, int_annos_link_fields)}
         FROM
             pg_catalog.pg_roles AS a
             CROSS JOIN LATERAL (
@@ -4957,9 +4969,7 @@ def _generate_role_views(schema: s_schema.Schema) -> List[dbops.View]:
     views = []
     for obj, query in objects.items():
         tabview = dbops.View(name=tabname(schema, obj), query=query)
-        inhview = dbops.View(name=inhviewname(schema, obj), query=query)
         views.append(tabview)
-        views.append(inhview)
 
     return views
 
@@ -4976,34 +4986,23 @@ def _generate_single_role_views(schema: s_schema.Schema) -> List[dbops.View]:
         schema, s_name.UnqualName('annotations'), type=s_links.Link)
     int_annos = Role.getptr(
         schema, s_name.UnqualName('annotations__internal'), type=s_links.Link)
+    view_query_fields = {
+        'id': "(json->>'id')::uuid",
+        'name': "json->>'name'",
+        'name__internal': "json->>'name'",
+        'superuser': 'True',
+        'abstract': 'False',
+        'is_derived': 'False',
+        'inherited_fields': 'ARRAY[]::text[]',
+        'computed_fields': 'ARRAY[]::text[]',
+        'builtin': 'True',
+        'internal': 'False',
+        'password': "json->>'password_hash'",
+    }
 
     view_query = f'''
         SELECT
-            (json->>'id')::uuid
-                AS {qi(ptr_col_name(schema, Role, 'id'))},
-            (SELECT id FROM edgedb."_SchemaObjectType"
-                 WHERE name = 'sys::Role')
-                AS {qi(ptr_col_name(schema, Role, '__type__'))},
-            json->>'name'
-                AS {qi(ptr_col_name(schema, Role, 'name'))},
-            json->>'name'
-                AS {qi(ptr_col_name(schema, Role, 'name__internal'))},
-            True
-                AS {qi(ptr_col_name(schema, Role, 'superuser'))},
-            False
-                AS {qi(ptr_col_name(schema, Role, 'abstract'))},
-            False
-                AS {qi(ptr_col_name(schema, Role, 'is_derived'))},
-            ARRAY[]::text[]
-                AS {qi(ptr_col_name(schema, Role, 'inherited_fields'))},
-            ARRAY[]::text[]
-                AS {qi(ptr_col_name(schema, Role, 'computed_fields'))},
-            True
-                AS {qi(ptr_col_name(schema, Role, 'builtin'))},
-            False
-                AS {qi(ptr_col_name(schema, Role, 'internal'))},
-            json->>'password_hash'
-                AS {qi(ptr_col_name(schema, Role, 'password'))}
+            {format_fields(schema, Role, view_query_fields)}
         FROM
             edgedbinstdata.instdata
         WHERE
@@ -5011,45 +5010,45 @@ def _generate_single_role_views(schema: s_schema.Schema) -> List[dbops.View]:
             AND json->>'tenant_id' = edgedb.get_backend_tenant_id()
     '''
 
+    member_of_link_query_fields = {
+        'source': "'00000000-0000-0000-0000-000000000000'::uuid",
+        'target': "'00000000-0000-0000-0000-000000000000'::uuid",
+    }
+
     member_of_link_query = f'''
         SELECT
-            '00000000-0000-0000-0000-000000000000'::uuid
-                AS {qi(ptr_col_name(schema, member_of, 'source'))},
-            '00000000-0000-0000-0000-000000000000'::uuid
-                AS {qi(ptr_col_name(schema, member_of, 'target'))}
+            {format_fields(schema, member_of, member_of_link_query_fields)}
         LIMIT 0
     '''
 
+    bases_link_query_fields = {
+        'source': "'00000000-0000-0000-0000-000000000000'::uuid",
+        'target': "'00000000-0000-0000-0000-000000000000'::uuid",
+        'index': "0::bigint",
+    }
+
     bases_link_query = f'''
         SELECT
-            '00000000-0000-0000-0000-000000000000'::uuid
-                AS {qi(ptr_col_name(schema, bases, 'source'))},
-            '00000000-0000-0000-0000-000000000000'::uuid
-                AS {qi(ptr_col_name(schema, bases, 'target'))},
-            0 AS {qi(ptr_col_name(schema, bases, 'index'))}
+            {format_fields(schema, bases, bases_link_query_fields)}
         LIMIT 0
     '''
 
     ancestors_link_query = f'''
         SELECT
-            '00000000-0000-0000-0000-000000000000'::uuid
-                AS {qi(ptr_col_name(schema, ancestors, 'source'))},
-            '00000000-0000-0000-0000-000000000000'::uuid
-                AS {qi(ptr_col_name(schema, ancestors, 'target'))},
-            0 AS {qi(ptr_col_name(schema, ancestors, 'index'))}
+            {format_fields(schema, ancestors, bases_link_query_fields)}
         LIMIT 0
     '''
 
+    annos_link_fields = {
+        'source': "(json->>'id')::uuid",
+        'target': "(annotations->>'id')::uuid",
+        'value': "(annotations->>'value')::text",
+        'owned': "(annotations->>'owned')::bool",
+    }
+
     annos_link_query = f'''
         SELECT
-            (json->>'id')::uuid
-                AS {qi(ptr_col_name(schema, annos, 'source'))},
-            (annotations->>'id')::uuid
-                AS {qi(ptr_col_name(schema, annos, 'target'))},
-            (annotations->>'value')::text
-                AS {qi(ptr_col_name(schema, annos, 'value'))},
-            (annotations->>'owned')::bool
-                AS {qi(ptr_col_name(schema, annos, 'owned'))}
+            {format_fields(schema, annos, annos_link_fields)}
         FROM
             edgedbinstdata.instdata
             CROSS JOIN LATERAL
@@ -5061,14 +5060,15 @@ def _generate_single_role_views(schema: s_schema.Schema) -> List[dbops.View]:
             AND json->>'tenant_id' = edgedb.get_backend_tenant_id()
     '''
 
+    int_annos_link_fields = {
+        'source': "(json->>'id')::uuid",
+        'target': "(annotations->>'id')::uuid",
+        'owned': "(annotations->>'owned')::bool",
+    }
+
     int_annos_link_query = f'''
         SELECT
-            (json->>'id')::uuid
-                AS {qi(ptr_col_name(schema, int_annos, 'source'))},
-            (annotations->>'id')::uuid
-                AS {qi(ptr_col_name(schema, int_annos, 'target'))},
-            (annotations->>'owned')::bool
-                AS {qi(ptr_col_name(schema, int_annos, 'owned'))}
+            {format_fields(schema, int_annos, int_annos_link_fields)}
         FROM
             edgedbinstdata.instdata
             CROSS JOIN LATERAL
@@ -5092,9 +5092,7 @@ def _generate_single_role_views(schema: s_schema.Schema) -> List[dbops.View]:
     views = []
     for obj, query in objects.items():
         tabview = dbops.View(name=tabname(schema, obj), query=query)
-        inhview = dbops.View(name=inhviewname(schema, obj), query=query)
         views.append(tabview)
-        views.append(inhview)
 
     return views
 
@@ -5105,25 +5103,19 @@ def _generate_schema_ver_views(schema: s_schema.Schema) -> List[dbops.View]:
         type=s_objtypes.ObjectType,
     )
 
+    view_fields = {
+        'id': "(v.value->>'id')::uuid",
+        'name': "(v.value->>'name')",
+        'name__internal': "(v.value->>'name')",
+        'version': "(v.value->>'version')::uuid",
+        'builtin': "(v.value->>'builtin')::bool",
+        'internal': "(v.value->>'internal')::bool",
+        'computed_fields': 'ARRAY[]::text[]',
+    }
+
     view_query = f'''
         SELECT
-            (v.value->>'id')::uuid
-                AS {qi(ptr_col_name(schema, Ver, 'id'))},
-            (SELECT id FROM edgedb."_SchemaObjectType"
-                 WHERE name = 'sys::GlobalSchemaVersion')
-                AS {qi(ptr_col_name(schema, Ver, '__type__'))},
-            (v.value->>'name')
-                AS {qi(ptr_col_name(schema, Ver, 'name'))},
-            (v.value->>'name')
-                AS {qi(ptr_col_name(schema, Ver, 'name__internal'))},
-            (v.value->>'version')::uuid
-                AS {qi(ptr_col_name(schema, Ver, 'version'))},
-            (v.value->>'builtin')::bool
-                AS {qi(ptr_col_name(schema, Ver, 'builtin'))},
-            (v.value->>'internal')::bool
-                AS {qi(ptr_col_name(schema, Ver, 'internal'))},
-            ARRAY[]::text[]
-                AS {qi(ptr_col_name(schema, Ver, 'computed_fields'))}
+            {format_fields(schema, Ver, view_fields)}
         FROM
             jsonb_each(
                 edgedb.get_database_metadata(
@@ -5139,9 +5131,7 @@ def _generate_schema_ver_views(schema: s_schema.Schema) -> List[dbops.View]:
     views = []
     for obj, query in objects.items():
         tabview = dbops.View(name=tabname(schema, obj), query=query)
-        inhview = dbops.View(name=inhviewname(schema, obj), query=query)
         views.append(tabview)
-        views.append(inhview)
 
     return views
 
@@ -5203,9 +5193,6 @@ def _generate_schema_alias_view(
         catenate=False,
     )
 
-    if module == 'sys' and not obj.get_abstract(schema):
-        bn = ('edgedbss', bn[1])
-
     targets = []
 
     if isinstance(obj, s_links.Link):
@@ -5805,17 +5792,6 @@ def get_support_views(
         for tn, q in cfg_views
     ])
 
-    abstract_conf = delta.CompositeMetaCommand.get_inhview(
-        schema,
-        schema.get('cfg::AbstractConfig', type=s_objtypes.ObjectType),
-        exclude_self=True,
-        pg_schema='edgedbss',
-    )
-
-    commands.add_command(
-        dbops.CreateView(abstract_conf, or_replace=True)
-    )
-
     for dbview in _generate_database_views(schema):
         commands.add_command(dbops.CreateView(dbview, or_replace=True))
 
@@ -6352,7 +6328,6 @@ def _generate_config_type_view(
 
     _memo.add(stype)
 
-    tname = stype.get_name(schema)
     views = []
 
     sources = []
@@ -6421,7 +6396,7 @@ def _generate_config_type_view(
     single_links = []
     multi_links = []
     multi_props = []
-    target_cols = []
+    target_cols: dict[s_pointers.Pointer, str] = {}
     where = ''
 
     path_steps = [p.get_shortname(schema).name for p, _ in path]
@@ -6469,7 +6444,7 @@ def _generate_config_type_view(
                     f'{pp_cast(f"{sval}->{ql(pn)}")}'
                     f' AS {qi(pp_col)}')
 
-                target_cols.append(extract_col)
+                target_cols[pp] = extract_col
 
                 constraints = pp.get_constraints(schema).objects(schema)
                 if any(c.issubclass(schema, exc) for c in constraints):
@@ -6486,26 +6461,18 @@ def _generate_config_type_view(
         sources.append(final_keysource)
 
         key_expr = 'k.key'
-        target_cols.append(f'{key_expr} AS id')
-
-        where = f'{key_expr} IS NOT NULL'
 
-        target_cols.append(textwrap.dedent(f'''\
-            (SELECT id
-            FROM edgedb."_SchemaObjectType"
-            WHERE name = 'cfg::' || ({sval}->>'_tname')) AS __type__'''))
+        tname = stype.get_name(schema).name
+        where = f"{key_expr} IS NOT NULL AND ({sval}->>'_tname') = {ql(tname)}"
 
     else:
-        key_expr = f"'{CONFIG_ID}'::uuid"
-
-        target_cols.extend([
-            f"{key_expr} AS id",
-            f'(SELECT id FROM edgedb."_SchemaObjectType" '
-            f"WHERE name = {ql(str(tname))}) AS __type__",
-        ])
+        key_expr = f"'{CONFIG_ID[scope]}'::uuid"
 
         key_components = []
 
+    id_ptr = stype.getptr(schema, s_name.UnqualName('id'))
+    target_cols[id_ptr] = f'{key_expr} AS id'
+
     for link in single_links:
         link_name = link.get_shortname(schema).name
         link_type = link.get_target(schema)
@@ -6552,11 +6519,17 @@ def _generate_config_type_view(
             target_key_components = key_components + [f'k{link_name}.key']
 
         target_key = _build_key_expr(target_key_components)
-        target_cols.append(f'({target_key}) AS {qi(link_col)}')
+        target_cols[link] = f'({target_key}) AS {qi(link_col)}'
 
         views.extend(target_views)
 
-    target_cols_str = ',\n'.join(target_cols)
+    # You can't change the order of a postgres view... so
+    # sort them by uuid timestamp to keep them in order
+    target_cols_sorted = sorted(
+        target_cols.items(), key=lambda p: p[0].id.time
+    )
+
+    target_cols_str = ',\n'.join([x for _, x in target_cols_sorted if x])
 
     fromlist = ',\n'.join(f'LATERAL {s}' for s in sources)
 
@@ -6571,7 +6544,6 @@ def _generate_config_type_view(
         target_query += f'\nWHERE\n    {where}'
 
     views.append((tabname(schema, stype), target_query))
-    views.append((inhviewname(schema, stype), target_query))
 
     for link in multi_links:
         target_sources = list(sources)
@@ -6635,7 +6607,6 @@ def _generate_config_type_view(
             ''')
 
         views.append((tabname(schema, link), link_query))
-        views.append((inhviewname(schema, link), link_query))
 
     for prop, pp_cast in multi_props:
         target_sources = list(sources)
@@ -6657,7 +6628,6 @@ def _generate_config_type_view(
         ''')
 
         views.append((tabname(schema, prop), link_query))
-        views.append((inhviewname(schema, prop), link_query))
 
     return views, exclusive_props
 
diff --git a/edb/schema/objtypes.py b/edb/schema/objtypes.py
index 58468177996..d1e2666a3bf 100644
--- a/edb/schema/objtypes.py
+++ b/edb/schema/objtypes.py
@@ -125,8 +125,8 @@ def is_free_object_type(self, schema: s_schema.Schema) -> bool:
 
     def is_fake_object_type(self, schema: s_schema.Schema) -> bool:
         return (
-            self.get_name(schema).module == 'cfg'
-            or self.is_free_object_type(schema)
+            # self.get_name(schema).module == 'cfg' or
+            self.is_free_object_type(schema)
         )
 
     def is_material_object_type(self, schema: s_schema.Schema) -> bool:
diff --git a/edb/server/bootstrap.py b/edb/server/bootstrap.py
index 102ad16cc85..7477a58487e 100644
--- a/edb/server/bootstrap.py
+++ b/edb/server/bootstrap.py
@@ -56,6 +56,7 @@
 from edb.server import compiler as edbcompiler
 from edb.server import defines as edbdef
 from edb.server import pgcluster
+from edb.server import pgcon
 
 from edb.pgsql import common as pg_common
 from edb.pgsql import dbops
@@ -71,8 +72,6 @@
 if TYPE_CHECKING:
     import uuid
 
-    from edb.server import pgcon
-
 
 logger = logging.getLogger('edb.server')
 
@@ -1774,6 +1773,11 @@ async def _bootstrap(ctx: BootstrapContext) -> None:
         else:
             tpl_ctx = ctx
 
+        # Some of the views need access to the _edgecon_state table,
+        # so set it up.
+        tmp_table_query = pgcon.SETUP_TEMP_TABLE_SCRIPT
+        await _execute(tpl_ctx.conn, tmp_table_query)
+
         await _populate_misc_instance_data(tpl_ctx)
 
         stdlib, config_spec, compiler = await _init_stdlib(
diff --git a/edb/server/pgcon/__init__.py b/edb/server/pgcon/__init__.py
index 862bcf2acf9..6956436184f 100644
--- a/edb/server/pgcon/__init__.py
+++ b/edb/server/pgcon/__init__.py
@@ -26,7 +26,7 @@
     BackendCatalogNameError,
 )
 
-from .pgcon import connect, PGConnection
+from .pgcon import connect, PGConnection, SETUP_TEMP_TABLE_SCRIPT
 
 __all__ = (
     'connect',
@@ -35,4 +35,5 @@
     'BackendConnectionError',
     'BackendPrivilegeError',
     'BackendCatalogNameError',
+    'SETUP_TEMP_TABLE_SCRIPT',
 )
diff --git a/edb/server/pgcon/__init__.pyi b/edb/server/pgcon/__init__.pyi
index ecd654a8052..8590ae9f134 100644
--- a/edb/server/pgcon/__init__.pyi
+++ b/edb/server/pgcon/__init__.pyi
@@ -104,3 +104,6 @@ class PGConnection:
 
     def get_server_parameter_status(self, parameter: str) -> Optional[str]:
         ...
+
+
+SETUP_TEMP_TABLE_SCRIPT: str
diff --git a/edb/server/pgcon/pgcon.pyx b/edb/server/pgcon/pgcon.pyx
index e7534fe20c3..69d92b340d5 100644
--- a/edb/server/pgcon/pgcon.pyx
+++ b/edb/server/pgcon/pgcon.pyx
@@ -108,6 +108,16 @@ cdef object EMPTY_SQL_STATE = json.dumps({}).encode('utf-8')
 cdef object logger = logging.getLogger('edb.server')
 
 
+SETUP_TEMP_TABLE_SCRIPT = '''
+        CREATE TEMPORARY TABLE _edgecon_state (
+            name text NOT NULL,
+            value jsonb NOT NULL,
+            type text NOT NULL CHECK(
+                type = 'C' OR type = 'B'),
+            UNIQUE(name, type)
+        );
+'''
+
 def _build_init_con_script(*, check_pg_is_in_recovery: bool) -> bytes:
     if check_pg_is_in_recovery:
         pg_is_in_recovery = ('''
@@ -133,13 +143,7 @@ def _build_init_con_script(*, check_pg_is_in_recovery: bool) -> bytes:
     return textwrap.dedent(f'''
         {pg_is_in_recovery}
 
-        CREATE TEMPORARY TABLE _edgecon_state (
-            name text NOT NULL,
-            value jsonb NOT NULL,
-            type text NOT NULL CHECK(
-                type = 'C' OR type = 'B'),
-            UNIQUE(name, type)
-        );
+        {SETUP_TEMP_TABLE_SCRIPT}
 
         PREPARE _clear_state AS
             DELETE FROM _edgecon_state;
diff --git a/tests/test_edgeql_introspection.py b/tests/test_edgeql_introspection.py
index 60d5ac20b83..5092d2affdb 100644
--- a/tests/test_edgeql_introspection.py
+++ b/tests/test_edgeql_introspection.py
@@ -1532,3 +1532,28 @@ async def test_edgeql_introspection_reverse_03(self):
         ''')
         count1 = res[0].z
         self.assertFalse(all(row.z == count1 for row in res))
+
+    async def test_edgeql_introspection_cfg_objects_01(self):
+        await self.assert_query_result(
+            r'''
+                SELECT count(sys::Database)
+                  = count(BaseObject[is sys::Database])
+            ''',
+            [True],
+        )
+
+        await self.assert_query_result(
+            r'''
+                SELECT count(cfg::AbstractConfig)
+                  = count(BaseObject[is cfg::AbstractConfig])
+            ''',
+            [True],
+        )
+
+        await self.assert_query_result(
+            r'''
+                SELECT count(cfg::ConfigObject)
+                  = count(BaseObject[is cfg::ConfigObject])
+            ''',
+            [True],
+        )


Code review comments:
diff_hunk: @@ -125,8 +125,8 @@ def is_free_object_type(self, schema: s_schema.Schema) -> bool:
 
     def is_fake_object_type(self, schema: s_schema.Schema) -> bool:
         return (
-            self.get_name(schema).module == 'cfg'
-            or self.is_free_object_type(schema)
+            # self.get_name(schema).module == 'cfg' or
path: edb/schema/objtypes.py
text: @user1:
Is this intended?

@author:
Well, it should have been deleted, not commented out, but yeah